<?php
// pages/payment_api.php
// API for Standard, Installment, and DB-driven Discount Options.

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

/* -------- helpers -------- */
function ensure_schema(mysqli $c){
  // base plans (standard + installment container)
  $c->query("
    CREATE TABLE IF NOT EXISTS payment_plans (
      id INT AUTO_INCREMENT PRIMARY KEY,
      course_id INT NOT NULL,
      plan_type VARCHAR(20) NOT NULL,     /* standard | installment */
      plan_name VARCHAR(100) DEFAULT NULL,
      course_fee_lkr DOUBLE DEFAULT 0,    /* used by standard */
      registration_fee_lkr DOUBLE DEFAULT 0,
      certificate_fee_usd DOUBLE DEFAULT 0,
      UNIQUE KEY uniq_course_plan (course_id, plan_type)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");

  // installment rows
  $c->query("
    CREATE TABLE IF NOT EXISTS installments (
      id INT AUTO_INCREMENT PRIMARY KEY,
      plan_id INT NOT NULL,
      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_plan (plan_id),
      CONSTRAINT fk_plan_inst FOREIGN KEY (plan_id) REFERENCES payment_plans(id)
        ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");

  // course-level discount options (used by both one-time & installments)
  $c->query("
    CREATE TABLE IF NOT EXISTS course_discounts (
      id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      course_id INT UNSIGNED NOT NULL,
      code VARCHAR(50) NOT NULL,
      label VARCHAR(191) NOT NULL,
      amount_lkr DECIMAL(12,2) NOT NULL DEFAULT 0,
      is_default TINYINT(1) NOT NULL DEFAULT 0,
      status ENUM('active','inactive') NOT NULL DEFAULT 'active',
      sort_order INT NOT NULL DEFAULT 0,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      INDEX idx_cd_course (course_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");
}

function upsert_standard_plan(mysqli $c, int $course_id, string $name, float $cfee, float $rfee, float $ufee){
  $s=$c->prepare("SELECT id FROM payment_plans WHERE course_id=? AND plan_type='standard' LIMIT 1");
  $s->bind_param('i',$course_id); $s->execute();
  $row=$s->get_result()->fetch_assoc(); $s->close();

  if($row){
    $id=(int)$row['id'];
    $u=$c->prepare("UPDATE payment_plans
                    SET plan_name=?, course_fee_lkr=?, registration_fee_lkr=?, certificate_fee_usd=?
                    WHERE id=?");
    $u->bind_param('sdddi',$name,$cfee,$rfee,$ufee,$id);
    $u->execute(); $u->close();
    return $id;
  } else {
    $i=$c->prepare("INSERT INTO payment_plans
      (course_id, plan_type, plan_name, course_fee_lkr, registration_fee_lkr, certificate_fee_usd)
      VALUES (?, 'standard', ?, ?, ?, ?)");
    $i->bind_param('isddd',$course_id,$name,$cfee,$rfee,$ufee);
    $i->execute(); $id=$i->insert_id; $i->close();
    return $id;
  }
}

ensure_schema($conn);

$action = $_GET['action'] ?? ($_POST['action'] ?? '');

try {

  /* ----------- STANDARD: GET ----------- */
  if ($action === 'get_simple_plan') {
    $course_id = (int)($_GET['course_id'] ?? 0);
    $type = $_GET['plan_type'] ?? '';
    if (!$course_id || $type!=='standard') {
      http_response_code(400); echo "course_id and plan_type=standard required"; exit;
    }

    $s=$conn->prepare("SELECT id, plan_name, course_fee_lkr, registration_fee_lkr, certificate_fee_usd
                       FROM payment_plans WHERE course_id=? AND plan_type='standard' LIMIT 1");
    $s->bind_param('i',$course_id); $s->execute();
    $row=$s->get_result()->fetch_assoc(); $s->close();

    $resp = $row ? [
      'plan_id'=>(int)$row['id'],
      'plan_name'=>$row['plan_name'] ?? 'Standard',
      'course_fee_lkr'=>(float)$row['course_fee_lkr'],
      'registration_fee_lkr'=>(float)$row['registration_fee_lkr'],
      'certificate_fee_usd'=>(float)$row['certificate_fee_usd'],
    ] : [
      'plan_id'=>0,'plan_name'=>'Standard','course_fee_lkr'=>0,'registration_fee_lkr'=>0,'certificate_fee_usd'=>0
    ];

    header('Content-Type: application/json'); echo json_encode($resp); exit;
  }

  /* ----------- STANDARD: SAVE ----------- */
  if ($action === 'save_simple_plan') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (!is_array($data)) { http_response_code(400); echo "Invalid JSON"; exit; }

    $course_id = (int)($data['course_id'] ?? 0);
    if (!$course_id) { http_response_code(400); echo "course_id required"; exit; }

    $name = trim($data['plan_name'] ?? 'Standard');
    $cfee = (float)($data['course_fee_lkr'] ?? 0);
    $rfee = (float)($data['registration_fee_lkr'] ?? 0);
    $ufee = (float)($data['certificate_fee_usd'] ?? 0);

    $id = upsert_standard_plan($conn,$course_id,$name,$cfee,$rfee,$ufee);
    header('Content-Type: application/json'); echo json_encode(['ok'=>true,'plan_id'=>$id]); exit;
  }

  /* ----------- INSTALLMENT: GET ----------- */
  if ($action === 'get_installment_plan') {
    $course_id = (int)($_GET['course_id'] ?? 0);
    if (!$course_id) { http_response_code(400); echo "course_id required"; exit; }

    // ensure container plan exists
    $s=$conn->prepare("SELECT id, plan_name FROM payment_plans WHERE course_id=? AND plan_type='installment' LIMIT 1");
    $s->bind_param('i',$course_id); $s->execute();
    $plan=$s->get_result()->fetch_assoc(); $s->close();

    if(!$plan){
      $i=$conn->prepare("INSERT INTO payment_plans (course_id, plan_type, plan_name) VALUES (?,?,?)");
      $ptype='installment'; $pname='Installment';
      $i->bind_param('iss',$course_id,$ptype,$pname); $i->execute();
      $plan_id=$i->insert_id; $i->close();
    } else { $plan_id=(int)$plan['id']; }

    $rows=[];
    $q=$conn->prepare("SELECT installment_no, due_date, course_fee_lkr, registration_fee_lkr, certificate_fee_usd
                       FROM installments WHERE plan_id=? ORDER BY installment_no ASC, id ASC");
    $q->bind_param('i',$plan_id); $q->execute();
    $rs=$q->get_result();
    while($r=$rs->fetch_assoc()) $rows[]=$r;
    $q->close();

    header('Content-Type: application/json');
    echo json_encode(['plan_id'=>$plan_id, 'plan_name'=>($plan['plan_name'] ?? 'Installment'), 'rows'=>$rows]);
    exit;
  }

  /* ----------- INSTALLMENT: SAVE ----------- */
  if ($action === 'save_installment_plan') {
    $p = json_decode(file_get_contents('php://input'), true);
    if (!is_array($p)) { http_response_code(400); echo "Invalid JSON"; exit; }

    $course_id = (int)($p['course_id'] ?? 0);
    $plan_id   = (int)($p['plan_id'] ?? 0);
    $rows      = $p['installments'] ?? [];
    if(!$course_id){ http_response_code(400); echo "course_id required"; exit; }

    $conn->begin_transaction();

    if ($plan_id<=0){
      $s=$conn->prepare("SELECT id FROM payment_plans WHERE course_id=? AND plan_type='installment' LIMIT 1");
      $s->bind_param('i',$course_id); $s->execute();
      $row=$s->get_result()->fetch_assoc(); $s->close();
      if($row){ $plan_id=(int)$row['id']; }
      else{
        $i=$conn->prepare("INSERT INTO payment_plans (course_id, plan_type, plan_name) VALUES (?,?,?)");
        $ptype='installment'; $pname='Installment';
        $i->bind_param('iss',$course_id,$ptype,$pname); $i->execute(); $plan_id=$i->insert_id; $i->close();
      }
    }

    $conn->query("DELETE FROM installments WHERE plan_id=$plan_id");

    if (!empty($rows)){
      $i=$conn->prepare("INSERT INTO installments
        (plan_id, installment_no, course_fee_lkr, registration_fee_lkr, certificate_fee_usd, due_date)
        VALUES (?,?,?,?,?,?)");
      foreach($rows as $r){
        $no=(int)($r['no'] ?? 0);
        $c=(float)($r['course_fee_lkr'] ?? 0);
        $rg=(float)($r['registration_fee_lkr'] ?? 0);
        $u=(float)($r['certificate_fee_usd'] ?? 0);
        $dd=($r['due_date'] ?? null) ?: null;
        $i->bind_param('iiidds',$plan_id,$no,$c,$rg,$u,$dd);
        $i->execute();
      }
      $i->close();
    }

    $conn->commit();
    header('Content-Type: application/json'); echo json_encode(['ok'=>true,'plan_id'=>$plan_id]); exit;
  }

  /* ----------- DISCOUNTS: GET (list) ----------- */
  if ($action === 'get_discounts') {
    $course_id = (int)($_GET['course_id'] ?? 0);
    if(!$course_id){ http_response_code(400); echo "course_id required"; exit; }

    $rows=[];
    $q=$conn->prepare("SELECT code,label,amount_lkr,is_default,status,sort_order
                       FROM course_discounts
                       WHERE course_id=? 
                       ORDER BY is_default DESC, sort_order ASC, amount_lkr DESC, id ASC");
    $q->bind_param('i',$course_id); $q->execute();
    $rs=$q->get_result();
    while($r=$rs->fetch_assoc()){
      $rows[] = [
        'code'=>$r['code'],
        'label'=>$r['label'],
        'amount_lkr'=>(float)$r['amount_lkr'],
        'is_default'=> (int)$r['is_default']===1,
        'status'=>$r['status'],
        'sort_order'=>(int)$r['sort_order']
      ];
    }
    header('Content-Type: application/json'); echo json_encode(['rows'=>$rows]); exit;
  }

  /* ----------- DISCOUNTS: SAVE (full replace per course) ----------- */
  if ($action === 'save_discounts') {
    $p = json_decode(file_get_contents('php://input'), true);
    if (!is_array($p)) { http_response_code(400); echo "Invalid JSON"; exit; }
    $course_id = (int)($p['course_id'] ?? 0);
    $list = $p['discounts'] ?? [];
    if(!$course_id){ http_response_code(400); echo "course_id required"; exit; }

    $conn->begin_transaction();
    $del=$conn->prepare("DELETE FROM course_discounts WHERE course_id=?");
    $del->bind_param('i',$course_id); $del->execute(); $del->close();

    if (!empty($list)){
      $ins=$conn->prepare("INSERT INTO course_discounts
        (course_id, code, label, amount_lkr, is_default, status, sort_order)
        VALUES (?,?,?,?,?,?,?)");
      foreach($list as $d){
        $code = trim((string)($d['code'] ?? ''));
        $label= trim((string)($d['label'] ?? ''));
        $amt  = (float)($d['amount_lkr'] ?? 0);
        $def  = !empty($d['is_default']) ? 1 : 0;
        $st   = in_array(($d['status'] ?? 'active'), ['active','inactive'], true) ? $d['status'] : 'active';
        $sort = (int)($d['sort_order'] ?? 0);
        $ins->bind_param('issdiss',$course_id,$code,$label,$amt,$def,$st,$sort);
        $ins->execute();
      }
      $ins->close();
      // ensure at most one default: keep the first default, clear the rest
      $conn->query("
        UPDATE course_discounts d
        JOIN (
          SELECT id FROM course_discounts WHERE course_id={$course_id} AND is_default=1 ORDER BY id ASC LIMIT 1
        ) keep ON 1=1
        SET d.is_default = CASE WHEN d.id=keep.id THEN 1 ELSE 0 END
        WHERE d.course_id={$course_id}
      ");
    }

    $conn->commit();
    header('Content-Type: application/json'); echo json_encode(['ok'=>true]); exit;
  }

  /* ----------- CARD SUMMARIES ----------- */
  if ($action === 'get_plan_summaries') {
    $course_id = (int)($_GET['course_id'] ?? 0);
    if(!$course_id){ http_response_code(400); echo "course_id required"; exit; }

    $out = ['standard'=>null,'discounts'=>null,'installment'=>null];

    // standard
    $s=$conn->prepare("SELECT id, plan_name, course_fee_lkr, registration_fee_lkr, certificate_fee_usd
                       FROM payment_plans WHERE course_id=? AND plan_type='standard' LIMIT 1");
    $s->bind_param('i',$course_id); $s->execute();
    $row=$s->get_result()->fetch_assoc(); $s->close();
    if($row){ $out['standard']=[
      'plan_id'=>(int)$row['id'],'plan_name'=>$row['plan_name']??'Standard',
      'course_fee_lkr'=>(float)$row['course_fee_lkr'],
      'registration_fee_lkr'=>(float)$row['registration_fee_lkr'],
      'certificate_fee_usd'=>(float)$row['certificate_fee_usd'],
    ]; }

    // discounts summary
    $d1=$conn->prepare("SELECT COUNT(*) c FROM course_discounts WHERE course_id=? AND status='active'");
    $d1->bind_param('i',$course_id); $d1->execute(); $cActive=(int)($d1->get_result()->fetch_assoc()['c']??0); $d1->close();

    $d2=$conn->prepare("SELECT label, amount_lkr FROM course_discounts WHERE course_id=? AND is_default=1 LIMIT 1");
    $d2->bind_param('i',$course_id); $d2->execute(); $def=$d2->get_result()->fetch_assoc(); $d2->close();

    $out['discounts']=[
      'active_count'=>$cActive,
      'default_label'=>$def['label'] ?? null,
      'default_amount_lkr'=> isset($def['amount_lkr']) ? (float)$def['amount_lkr'] : null
    ];

    // installment summary (count + sums)
    $q=$conn->prepare("SELECT p.id, p.plan_name,
                       COUNT(i.id) AS items,
                       COALESCE(SUM(i.course_fee_lkr),0) csum,
                       COALESCE(SUM(i.registration_fee_lkr),0) rsum,
                       COALESCE(SUM(i.certificate_fee_usd),0) usum
                       FROM payment_plans p
                       LEFT JOIN installments i ON i.plan_id=p.id
                       WHERE p.course_id=? AND p.plan_type='installment'
                       GROUP BY p.id, p.plan_name LIMIT 1");
    $q->bind_param('i',$course_id); $q->execute();
    $row=$q->get_result()->fetch_assoc(); $q->close();
    if($row){ $out['installment']=[
      'plan_id'=>(int)$row['id'], 'plan_name'=>$row['plan_name']??'Installment',
      'items'=>(int)$row['items'],
      'course_fee_sum'=>(float)$row['csum'],
      'registration_fee_sum'=>(float)$row['rsum'],
      'certificate_fee_sum'=>(float)$row['usum'],
    ]; }

    header('Content-Type: application/json'); echo json_encode($out); exit;
  }

  http_response_code(404); echo "Unknown action";
} catch(Throwable $e){
  try{ $conn->rollback(); }catch(Throwable $e2){}
  http_response_code(500);
  echo nl2br($e->getMessage());
}
