<?php
// ../ajax/fetch_fee_plans.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
ec_require_login();

header('Content-Type: application/json; charset=utf-8');

$db = ec_db();
if (!$db) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'DB connection failed']);
  exit;
}

$conn = $db;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset('utf8mb4');

$course_id = (int)($_GET['course_id'] ?? 0);
if ($course_id <= 0) {
  echo json_encode(['ok'=>true,'plans'=>[], 'discounts'=>[], 'base'=>['course_fee_lkr'=>0,'registration_fee_lkr'=>0,'certificate_fee_usd'=>0]]);
  exit;
}

try {
  /* 0) Base fees from courses (helps UI even if no plans exist) */
  $base = ['course_fee_lkr'=>0.0,'registration_fee_lkr'=>0.0,'certificate_fee_usd'=>0.0];
  try {
    $st0 = $conn->prepare("SELECT course_fee_lkr, registration_fee_lkr, certificate_fee_usd FROM courses WHERE id=? LIMIT 1");
    $st0->bind_param('i', $course_id);
    $st0->execute();
    if ($r0 = $st0->get_result()->fetch_assoc()) {
      $base = [
        'course_fee_lkr'       => (float)($r0['course_fee_lkr'] ?? 0),
        'registration_fee_lkr' => (float)($r0['registration_fee_lkr'] ?? 0),
        'certificate_fee_usd'  => (float)($r0['certificate_fee_usd'] ?? 0),
      ];
    }
    $st0->close();
  } catch (Throwable $e) {
    // ignore base fee failure
  }

  /* 1) Load plans for this course */
  $sql = "SELECT id, course_id, plan_name, plan_type, months AS duration_months,
                 course_fee_lkr, registration_fee_lkr, certificate_fee_usd, status
          FROM payment_plans
          WHERE course_id=? AND status='Active'
          ORDER BY FIELD(plan_type,'installment','standard','discount'), id";

  $st = $conn->prepare($sql);
  $st->bind_param('i', $course_id);
  $st->execute();
  $res = $st->get_result();
  $planRows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
  $st->close();

  /* 2) If there are installment plans, fetch their installments */
  $instIds = array_map(
    'intval',
    array_column(
      array_filter($planRows, fn($r) => strtolower((string)($r['plan_type'] ?? '')) === 'installment'),
      'id'
    )
  );

  $instMap = [];
  if ($instIds) {
    $in = implode(',', array_map('intval', $instIds));

    $q2 = "SELECT plan_id, installment_no, due_date,
                  course_fee_lkr, registration_fee_lkr, certificate_fee_usd
           FROM payment_plan_installments
           WHERE plan_id IN ($in)
           ORDER BY plan_id ASC, installment_no ASC, id ASC";

    if ($rs2 = $conn->query($q2)) {
      while ($r = $rs2->fetch_assoc()) {
        $pid = (int)$r['plan_id'];

        // Force 1..N numbering per plan_id (avoid duplicates)
        $i = isset($instMap[$pid]) ? count($instMap[$pid]) : 0;

        $instMap[$pid][] = [
          'installment_no'       => $i + 1,
          'due_date'             => "", // IMPORTANT: UI will generate due dates
          'course_fee_lkr'       => (float)($r['course_fee_lkr'] ?? 0),
          'registration_fee_lkr' => (float)($r['registration_fee_lkr'] ?? 0),
          'certificate_fee_usd'  => (float)($r['certificate_fee_usd'] ?? 0),
        ];
      }
      $rs2->close();
    }
  }

  /* 3) Normalize every plan to include an `installments` array */
  $plans = [];
  foreach ($planRows as $p) {
    $type = strtolower((string)($p['plan_type'] ?? 'standard'));

    if ($type === 'installment') {
      $installments = $instMap[(int)$p['id']] ?? [];
    } else {
      // STANDARD/DISCOUNT => single "installment" so the front-end can sum it
      $installments = [[
        'installment_no'       => 1,
        'due_date'             => "",
        'course_fee_lkr'       => (float)($p['course_fee_lkr'] ?? 0),
        'registration_fee_lkr' => (float)($p['registration_fee_lkr'] ?? 0),
        'certificate_fee_usd'  => (float)($p['certificate_fee_usd'] ?? 0),
      ]];
    }

    $plans[] = [
      'id'                 => (int)$p['id'],
      'course_id'          => (int)($p['course_id'] ?? $course_id),  // ✅ IMPORTANT
      'plan_name'          => (string)($p['plan_name'] ?? ''),
      'type'               => $type,
      'duration_months'    => (int)($p['duration_months'] ?? 0),
      'certificate_fee_usd'=> (float)($p['certificate_fee_usd'] ?? 0), // ✅ for JS
      'installments'       => $installments,
    ];
  }

  /* 4) Discount presets (course-specific first, then global course_id=0) */
  $discounts = [];
  $qDisc = "SELECT id, label, amount_lkr, is_default
            FROM course_discounts
            WHERE status='active' AND (course_id=? OR course_id=0)
            ORDER BY (course_id=? ) DESC, is_default DESC, sort_order ASC, id ASC";

  $sd = $conn->prepare($qDisc);
  $sd->bind_param('ii', $course_id, $course_id);
  $sd->execute();
  $dr = $sd->get_result();
  while ($d = $dr->fetch_assoc()) {
    $discounts[] = [
      'id'         => (int)($d['id'] ?? 0),
      'label'      => (string)($d['label'] ?? ''),
      'amount_lkr' => (float)($d['amount_lkr'] ?? 0),
      'is_default' => !empty($d['is_default']) ? 1 : 0,
    ];
  }
  $sd->close();

  echo json_encode([
    'ok'        => true,
    'plans'     => $plans,
    'discounts' => $discounts,
    'base'      => $base
  ]);
  exit;

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
  exit;
}
