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

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

function flash($msg,$ok=true){
  $bg = $ok ? '#f0fdf4' : '#fff1f2';
  $bd = $ok ? '#86efac' : '#fecaca';
  $cl = $ok ? '#065f46' : '#991b1b';
  echo "<div class='card mt-3' style='background:$bg;border-color:$bd;color:$cl'>".h($msg)."</div>";
}

/* ---------------- Search box ---------------- */
$student_id = (int)($_GET['id'] ?? 0);
$q = trim($_GET['q'] ?? '');
$results = null;

if (!$student_id && $q!=='') {
  $qesc = '%'.mysqli_real_escape_string($conn,$q).'%';
  $sql = "SELECT id,full_name,cnic,email,contact_number FROM students
          WHERE full_name LIKE '$qesc' OR cnic LIKE '$qesc' OR email LIKE '$qesc'
          ORDER BY full_name LIMIT 30";
  $results = mysqli_query($conn, $sql);
}

/* ---------------- Handle POST actions ---------------- */
if ($_SERVER['REQUEST_METHOD']==='POST' && hash_equals($CSRF, $_POST['csrf'] ?? '')) {
  $act = $_POST['act'] ?? '';
  $sid = (int)($_POST['sid'] ?? 0);

  if ($act==='update_student' && $sid>0){
    $full = trim($_POST['full_name']??'');
    $father=trim($_POST['father_name']??'');
    $fnum = trim($_POST['father_number']??'');
    $gender=trim($_POST['gender']??'');
    $cnic = trim($_POST['cnic']??'');
    $dob  = $_POST['dob']??'';
    $contact=trim($_POST['contact_number']??'');
    $email=trim($_POST['email']??'');
    $addr =trim($_POST['address']??'');
    $st=mysqli_prepare($conn,"UPDATE students SET full_name=?, father_name=?, father_number=?, gender=?, cnic=?, dob=?, contact_number=?, email=?, address=? WHERE id=?");
    mysqli_stmt_bind_param($st,"sssssssssi",$full,$father,$fnum,$gender,$cnic,$dob,$contact,$email,$addr,$sid);
    mysqli_stmt_execute($st); mysqli_stmt_close($st);
    header("Location: admin_student_manage.php?id=$sid&msg=".urlencode('Profile updated')); exit;
  }

  if ($act==='update_portal' && $sid>0){
    $enabled = (int)($_POST['portal_enabled'] ?? 0);
    $policy  = $_POST['policy'] ?? 'AUTO';
    $grace   = $_POST['grace_until'] ?? null;

    $st=mysqli_prepare($conn,"UPDATE students SET portal_enabled=? WHERE id=?");
    mysqli_stmt_bind_param($st,"ii",$enabled,$sid);
    mysqli_stmt_execute($st); mysqli_stmt_close($st);

    // upsert student_portal_access
    $ck = mysqli_query($conn, "SELECT student_id FROM student_portal_access WHERE student_id=$sid LIMIT 1");
    if (mysqli_fetch_assoc($ck)){
      $up = mysqli_prepare($conn,"UPDATE student_portal_access SET policy=?, grace_until=? WHERE student_id=?");
      mysqli_stmt_bind_param($up,"ssi",$policy,$grace,$sid);
      mysqli_stmt_execute($up); mysqli_stmt_close($up);
    } else {
      $ins = mysqli_prepare($conn,"INSERT INTO student_portal_access(student_id,policy,grace_until) VALUES (?,?,?)");
      mysqli_stmt_bind_param($ins,"iss",$sid,$policy,$grace);
      mysqli_stmt_execute($ins); mysqli_stmt_close($ins);
    }
    header("Location: admin_student_manage.php?id=$sid&msg=".urlencode('Portal settings updated')); exit;
  }

  if ($act==='set_password' && $sid>0){
    $p1 = $_POST['pass'] ?? '';
    $p2 = $_POST['pass2'] ?? '';
    if ($p1==='' || $p1!==$p2){
      header("Location: admin_student_manage.php?id=$sid&err=".urlencode('Passwords do not match')); exit;
    }
    $hash = password_hash($p1, PASSWORD_BCRYPT);
    // ensure students table has password_hash column
    $st = mysqli_prepare($conn,"UPDATE students SET password_hash=? WHERE id=?");
    mysqli_stmt_bind_param($st,"si",$hash,$sid);
    if(!@mysqli_stmt_execute($st)){
      mysqli_stmt_close($st);
      header("Location: admin_student_manage.php?id=$sid&err=".urlencode('Add students.password_hash column first: ALTER TABLE students ADD password_hash VARCHAR(255) NULL;')); exit;
    }
    mysqli_stmt_close($st);
    header("Location: admin_student_manage.php?id=$sid&msg=".urlencode('Password updated')); exit;
  }

  if ($act==='reg_update'){
    $rid = (int)($_POST['rid'] ?? 0);
    $course_id = (int)($_POST['course_id'] ?? 0);
    $batch_id  = (int)($_POST['batch_id'] ?? 0);
    $fee_status= $_POST['fee_status'] ?? 'UNPAID';
    $status    = $_POST['status'] ?? 'ACTIVE';
    if($rid>0 && $sid>0 && $course_id>0 && $batch_id>0){
      $st=mysqli_prepare($conn,"UPDATE registrations SET course_id=?, batch_id=?, fee_status=?, status=? WHERE id=? AND student_id=?");
      mysqli_stmt_bind_param($st,"iissii",$course_id,$batch_id,$fee_status,$status,$rid,$sid);
      mysqli_stmt_execute($st); mysqli_stmt_close($st);
      header("Location: admin_student_manage.php?id=$sid&msg=".urlencode('Registration updated')); exit;
    } else {
      header("Location: admin_student_manage.php?id=$sid&err=".urlencode('Missing fields for registration update')); exit;
    }
  }

  if ($act==='reg_delete'){
    $rid = (int)($_POST['rid'] ?? 0);
    if ($rid>0 && $sid>0){
      // soft safety: do not delete if there are dependent payments (optional check)
      mysqli_query($conn,"DELETE FROM registrations WHERE id=$rid AND student_id=$sid");
      header("Location: admin_student_manage.php?id=$sid&msg=".urlencode('Registration deleted')); exit;
    }
  }

  if ($act==='student_delete'){
    $sid = (int)($_POST['sid'] ?? 0);
    if ($sid>0){
      $c = mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) c FROM registrations WHERE student_id=$sid"));
      if ((int)$c['c']>0){
        header("Location: admin_student_manage.php?id=$sid&err=".urlencode('Cannot delete: student has registrations')); exit;
      }
      mysqli_query($conn,"DELETE FROM students WHERE id=$sid");
      header("Location: admin_student_manage.php?msg=".urlencode('Student deleted')); exit;
    }
  }
}

// If student selected, load details
$student = null; $regs = null;
if ($student_id){
  $st = mysqli_prepare($conn,"SELECT * FROM students WHERE id=? LIMIT 1");
  mysqli_stmt_bind_param($st,"i",$student_id);
  mysqli_stmt_execute($st);
  $r = mysqli_stmt_get_result($st);
  $student = mysqli_fetch_assoc($r);
  mysqli_stmt_close($st);

  $regs = mysqli_query($conn, "
    SELECT r.id,r.reg_no,r.course_id,r.batch_id,r.fee_status,r.status,r.approved_at,
           c.name AS course, b.name AS batch
    FROM registrations r
    JOIN courses c ON c.id=r.course_id
    JOIN batches b ON b.id=r.batch_id
    WHERE r.student_id={$student_id}
    ORDER BY r.approved_at DESC, r.id DESC
  ");
}

// lookups for forms
$courses = mysqli_query($conn,"SELECT id,name FROM courses WHERE is_active=1 ORDER BY name");

admin_header('Manage Student');
$msg = $_GET['msg'] ?? ''; $err = $_GET['err'] ?? '';
?>
<h2 style="margin:0 0 8px">Manage Student</h2>

<!-- Search -->
<div class="card">
  <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
    <input name="q" value="<?=h($q)?>" placeholder="Search name / CNIC / email" style="max-width:300px">
    <button class="btn">Search</button>
    <?php if($student_id): ?><a class="btn" href="admin_student_manage.php">New search</a><?php endif; ?>
  </form>
  <?php if($results): ?>
    <div class="table-wrap mt-3">
      <table>
        <thead><tr><th>ID</th><th>Name</th><th>CNIC</th><th>Email</th><th>Contact</th><th>Open</th></tr></thead>
        <tbody>
          <?php while($s=mysqli_fetch_assoc($results)): ?>
            <tr>
              <td><?=$s['id']?></td>
              <td><?=h($s['full_name'])?></td>
              <td><?=h($s['cnic'])?></td>
              <td><?=h($s['email'])?></td>
              <td><?=h($s['contact_number'])?></td>
              <td><a class="btn" href="admin_student_manage.php?id=<?=$s['id']?>">Manage</a></td>
            </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  <?php endif; ?>
</div>

<?php
if($msg) flash($msg,true);
if($err) flash($err,false);
?>

<?php if($student): ?>
<div class="grid mt-3" style="grid-template-columns:repeat(12,1fr);gap:12px">

  <!-- Profile -->
  <div class="card" style="grid-column:span 6">
    <h3 style="margin:0 0 10px;color:#2563eb">Profile</h3>
    <form method="post">
      <input type="hidden" name="csrf" value="<?=$CSRF?>">
      <input type="hidden" name="act" value="update_student">
      <input type="hidden" name="sid" value="<?=$student['id']?>">

      <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
        <div style="grid-column:span 6"><label>Full Name</label><input name="full_name" value="<?=h($student['full_name'])?>" required></div>
        <div style="grid-column:span 3"><label>Father Name</label><input name="father_name" value="<?=h($student['father_name'])?>"></div>
        <div style="grid-column:span 3"><label>Father Number</label><input name="father_number" value="<?=h($student['father_number'])?>"></div>

        <div style="grid-column:span 3"><label>Gender</label>
          <select name="gender">
            <?php foreach(['Male','Female','Other'] as $g): ?>
              <option <?=$student['gender']===$g?'selected':''?>><?=$g?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div style="grid-column:span 3"><label>CNIC</label><input name="cnic" value="<?=h($student['cnic'])?>" required></div>
        <div style="grid-column:span 3"><label>DOB</label><input type="date" name="dob" value="<?=h($student['dob'])?>"></div>
        <div style="grid-column:span 3"><label>Contact</label><input name="contact_number" value="<?=h($student['contact_number'])?>"></div>

        <div style="grid-column:span 6"><label>Email</label><input type="email" name="email" value="<?=h($student['email'])?>"></div>
        <div style="grid-column:span 12"><label>Address</label><input name="address" value="<?=h($student['address'])?>"></div>
        <div style="grid-column:span 12;display:flex;justify-content:flex-end"><button class="btn primary">Save Profile</button></div>
      </div>
    </form>
  </div>

  <!-- Portal Controls -->
  <div class="card" style="grid-column:span 6">
    <h3 style="margin:0 0 10px;color:#2563eb">Portal Access</h3>
    <?php
      // load portal access row
      $pol = mysqli_query($conn,"SELECT policy,grace_until FROM student_portal_access WHERE student_id={$student_id} LIMIT 1");
      $policy='AUTO'; $grace=null;
      if($pp=mysqli_fetch_assoc($pol)){ $policy=$pp['policy'] ?: 'AUTO'; $grace=$pp['grace_until']; }
    ?>
    <form method="post" style="display:grid;gap:10px">
      <input type="hidden" name="csrf" value="<?=$CSRF?>">
      <input type="hidden" name="act" value="update_portal">
      <input type="hidden" name="sid" value="<?=$student['id']?>">

      <div style="display:flex;gap:12px;align-items:center">
        <label style="display:flex;gap:6px;align-items:center">
          <input type="checkbox" name="portal_enabled" value="1" <?=((int)$student['portal_enabled']===1?'checked':'')?> style="width:auto;height:auto">
          Enabled
        </label>
        <div>
          <label>Policy</label>
          <select name="policy">
            <?php foreach(['AUTO','FORCE_ALLOW','FORCE_BLOCK'] as $p): ?>
              <option <?=$policy===$p?'selected':''?>><?=$p?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div>
          <label>Grace Until</label>
          <input type="date" name="grace_until" value="<?=h($grace)?>">
        </div>
        <div style="margin-left:auto"><button class="btn">Save</button></div>
      </div>
      <div class="muted">AUTO: Paid ya grace date tak access. FORCE_ALLOW: hamesha allow. FORCE_BLOCK: hamesha band.</div>
    </form>

    <hr style="border:none;border-top:1px solid #e5e7eb;margin:12px 0">

    <h4 style="margin:0 0 8px">Reset Password</h4>
    <form method="post" onsubmit="return this.pass.value.length>=6 && this.pass.value===this.pass2.value">
      <input type="hidden" name="csrf" value="<?=$CSRF?>">
      <input type="hidden" name="act" value="set_password">
      <input type="hidden" name="sid" value="<?=$student['id']?>">
      <div style="display:flex;gap:8px;flex-wrap:wrap">
        <input type="password" name="pass" placeholder="New password (min 6)" required style="max-width:220px">
        <input type="password" name="pass2" placeholder="Confirm" required style="max-width:220px">
        <button class="btn">Update</button>
      </div>
      <div class="muted mt-2">Note: Agar error aye to SQL run karein: <code>ALTER TABLE students ADD password_hash VARCHAR(255) NULL;</code></div>
    </form>
  </div>

  <!-- Registrations -->
  <div class="card" style="grid-column:span 12">
    <h3 style="margin:0 0 10px;color:#2563eb">Registrations</h3>
    <?php if(!$regs || mysqli_num_rows($regs)==0): ?>
      <div class="muted">No registrations yet.</div>
    <?php else: ?>
      <div class="table-wrap">
        <table>
          <thead>
            <tr>
              <th>#</th><th>Reg No</th><th>Course</th><th>Batch</th><th>Fee Status</th><th>Status</th><th>Approved</th><th style="width:340px">Update</th><th>Delete</th>
            </tr>
          </thead>
          <tbody>
            <?php while($r=mysqli_fetch_assoc($regs)): ?>
              <tr>
                <td><?=$r['id']?></td>
                <td><?=h($r['reg_no'])?></td>
                <td><?=h($r['course'])?></td>
                <td><?=h($r['batch'])?></td>
                <td><?=h($r['fee_status'])?></td>
                <td><?=h($r['status'])?></td>
                <td><?=h($r['approved_at'])?></td>
                <td>
                  <form method="post" style="display:flex;gap:6px;flex-wrap:wrap;align-items:center">
                    <input type="hidden" name="csrf" value="<?=$CSRF?>">
                    <input type="hidden" name="act" value="reg_update">
                    <input type="hidden" name="sid" value="<?=$student['id']?>">
                    <input type="hidden" name="rid" value="<?=$r['id']?>">

                    <!-- Course -->
                    <select name="course_id" onchange="loadBatches(this, 'b<?=$r['id']?>')" required>
                      <?php mysqli_data_seek($courses,0); while($c=mysqli_fetch_assoc($courses)): ?>
                        <option value="<?=$c['id']?>" <?=$c['name']===$r['course']?'selected':''?>><?=h($c['name'])?></option>
                      <?php endwhile; ?>
                    </select>

                    <!-- Batch (will be filled by JS on first change; also show current) -->
                    <select name="batch_id" id="b<?=$r['id']?>" required>
                      <option value="<?=$r['batch_id']?>"><?=h($r['batch'])?> (current)</option>
                    </select>

                    <select name="fee_status">
                      <?php foreach(['UNPAID','PARTIAL','PAID'] as $fs): ?>
                        <option <?=$r['fee_status']===$fs?'selected':''?>><?=$fs?></option>
                      <?php endforeach; ?>
                    </select>

                    <select name="status">
                      <?php foreach(['ACTIVE','INACTIVE','COMPLETED','CANCELLED'] as $st): ?>
                        <option <?=$r['status']===$st?'selected':''?>><?=$st?></option>
                      <?php endforeach; ?>
                    </select>

                    <button class="btn">Save</button>
                  </form>
                </td>
                <td>
                  <form method="post" onsubmit="return confirm('Delete this registration?')">
                    <input type="hidden" name="csrf" value="<?=$CSRF?>">
                    <input type="hidden" name="act" value="reg_delete">
                    <input type="hidden" name="sid" value="<?=$student['id']?>">
                    <input type="hidden" name="rid" value="<?=$r['id']?>">
                    <button class="btn" style="border-color:#fecaca;color:#991b1b">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

  <!-- Danger Zone -->
  <div class="card" style="grid-column:span 12">
    <h3 style="margin:0 0 8px;color:#b91c1c">Danger Zone</h3>
    <form method="post" onsubmit="return confirm('Delete student? Only if no registrations exist.')">
      <input type="hidden" name="csrf" value="<?=$CSRF?>">
      <input type="hidden" name="act" value="student_delete">
      <input type="hidden" name="sid" value="<?=$student['id']?>">
      <button class="btn" style="border-color:#fecaca;color:#b91c1c">Delete Student</button>
    </form>
  </div>
</div>
<?php endif; ?>

<script>
// Load batches for selected course (AJAX-like via fetch to a tiny helper)
// We'll call an inline endpoint on the same page using GET with action=get_batches
async function loadBatches(courseSel, targetId){
  const course_id = courseSel.value;
  const el = document.getElementById(targetId);
  el.innerHTML = '<option>Loading...</option>';
  const resp = await fetch('get_batches.php?course_id='+encodeURIComponent(course_id));
  const data = await resp.json();
  el.innerHTML = '';
  if (data.ok && data.rows.length){
    data.rows.forEach(b=>{
      const o=document.createElement('option');
      o.value=b.id; o.textContent = `${b.name} (${b.status} • ${b.start_date})`;
      el.appendChild(o);
    });
  } else {
    const o=document.createElement('option');
    o.textContent='No batches'; o.value='';
    el.appendChild(o);
  }
}
</script>

<?php admin_footer(); ?>
