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

// ---------- helpers ----------
if (!function_exists('h')) {
  function h($s){ return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); }
}
function flash_set($msg, $type='ok'){ $_SESSION['flash'] = ['m'=>$msg, 't'=>$type]; }
function flash_get(){
  if (!empty($_SESSION['flash'])) { $f = $_SESSION['flash']; unset($_SESSION['flash']); return $f; }
  return null;
}
function rand_password($len=10){
  $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%';
  $out=''; for($i=0;$i<$len;$i++) $out .= $alphabet[random_int(0, strlen($alphabet)-1)];
  return $out;
}

// ---------- actions ----------
if ($_SERVER['REQUEST_METHOD']==='POST') {
  $action = $_POST['action'] ?? '';

  // SET / RESET PASSWORD
  if ($action==='set_password') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $pass = trim($_POST['new_password'] ?? '');
    $gen  = isset($_POST['gen']) ? 1 : 0;
    $force = isset($_POST['force_reset']) ? 1 : 0;

    if ($sid > 0) {
      if ($gen===1) { $pass = rand_password(10); }
      if ($pass==='') { flash_set('Password required or choose Generate.','err'); header('Location: student_accounts.php'); exit; }

      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $st = mysqli_prepare($conn, "UPDATE students SET portal_password_hash=?, portal_enabled=1, portal_force_reset=?, status='ACTIVE' WHERE id=?");
      mysqli_stmt_bind_param($st, "sii", $hash, $force, $sid);
      if (!mysqli_stmt_execute($st)) { flash_set('Failed to set password: '.mysqli_stmt_error($st),'err'); }
      else {
        // store generated password only for display once
        if ($gen===1) flash_set('Password set. Temporary password: '.$pass.'  (copy now!)','ok');
        else flash_set('Password updated successfully.','ok');
      }
      mysqli_stmt_close($st);
    }
    header('Location: student_accounts.php');
    exit;
  }

  // TOGGLE PORTAL
  if ($action==='toggle_portal') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $next = (int)($_POST['next'] ?? 0);
    if ($sid>0) {
      $st = mysqli_prepare($conn, "UPDATE students SET portal_enabled=? WHERE id=?");
      mysqli_stmt_bind_param($st, "ii", $next, $sid);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
      flash_set('Portal '.($next? 'enabled':'disabled').' for student #'.$sid,'ok');
    }
    header('Location: student_accounts.php');
    exit;
  }

  // SET STATUS (Active / Left / Suspended) + left_at optional
  if ($action==='set_status') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $status_in = $_POST['status'] ?? 'ACTIVE';
    $left_at   = $_POST['left_at'] ?? '';
    $status = in_array($status_in, ['ACTIVE','LEFT','SUSPENDED'], true) ? $status_in : 'ACTIVE';

    if ($sid>0) {
      $st = mysqli_prepare($conn, "UPDATE students SET status=?, left_at=NULLIF(?,'' ) WHERE id=?");
      mysqli_stmt_bind_param($st, "ssi", $status, $left_at, $sid);
      if(!mysqli_stmt_execute($st)) flash_set('Status update failed: '.mysqli_stmt_error($st),'err');
      else flash_set('Status updated.','ok');
      mysqli_stmt_close($st);
    }
    header('Location: student_accounts.php');
    exit;
  }

  // SET GRACE UNTIL (portal allowed until date)
  if ($action==='set_grace') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $grace = $_POST['portal_grace_until'] ?? '';
    if ($sid>0) {
      $st = mysqli_prepare($conn, "UPDATE students SET portal_grace_until=NULLIF(?, '') WHERE id=?");
      mysqli_stmt_bind_param($st, "si", $grace, $sid);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
      flash_set('Grace date '.($grace? 'set to '.$grace : 'cleared').'.','ok');
    }
    header('Location: student_accounts.php');
    exit;
  }

  // EDIT BASIC INFO
  if ($action==='edit_student') {
    $sid = (int)($_POST['student_id'] ?? 0);
    $name = trim($_POST['full_name'] ?? '');
    $contact = trim($_POST['contact_number'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $address = trim($_POST['address'] ?? '');
    if ($sid>0 && $name!=='') {
      $st = mysqli_prepare($conn, "UPDATE students SET full_name=?, contact_number=?, email=?, address=? WHERE id=?");
      mysqli_stmt_bind_param($st, "ssssi", $name, $contact, $email, $address, $sid);
      if(!mysqli_stmt_execute($st)) flash_set('Update failed: '.mysqli_stmt_error($st),'err');
      else flash_set('Student updated.','ok');
      mysqli_stmt_close($st);
    }
    header('Location: student_accounts.php');
    exit;
  }

  // DELETE (safe: only if no registrations/payments)
  if ($action==='delete_student') {
    $sid = (int)($_POST['student_id'] ?? 0);
    if ($sid>0) {
      $ok = true;
      $ck1 = mysqli_query($conn, "SELECT COUNT(*) c FROM registrations WHERE student_id={$sid}");
      $r1  = (int)mysqli_fetch_assoc($ck1)['c'];
      $ck2 = mysqli_query($conn, "SELECT COUNT(*) c FROM fee_payments WHERE student_id={$sid}");
      $r2  = (int)mysqli_fetch_assoc($ck2)['c'];
      if ($r1>0 || $r2>0) { $ok=false; }
      if (!$ok) {
        flash_set("Cannot delete: student has linked registrations or payments.", 'err');
      } else {
        $del = mysqli_prepare($conn, "DELETE FROM students WHERE id=?");
        mysqli_stmt_bind_param($del, "i", $sid);
        if (!mysqli_stmt_execute($del)) flash_set('Delete failed: '.mysqli_stmt_error($del),'err');
        else flash_set('Student deleted.','ok');
        mysqli_stmt_close($del);
      }
    }
    header('Location: student_accounts.php');
    exit;
  }
}

// ---------- filters ----------
$q = trim($_GET['q'] ?? '');
$portal = $_GET['portal'] ?? '';
$status = $_GET['status'] ?? '';

// ---------- list ----------
$where = 'WHERE 1=1';
if ($q!=='') {
  $esc = mysqli_real_escape_string($conn, $q);
  $where .= " AND (s.full_name LIKE '%$esc%' OR s.email LIKE '%$esc%' OR s.cnic LIKE '%$esc%')";
}
if ($portal==='enabled')  $where .= " AND s.portal_enabled=1";
if ($portal==='disabled') $where .= " AND s.portal_enabled=0";
if (in_array($status, ['ACTIVE','LEFT','SUSPENDED'], true)) $where .= " AND s.status='".$status."'";

// latest registration per student (course/batch)
$sql = "
SELECT
  s.id, s.full_name, s.email, s.contact_number, s.address, s.cnic,
  s.portal_enabled, s.portal_force_reset, s.status, s.left_at, s.portal_grace_until,
  r.reg_no, r.fee_status, r.status AS reg_status,
  c.name AS course_name, b.name AS batch_name
FROM students s
LEFT JOIN (
  SELECT r1.*
  FROM registrations r1
  JOIN (
    SELECT student_id, MAX(approved_at) maxd FROM registrations GROUP BY student_id
  ) r2 ON r2.student_id=r1.student_id AND r2.maxd=r1.approved_at
) r ON r.student_id=s.id
LEFT JOIN courses c ON c.id=r.course_id
LEFT JOIN batches b ON b.id=r.batch_id
$where
ORDER BY s.id DESC
LIMIT 200
";
$rows = mysqli_query($conn, $sql);

admin_header('Student Accounts');
$flash = flash_get();
?>
<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}
.badge.blue{background:#dbeafe;color:#1e40af;border-color:#bfdbfe}
.row-actions .btn{padding:6px 10px}
fieldset{border:1px solid var(--border);border-radius:10px;padding:10px;margin:0}
legend{font-size:12px;color:#475569;padding:0 6px}
.inline-form{display:flex;gap:8px;flex-wrap:wrap;align-items:end}
</style>

<h2 style="display:flex;align-items:center;gap:10px;margin:0 0 8px">
  Student Portal Control
  <span class="badge blue">Set passwords · enable/disable · status · grace</span>
</h2>

<?php if($flash): ?>
  <div class="card mt-2 <?= $flash['t']==='err' ? 'flash' : 'flash' ?>" style="background:<?= $flash['t']==='err'?'#fff1f2':'#eff6ff'?>;border-color:<?= $flash['t']==='err'?'#fecaca':'#bfdbfe'?>;color:<?= $flash['t']==='err'?'#991b1b':'#1e40af'?>">
    <?= h($flash['m']) ?>
  </div>
<?php endif; ?>

<div class="card mt-3">
  <form method="get" style="display:flex;gap:8px;flex-wrap:wrap">
    <input name="q" value="<?=h($q)?>" placeholder="Search name/email/CNIC..." style="max-width:260px">
    <select name="portal">
      <option value="">Portal: All</option>
      <option value="enabled"  <?=$portal==='enabled'?'selected':''?>>Enabled</option>
      <option value="disabled" <?=$portal==='disabled'?'selected':''?>>Disabled</option>
    </select>
    <select name="status">
      <option value="">Status: All</option>
      <?php foreach(['ACTIVE','LEFT','SUSPENDED'] as $st): ?>
        <option <?=$status===$st?'selected':''?>><?=$st?></option>
      <?php endforeach; ?>
    </select>
    <button class="btn">Apply</button>
    <a class="btn" href="student_accounts.php">Reset</a>
  </form>
</div>

<div class="card mt-3">
  <div class="table-wrap">
    <table style="min-width:1100px">
      <thead>
        <tr>
          <th>#</th>
          <th>Student</th>
          <th>Contact</th>
          <th>Course / Batch</th>
          <th>Reg</th>
          <th>Portal</th>
          <th>Status</th>
          <th>Grace</th>
          <th style="width:420px">Actions</th>
        </tr>
      </thead>
      <tbody>
      <?php if(mysqli_num_rows($rows)==0): ?>
        <tr><td colspan="9" style="text-align:center;padding:24px;color:#64748b">No results.</td></tr>
      <?php endif; ?>
      <?php while($r = mysqli_fetch_assoc($rows)): ?>
        <tr>
          <td><?= (int)$r['id'] ?></td>
          <td style="font-weight:700">
            <?= h($r['full_name']) ?><br>
            <span style="color:#64748b;font-size:12px"><?= h($r['email']) ?></span><br>
            <span style="color:#64748b;font-size:12px">CNIC: <?= h($r['cnic']) ?></span>
          </td>
          <td>
            <?= h($r['contact_number']) ?><br>
            <span style="color:#64748b;font-size:12px"><?= h($r['address']) ?></span>
          </td>
          <td>
            <?= h($r['course_name'] ?: '-') ?><br>
            <span style="color:#64748b;font-size:12px"><?= h($r['batch_name'] ?: '-') ?></span>
          </td>
          <td>
            <?= h($r['reg_no'] ?: '-') ?><br>
            <span class="badge <?= $r['fee_status']==='PAID'?'ok':($r['fee_status']==='PARTIAL'?'warn':'danger') ?>">
              <?= h($r['fee_status'] ?: 'UNPAID') ?>
            </span>
          </td>
          <td>
            <?= $r['portal_enabled'] ? '<span class="badge ok">Enabled</span>' : '<span class="badge danger">Disabled</span>' ?><br>
            <?php if($r['portal_force_reset']): ?>
              <span class="badge warn" title="Student must change password on next login">Force reset</span>
            <?php endif; ?>
          </td>
          <td>
            <?php
              $b = $r['status']==='ACTIVE' ? 'ok' : ($r['status']==='LEFT'?'danger':'warn');
            ?>
            <span class="badge <?=$b?>"><?= h($r['status']) ?></span>
            <?php if($r['left_at']): ?>
              <div class="muted">Left at: <?= h($r['left_at']) ?></div>
            <?php endif; ?>
          </td>
          <td><?= h($r['portal_grace_until'] ?: '-') ?></td>

          <td class="row-actions">
            <!-- Set/Reset Password -->
            <form method="post" class="inline-form" style="margin-top:6px">
              <input type="hidden" name="action" value="set_password">
              <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
              <div>
                <label>Password</label>
                <input name="new_password" placeholder="New password">
              </div>
              <div>
                <label>&nbsp;</label>
                <label style="font-size:12px;color:#475569;display:flex;gap:6px;align-items:center">
                  <input type="checkbox" name="gen" value="1"> Generate
                </label>
              </div>
              <div>
                <label>&nbsp;</label>
                <label style="font-size:12px;color:#475569;display:flex;gap:6px;align-items:center">
                  <input type="checkbox" name="force_reset" value="1" <?= $r['portal_force_reset']?'checked':'' ?>> Force reset
                </label>
              </div>
              <button class="btn">Save</button>
            </form>

            <!-- Portal toggle -->
            <form method="post" class="inline-form" style="margin-top:6px">
              <input type="hidden" name="action" value="toggle_portal">
              <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
              <input type="hidden" name="next" value="<?= $r['portal_enabled']?0:1 ?>">
              <button class="btn"><?= $r['portal_enabled']? 'Disable Portal':'Enable Portal' ?></button>
            </form>

            <!-- Status + left_at -->
            <form method="post" class="inline-form" style="margin-top:6px">
              <input type="hidden" name="action" value="set_status">
              <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
              <div>
                <label>Status</label>
                <select name="status">
                  <?php foreach(['ACTIVE','LEFT','SUSPENDED'] as $st): ?>
                    <option <?=$r['status']===$st?'selected':''?>><?=$st?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              <div>
                <label>Left at (opt)</label>
                <input type="date" name="left_at" value="<?= h($r['left_at']) ?>">
              </div>
              <button class="btn">Update</button>
            </form>

            <!-- Grace until -->
            <form method="post" class="inline-form" style="margin-top:6px">
              <input type="hidden" name="action" value="set_grace">
              <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
              <div>
                <label>Grace until</label>
                <input type="date" name="portal_grace_until" value="<?= h($r['portal_grace_until']) ?>">
              </div>
              <button class="btn">Save</button>
            </form>

            <!-- Edit basic info -->
            <details style="margin-top:6px">
              <summary class="btn" style="display:inline-block">Edit info</summary>
              <form method="post" style="margin-top:8px;display:grid;gap:8px">
                <input type="hidden" name="action" value="edit_student">
                <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
                <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:8px">
                  <div style="grid-column:span 6">
                    <label>Full name</label>
                    <input name="full_name" value="<?= h($r['full_name']) ?>" required>
                  </div>
                  <div style="grid-column:span 3">
                    <label>Contact</label>
                    <input name="contact_number" value="<?= h($r['contact_number']) ?>">
                  </div>
                  <div style="grid-column:span 3">
                    <label>Email</label>
                    <input type="email" name="email" value="<?= h($r['email']) ?>">
                  </div>
                  <div style="grid-column:span 12">
                    <label>Address</label>
                    <input name="address" value="<?= h($r['address']) ?>">
                  </div>
                </div>
                <div style="display:flex;gap:8px;justify-content:flex-end">
                  <button class="btn">Save</button>
                </div>
              </form>
            </details>

            <!-- Delete -->
            <form method="post" class="inline-form" style="margin-top:6px" onsubmit="return confirm('Delete this student? Only possible if no registrations/payments exist.');">
              <input type="hidden" name="action" value="delete_student">
              <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
              <button class="btn" style="border-color:#fecaca;color:#991b1b">Delete</button>
            </form>

          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>

<?php admin_footer(); ?>
