<?php
// ===== DEBUG + SAFE HEADERS =====
error_reporting(E_ALL);
ini_set('display_errors', 1);
ob_start(); // buffer output so header() can always redirect

require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

$id = (int)($_GET['id'] ?? 0);

// ---------- Load request ----------
$stmt = mysqli_prepare($conn, "SELECT * FROM admission_requests WHERE id=?");
if(!$stmt){ die("Prepare failed (load req): ".mysqli_error($conn)); }
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$req = mysqli_fetch_assoc($res);
mysqli_stmt_close($stmt);

if (!$req) {
  admin_header('Not Found');
  echo "<p>Request not found.</p>";
  admin_footer(); exit;
}

// ---------- Load courses (active) into array ----------
$coursesArr = [];
$cq = mysqli_query($conn, "SELECT id, name FROM courses WHERE is_active=1 ORDER BY name");
if(!$cq){ die("Query failed (courses): ".mysqli_error($conn)); }
while ($c = mysqli_fetch_assoc($cq)) $coursesArr[] = $c;

// ---------- Guess preferred course ----------
$prefCourseId = 0;
if (!empty($req['requested_course'])) {
  $g = mysqli_prepare($conn, "SELECT id FROM courses WHERE name=? LIMIT 1");
  if($g){
    mysqli_stmt_bind_param($g, "s", $req['requested_course']);
    mysqli_stmt_execute($g);
    $gRes = mysqli_stmt_get_result($g);
    if ($row = mysqli_fetch_assoc($gRes)) $prefCourseId = (int)$row['id'];
    mysqli_stmt_close($g);
  }
}

// ---------- Resolve selected course id ----------
$selected_course_id = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['course_id']) && (int)$_POST['course_id'] > 0) {
  $selected_course_id = (int)$_POST['course_id'];
} elseif ($prefCourseId > 0) {
  $selected_course_id = $prefCourseId;
} elseif (!empty($coursesArr)) {
  $selected_course_id = (int)$coursesArr[0]['id'];
}

// ---------- Helper: load batches ----------
function load_batches($conn, $course_id) {
  $list = [];
  if ($course_id > 0) {
    $bs = mysqli_prepare($conn, "SELECT id, name, timing, start_date FROM batches
                                 WHERE course_id=? AND status IN ('Scheduled','Ongoing')
                                 ORDER BY start_date");
    if(!$bs){ die("Prepare failed (batches): ".mysqli_error($conn)); }
    mysqli_stmt_bind_param($bs, "i", $course_id);
    mysqli_stmt_execute($bs);
    $bRes = mysqli_stmt_get_result($bs);
    while ($b = mysqli_fetch_assoc($bRes)) $list[] = $b;
    mysqli_stmt_close($bs);
  }
  return $list;
}
$batches = load_batches($conn, $selected_course_id);

// =======================================================
// APPROVE handler (idempotent + PRG + lenient POST detect)
// =======================================================
$isPost = ($_SERVER['REQUEST_METHOD'] === 'POST');
// Button name kabhi-kabhi POST me nahi aata (Enter key submit etc.)
// Isliye approveMode true agar: approve set ho YA (refresh nahi aur course+batch present)
$approveMode = $isPost && (
  isset($_POST['approve'])
  || (empty($_POST['refresh']) && isset($_POST['course_id'], $_POST['batch_id']))
);

if ($approveMode) {
  $course_id  = (int)($_POST['course_id'] ?? 0);
  $batch_id   = (int)($_POST['batch_id'] ?? 0);
  $fee_status = $_POST['fee_status'] ?? 'UNPAID';

  if (!$course_id || !$batch_id) {
    $err = "Select course & batch.";
  } else {
    // Ensure InnoDB/transactions supported — if not, fallback to autocommit off
    if (!mysqli_begin_transaction($conn)) {
      // fallback
      mysqli_autocommit($conn, false);
    }

    // 1) Lock the request row and re-check status
    $lock = mysqli_prepare($conn, "SELECT status, registration_id FROM admission_requests WHERE id=? FOR UPDATE");
    if(!$lock){ mysqli_rollback($conn); die("Prepare failed (lock req): ".mysqli_error($conn)); }
    mysqli_stmt_bind_param($lock, "i", $id);
    mysqli_stmt_execute($lock);
    $lockRes = mysqli_stmt_get_result($lock);
    $rowLock = mysqli_fetch_assoc($lockRes);
    mysqli_stmt_close($lock);

    if (!$rowLock) {
      mysqli_rollback($conn);
      $err = "Request not found.";
    } elseif ($rowLock['status'] !== 'PENDING' || !empty($rowLock['registration_id'])) {
      mysqli_rollback($conn);
      header('Location: requests_pending.php?msg=' . urlencode('This request was already processed.'));
      exit;
    } else {
      // 2) Ensure student exists
      $student_id = 0;
      $st = mysqli_prepare($conn, "SELECT id FROM students WHERE cnic=? LIMIT 1");
      if(!$st){ mysqli_rollback($conn); die("Prepare failed (find student): ".mysqli_error($conn)); }
      mysqli_stmt_bind_param($st, "s", $req['cnic']);
      mysqli_stmt_execute($st);
      $sr = mysqli_stmt_get_result($st);
      if ($row = mysqli_fetch_assoc($sr)) $student_id = (int)$row['id'];
      mysqli_stmt_close($st);

      if (!$student_id) {
        $ins = mysqli_prepare($conn, "INSERT INTO students
          (full_name, father_name, father_number, cnic, dob, contact_number, email, address)
          VALUES (?,?,?,?,?,?,?,?)");
        if(!$ins){ mysqli_rollback($conn); die("Prepare failed (insert student): ".mysqli_error($conn)); }
        mysqli_stmt_bind_param($ins, "ssssssss",
          $req['full_name'], $req['father_name'], $req['father_number'], $req['cnic'], $req['dob'],
          $req['contact_number'], $req['email'], $req['address']
        );
        if(!mysqli_stmt_execute($ins)){ mysqli_rollback($conn); die("Execute failed (insert student): ".mysqli_stmt_error($ins)); }
        $student_id = mysqli_insert_id($conn);
        mysqli_stmt_close($ins);
      }

      // 3) Generate REG NO (ZE-YYYY-####)
      $year = date('Y');
      $countRes = mysqli_query($conn, "SELECT COUNT(*)+1 AS n FROM registrations WHERE YEAR(approved_at)=$year");
      if(!$countRes){ mysqli_rollback($conn); die("Query failed (reg seq): ".mysqli_error($conn)); }
      $seq = (int)mysqli_fetch_assoc($countRes)['n'];
      $reg_no = sprintf("ZE-%s-%04d", $year, $seq);

      // 4) Insert registration
      $insr = mysqli_prepare($conn, "INSERT INTO registrations
        (reg_no, student_id, course_id, batch_id, preferred_start_date, source, fee_status, status, requested_at, approved_at)
        VALUES (?,?,?,?,?,'online_form',?,'ACTIVE',?,NOW())");
      if(!$insr){ mysqli_rollback($conn); die("Prepare failed (insert reg): ".mysqli_error($conn)); }

      // types: s i i i s s s
      if(!mysqli_stmt_bind_param($insr, "siiisss",
        $reg_no, $student_id, $course_id, $batch_id, $req['preferred_start_date'],
        $fee_status, $req['created_at']
      )){
        mysqli_rollback($conn); die("Bind failed (insert reg): ".mysqli_stmt_error($insr));
      }
      if(!mysqli_stmt_execute($insr)){
        mysqli_rollback($conn); die("Execute failed (insert reg): ".mysqli_stmt_error($insr));
      }
      $registration_id = mysqli_insert_id($conn);
      mysqli_stmt_close($insr);

      // 5) Update request
      $upr = mysqli_prepare($conn, "UPDATE admission_requests
                                    SET status='APPROVED', registration_id=?, updated_at=NOW()
                                    WHERE id=?");
      if(!$upr){ mysqli_rollback($conn); die("Prepare failed (update req): ".mysqli_error($conn)); }
      mysqli_stmt_bind_param($upr, "ii", $registration_id, $id);
      if(!mysqli_stmt_execute($upr)){
        mysqli_rollback($conn); die("Execute failed (update req): ".mysqli_stmt_error($upr));
      }
      mysqli_stmt_close($upr);

      // 6) Commit + PRG
      if (!mysqli_commit($conn)) {
        // if InnoDB not available and we used autocommit(false)
        mysqli_commit($conn);
      }
      // IMPORTANT: stop any output before redirect
      ob_clean();
      header('Location: requests_pending.php?msg=' . urlencode("Approved — Reg: {$reg_no}"));
      exit;
    }
  }
}

// ---------- Recompute batches on course refresh ----------
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['refresh'])) {
  $batches = load_batches($conn, $selected_course_id);
}

admin_header('Review Request');
?>
<h2 style="margin:0 0 8px">Review Admission Request</h2>

<?php if(!empty($ok)): ?>
  <div class="card mt-3" style="border-color:#86efac;background:#f0fdf4;color:#065f46"> <?=$ok?> </div>
<?php endif; ?>
<?php if(!empty($err)): ?>
  <div class="card mt-3" style="border-color:#fecaca;background:#fff1f2;color:#991b1b"> <?=$err?> </div>
<?php endif; ?>

<div class="grid mt-3">
  <div class="card col-6">
    <h3 style="margin:0 0 8px;color:#2563eb">Applicant</h3>
    <table>
      <tr><th>Name</th><td><?=h($req['full_name'])?></td></tr>
      <tr><th>Father</th><td><?=h($req['father_name'])?> (<?=h($req['father_number'])?>)</td></tr>
      <tr><th>CNIC</th><td><?=h($req['cnic'])?></td></tr>
      <tr><th>Gender</th><td><?=h($req['gender'])?></td></tr>
      <tr><th>DOB</th><td><?=h($req['dob'])?></td></tr>
      <tr><th>Contact</th><td><?=h($req['contact_number'])?>, <?=h($req['email'])?></td></tr>
      <tr><th>Address</th><td><?=h($req['address'])?></td></tr>
      <tr><th>Requested</th><td><?=h($req['requested_course'])?> • <?=h($req['preferred_timing'])?> • Start: <?=h($req['preferred_start_date'])?></td></tr>
      <?php if(!empty($req['cnic_file_path'])): ?>
      <tr><th>CNIC/B-Form</th><td><a class="btn" href="../<?=h($req['cnic_file_path'])?>" target="_blank">View Upload</a></td></tr>
      <?php endif; ?>
    </table>
  </div>

  <div class="card col-6">
    <h3 style="margin:0 0 8px;color:#2563eb">Approve & Assign</h3>
    <form method="post" id="approveForm">
      <label>Course</label>
      <select name="course_id" id="courseSelect" required>
        <?php foreach($coursesArr as $c): ?>
          <option value="<?=$c['id']?>" <?=$c['id']==$selected_course_id?'selected':''?>><?=h($c['name'])?></option>
        <?php endforeach; ?>
      </select>

      <label class="mt-2">Batch</label>
      <select name="batch_id" id="batchSelect" required>
        <?php if(!empty($batches)): ?>
          <?php foreach($batches as $b): ?>
            <option value="<?=$b['id']?>"><?=h($b['name'])?> (<?=h($b['timing'])?> • <?=h($b['start_date'])?>)</option>
          <?php endforeach; ?>
        <?php else: ?>
          <option value="">— No batches for this course —</option>
        <?php endif; ?>
      </select>
      <?php if(empty($batches)): ?>
        <div class="mt-2" style="color:#991b1b">
          No batches found for selected course. <a class="btn" href="batches.php">Create Batch</a>
        </div>
      <?php endif; ?>

      <label class="mt-2">Fee Status</label>
      <select name="fee_status">
        <option>UNPAID</option><option>PARTIAL</option><option>PAID</option>
      </select>

      <div class="mt-3" style="display:flex;gap:8px;align-items:center">
        <button class="btn primary" type="submit" name="approve" value="1" id="approveBtn">
          Approve & Create Registration
        </button>
        <a class="btn" href="requests_pending.php">Back</a>
      </div>

      <!-- used to refresh batches on course change -->
      <input type="hidden" name="refresh" value="">
    </form>
  </div>
</div>

<script>
const form = document.getElementById('approveForm');
const courseSel = document.getElementById('courseSelect');
const approveBtn = document.getElementById('approveBtn');

// Course change -> refresh batches
courseSel.addEventListener('change', function(){
  form.refresh.value = '1';
  form.submit();
});

// Prevent double-submit
form.addEventListener('submit', function(){
  if (approveBtn && !form.refresh.value) {
    approveBtn.disabled = true;
    approveBtn.textContent = 'Processing...';
  }
});
</script>

<?php admin_footer();
// ---- optional: uncomment to see raw post ----
// if($_SERVER['REQUEST_METHOD']==='POST'){ echo "<pre>"; print_r($_POST); echo "</pre>"; }
