<?php
// /EDENrms/ajax/save_student_plan.php
// Saves the chosen plan (one-time or installments) + plan discount for a student.

header('Content-Type: application/json');

require_once __DIR__ . '/../includes/db.php'; // $conn (mysqli)
mysqli_set_charset($conn, 'utf8mb4');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

function ensure_tables(mysqli $c){
  // student_fee_plans: one row per student (latest selected plan)
  $c->query("
    CREATE TABLE IF NOT EXISTS student_fee_plans (
      id INT AUTO_INCREMENT PRIMARY KEY,
      student_id INT NOT NULL,
      fee_plan_id INT NULL,                 -- references payment_plans.id (null for one-time)
      plan_type VARCHAR(20) NOT NULL,       -- 'one' | 'inst'
      plan_discount_lkr DOUBLE DEFAULT 0,   -- absolute LKR discount selected
      discount_id INT NULL,                 -- optional: course_discounts.id
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      UNIQUE KEY uniq_student (student_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");

  // A per-student snapshot of installments (exact rows shown during registration)
  $c->query("
    CREATE TABLE IF NOT EXISTS student_installments (
      id INT AUTO_INCREMENT PRIMARY KEY,
      student_id INT NOT NULL,
      sort_order INT NOT NULL DEFAULT 0,
      installment_no INT NOT NULL,
      course_fee_lkr DOUBLE DEFAULT 0,
      registration_fee_lkr DOUBLE DEFAULT 0,
      certificate_fee_usd DOUBLE DEFAULT 0,
      due_date DATE NULL,
      KEY idx_student (student_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");
}

try {
  $student_id   = (int)($_POST['student_id'] ?? 0);
  $plan_json    = $_POST['selected_plan'] ?? ($_POST['selected_plan_json'] ?? '');
  if ($student_id <= 0 || $plan_json === '') {
    http_response_code(400); echo json_encode(['ok'=>false,'error'=>'student_id and selected_plan required']); exit;
  }

  $plan = json_decode($plan_json, true);
  if (!is_array($plan)) { http_response_code(400); echo json_encode(['ok'=>false,'error'=>'Invalid selected_plan JSON']); exit; }

  ensure_tables($conn);

  $type     = ($plan['type'] ?? '') === 'one' ? 'one' : 'inst';
  $feePlan  = isset($plan['plan_id']) && is_numeric($plan['plan_id']) ? (int)$plan['plan_id'] : null; // null for one-time
  $discLkr  = (float)($plan['plan_discount_lkr'] ?? 0);
  $discId   = isset($plan['discount_id']) && is_numeric($plan['discount_id']) ? (int)$plan['discount_id'] : null;
  $rows     = is_array($plan['installments'] ?? null) ? $plan['installments'] : [];

  $conn->begin_transaction();

  // Upsert student_fee_plans
  $sql = "INSERT INTO student_fee_plans (student_id, fee_plan_id, plan_type, plan_discount_lkr, discount_id)
          VALUES (?,?,?,?,?)
          ON DUPLICATE KEY UPDATE fee_plan_id=VALUES(fee_plan_id),
                                  plan_type=VALUES(plan_type),
                                  plan_discount_lkr=VALUES(plan_discount_lkr),
                                  discount_id=VALUES(discount_id)";
  $st = $conn->prepare($sql);
  $st->bind_param('iisdi', $student_id, $feePlan, $type, $discLkr, $discId);
  $st->execute();
  $st->close();

  // Replace snapshot of installments for the student
  $del = $conn->prepare("DELETE FROM student_installments WHERE student_id=?");
  $del->bind_param('i',$student_id); $del->execute(); $del->close();

  if ($rows) {
    $ins = $conn->prepare("INSERT INTO student_installments
      (student_id, sort_order, installment_no, course_fee_lkr, registration_fee_lkr, certificate_fee_usd, due_date)
      VALUES (?,?,?,?,?,?,?)");

    $i = 0;
    foreach ($rows as $r) {
      $i++;
      $no = (int)($r['installment_no'] ?? $r['no'] ?? $i);
      $c  = (float)($r['course_fee_lkr'] ?? 0);
      $rg = (float)($r['registration_fee_lkr'] ?? 0);
      $u  = (float)($r['certificate_fee_usd'] ?? 0);
      $dd = isset($r['due_date']) && $r['due_date'] !== '' ? $r['due_date'] : null;
      $ins->bind_param('iiiddis', $student_id, $i, $no, $c, $rg, $u, $dd);
      $ins->execute();
    }
    $ins->close();
  }

  $conn->commit();
  echo json_encode(['ok'=>true]);
} catch (Throwable $e) {
  try{ $conn->rollback(); }catch(Throwable $e2){}
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
