<?php
header('Content-Type: application/json; charset=utf-8');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost","root","","edencampus"); $mysqli->set_charset("utf8mb4");

$student_id = (int)($_POST['student_id'] ?? 0);
$plan_id    = (int)($_POST['plan_id'] ?? 0);
$data_json  = $_POST['data'] ?? '';
if ($student_id<=0 || !$data_json) { echo json_encode(['ok'=>false,'error'=>'Bad input']); exit; }
$rows = json_decode($data_json, true);
if (!is_array($rows) || !count($rows)) { echo json_encode(['ok'=>false,'error'=>'No rows']); exit; }

$mysqli->query("CREATE TABLE IF NOT EXISTS student_installments (
  id INT AUTO_INCREMENT PRIMARY KEY,
  student_id INT NOT NULL,
  plan_id INT DEFAULT NULL,
  installment_no INT NOT NULL,
  course_fee_lkr DECIMAL(10,2) DEFAULT 0,
  registration_fee_lkr DECIMAL(10,2) DEFAULT 0,
  certificate_fee_usd DECIMAL(10,2) DEFAULT 0,
  due_date DATE NULL,
  UNIQUE KEY stu_inst_unique (student_id, installment_no)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

$mysqli->begin_transaction();
$del = $mysqli->prepare("DELETE FROM student_installments WHERE student_id=?");
$del->bind_param("i",$student_id); $del->execute(); $del->close();

$ins = $mysqli->prepare("INSERT INTO student_installments
  (student_id, plan_id, installment_no, course_fee_lkr, registration_fee_lkr, certificate_fee_usd, due_date)
  VALUES (?,?,?,?,?,?,?)");
foreach ($rows as $r) {
  $no = (int)($r['installment_no'] ?? 0);
  $c  = (float)($r['course_fee_lkr'] ?? 0);
  $rg = (float)($r['registration_fee_lkr'] ?? 0);
  $cu = (float)($r['certificate_fee_usd'] ?? 0);
  $dd = ($r['due_date'] ?? null);
  $ins->bind_param("iiiddds", $student_id, $plan_id, $no, $c, $rg, $cu, $dd);
  $ins->execute();
}
$ins->close();
$mysqli->commit();
echo json_encode(['ok'=>true]);
