<?php
// /admin/portal_control.php
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

// flash
$msg = $_GET['msg'] ?? '';
$err = $_GET['err'] ?? '';

/* ---------------------------------------------
   Helpers
--------------------------------------------- */
function latest_fee_status(mysqli $conn, int $student_id) {
  // Use latest registration (approved) for this student
  $q = mysqli_query($conn, "
    SELECT r.id, r.course_id, r.fee_status, r.approved_at
    FROM registrations r
    WHERE r.student_id = {$student_id}
    ORDER BY r.approved_at DESC
    LIMIT 1
  ");
  $reg = mysqli_fetch_assoc($q);
  if (!$reg) return ['fee_status'=>'N/A', 'course_id'=>null];

  // Prefer fee_payments latest snapshot if exists
  $q2 = mysqli_query($conn, "
    SELECT status, total_fee, paid_amount, discount, extra_charges, updated_at
    FROM fee_payments
    WHERE student_id={$student_id} AND course_id=".(int)$reg['course_id']."
    ORDER BY updated_at DESC
    LIMIT 1
  ");
  if ($snap = mysqli_fetch_assoc($q2)) {
    return [
      'fee_status' => $snap['status'],      // PAID / PARTIAL / UNPAID
      'course_id'  => (int)$reg['course_id']
    ];
  } else {
    return [
      'fee_status' => $reg['fee_status'] ?: 'UNPAID',
      'course_id'  => (int)$reg['course_id']
    ];
  }
}

function effective_portal_access($fee_status, $policy, $grace_until) {
  $today = date('Y-m-d');
  // overrides first
  if ($policy === 'FORCE_ALLOW') return ['OPEN','badge ok'];
  if ($policy === 'FORCE_BLOCK') return ['BLOCKED','badge danger'];

  // AUTO logic
  if ($fee_status === 'PAID') return ['OPEN','badge ok'];
  if ($fee_status === 'PARTIAL') {
    if (!empty($grace_until) && $grace_until >= $today) return ['OPEN (Grace)','badge warn'];
    return ['BLOCKED','badge danger'];
  }
  if ($fee_status === 'UNPAID') {
    if (!empty($grace_until) && $grace_until >= $today) return ['OPEN (Grace)','badge warn'];
    return ['BLOCKED','badge danger'];
  }
  // unknown
  return ['BLOCKED','badge danger'];
}

/* ---------------------------------------------
   Save (POST)
--------------------------------------------- */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save'])) {
  $student_id = (int)($_POST['student_id'] ?? 0);
  $policy_in  = $_POST['policy'] ?? 'AUTO';
  $policy     = in_array($policy_in, ['AUTO','FORCE_ALLOW','FORCE_BLOCK'], true) ? $policy_in : 'AUTO';
  $grace      = trim($_POST['grace_until'] ?? '');
  $note       = trim($_POST['note'] ?? '');

  if ($student_id <= 0) {
    header("Location: portal_control.php?err=".urlencode("Invalid student"));
    exit;
  }

  // Normalise grace date
  if ($grace === '') $grace = NULL;

  // Upsert
  $sql = "INSERT INTO student_portal_access (student_id, policy, grace_until, note, updated_by)
          VALUES (?, ?, ?, ?, ?)
          ON DUPLICATE KEY UPDATE policy=VALUES(policy), grace_until=VALUES(grace_until), note=VALUES(note), updated_by=VALUES(updated_by)";
  $st = mysqli_prepare($conn, $sql);
  if (!$st) { header("Location: portal_control.php?err=".urlencode(mysqli_error($conn))); exit; }

  // bind: i s s s i  (NULL for grace handled via mysqli_stmt_bind_param by passing null and "s")
  mysqli_stmt_bind_param($st, "isssi", $student_id, $policy, $grace, $note, $_SESSION['admin_id']);
  if (!mysqli_stmt_execute($st)) {
    $e = mysqli_stmt_error($st);
    mysqli_stmt_close($st);
    header("Location: portal_control.php?err=".urlencode($e));
    exit;
  }
  mysqli_stmt_close($st);
  header("Location: portal_control.php?msg=".urlencode("Portal policy saved"));
  exit;
}

/* ---------------------------------------------
   Filters
--------------------------------------------- */
$q   = trim($_GET['q'] ?? '');     // name/cnic
$only_problem = isset($_GET['only_problem']) ? (int)$_GET['only_problem'] : 0;

/* ---------------------------------------------
   List students + portal policy
--------------------------------------------- */
$where = " WHERE 1=1 ";
if ($q !== '') {
  $qesc = mysqli_real_escape_string($conn, $q);
  $where .= " AND (s.full_name LIKE '%$qesc%' OR s.cnic LIKE '%$qesc%') ";
}

$sql = "
SELECT
  s.id, s.full_name, s.cnic, s.contact_number, s.email,
  spa.policy, spa.grace_until, spa.note
FROM students s
LEFT JOIN student_portal_access spa ON spa.student_id = s.id
$where
ORDER BY s.created_at DESC
LIMIT 300
";
$list = mysqli_query($conn, $sql);

admin_header('Student Portal Control');
?>
<style>
.badge{padding:2px 8px;border-radius:999px;font-size:12px;font-weight:700;border:1px solid transparent;display:inline-block}
.badge.ok{background:#dcfce7;color:#166534;border-color:#86efac}
.badge.warn{background:#fff7ed;color:#9a3412;border-color:#fed7aa}
.badge.danger{background:#fee2e2;color:#991b1b;border-color:#fecaca}
.k{font-size:12px;color:#64748b}
thead th{position:sticky;top:0;background:#f1f5f9;z-index:1}
</style>

<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Student Portal Control
  <span class="badge warn">Block/Allow + Grace</span>
</h2>

<?php if($msg): ?><div class="card" style="background:#eff6ff;border:1px solid #bfdbfe;color:#1e40af;margin-top:10px"><?=h($msg)?></div><?php endif; ?>
<?php if($err): ?><div class="card" style="background:#fee2e2;border:1px solid #fecaca;color:#991b1b;margin-top:10px"><?=h($err)?></div><?php endif; ?>

<div class="card mt-3">
  <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <input name="q" value="<?=h($q)?>" placeholder="Search name or CNIC..." style="max-width:260px">
    <label style="display:flex;gap:6px;align-items:center">
      <input type="checkbox" name="only_problem" value="1" <?= $only_problem? 'checked':''?>>
      <span class="k">Show only blocked/unpaid</span>
    </label>
    <button class="btn">Apply</button>
    <a class="btn" href="portal_control.php">Reset</a>
  </form>
</div>

<div class="card mt-3">
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th style="text-align:left">Student</th>
          <th>CNIC</th>
          <th>Contact</th>
          <th>Fee Status</th>
          <th>Policy</th>
          <th>Grace Until</th>
          <th>Portal</th>
          <th style="width:320px">Set Policy</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $has=false;
        while($s = mysqli_fetch_assoc($list)):
          $has=true;
          $fee = latest_fee_status($conn, (int)$s['id']);           // ['fee_status','course_id']
          $pol = $s['policy'] ?? 'AUTO';
          $grc = $s['grace_until'] ?? null;
          [$portal,$cls] = effective_portal_access($fee['fee_status'], $pol, $grc);

          if ($only_problem) {
            // show rows where portal is blocked OR fee unpaid/partial
            if (!in_array($fee['fee_status'], ['UNPAID','PARTIAL'])) {
              // but if policy forces block, still include
              if ($portal!=='BLOCKED' && strpos($portal,'Grace')===false) continue;
            }
          }
        ?>
        <tr>
          <td style="text-align:center"><?= (int)$s['id'] ?></td>
          <td style="font-weight:600"><?= h($s['full_name']) ?></td>
          <td style="text-align:center"><?= h($s['cnic']) ?></td>
          <td style="text-align:center"><?= h($s['contact_number']) ?></td>
          <td style="text-align:center">
            <?php
              echo $fee['fee_status']==='PAID'    ? '<span class="badge ok">PAID</span>' :
                   ($fee['fee_status']==='PARTIAL'? '<span class="badge warn">PARTIAL</span>' :
                                                     '<span class="badge danger">UNPAID</span>');
            ?>
          </td>
          <td style="text-align:center"><?= h($pol) ?></td>
          <td style="text-align:center"><?= h($grc ?: '-') ?></td>
          <td style="text-align:center"><span class="<?=$cls?>"><?= h($portal) ?></span></td>
          <td>
            <form method="post" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
              <input type="hidden" name="student_id" value="<?= (int)$s['id'] ?>">
              <select name="policy" style="min-width:150px">
                <option value="AUTO"        <?= $pol==='AUTO'?'selected':'' ?>>AUTO (fee-based)</option>
                <option value="FORCE_ALLOW" <?= $pol==='FORCE_ALLOW'?'selected':'' ?>>FORCE_ALLOW</option>
                <option value="FORCE_BLOCK" <?= $pol==='FORCE_BLOCK'?'selected':'' ?>>FORCE_BLOCK</option>
              </select>
              <input type="date" name="grace_until" value="<?= h($grc) ?>" title="Allow until this date in AUTO mode">
              <input name="note" placeholder="Note (optional)" value="<?= h($s['note'] ?? '') ?>" style="min-width:120px">
              <button class="btn primary" name="save" value="1">Save</button>
            </form>
          </td>
        </tr>
        <?php endwhile; ?>
        <?php if(!$has): ?>
          <tr><td colspan="9" style="text-align:center;color:#64748b;padding:16px">No students found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<?php admin_footer(); ?>
