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

// small helpers
function _post($k,$d=''){ return isset($_POST[$k]) ? trim($_POST[$k]) : $d; }
function _get($k,$d=''){ return isset($_GET[$k])  ? trim($_GET[$k])  : $d; }

// messages
$msg = _get('msg','');
$err = _get('err','');

// ---------------------------------------------
// CREATE
// ---------------------------------------------
if ($_SERVER['REQUEST_METHOD']==='POST' && (_post('action')==='create')) {
  $full_name     = _post('full_name');
  $father_name   = _post('father_name');
  $father_number = _post('father_number');
  $gender        = _post('gender'); // optional column
  $cnic          = _post('cnic');
  $dob           = _post('dob');
  $contact       = _post('contact_number');
  $email         = _post('email');
  $address       = _post('address');

  if ($full_name!=='' && $cnic!=='' && $contact!=='') {
    // try with gender first; fallback without if column missing
    $sql = "INSERT INTO students
      (full_name, father_name, father_number, gender, cnic, dob, contact_number, email, address, created_at)
      VALUES (?,?,?,?,?,?,?,?,?,NOW())";
    $st = mysqli_prepare($conn, $sql);
    if(!$st){ die("Prepare failed: ".mysqli_error($conn)); }
    mysqli_stmt_bind_param($st, "sssssssss",
      $full_name,$father_name,$father_number,$gender,$cnic,$dob,$contact,$email,$address
    );
    if (!mysqli_stmt_execute($st)) {
      if (strpos(mysqli_stmt_error($st), "Unknown column 'gender'") !== false) {
        mysqli_stmt_close($st);
        $sql2 = "INSERT INTO students
          (full_name, father_name, father_number, cnic, dob, contact_number, email, address, created_at)
          VALUES (?,?,?,?,?,?,?,?,NOW())";
        $st2 = mysqli_prepare($conn, $sql2);
        mysqli_stmt_bind_param($st2, "ssssssss",
          $full_name,$father_name,$father_number,$cnic,$dob,$contact,$email,$address
        );
        if(!mysqli_stmt_execute($st2)){ die("Insert failed: ".mysqli_stmt_error($st2)); }
        mysqli_stmt_close($st2);
      } else {
        die("Insert failed: ".mysqli_stmt_error($st));
      }
    } else {
      mysqli_stmt_close($st);
    }
    header("Location: students_manage.php?msg=".urlencode('Student added'));
    exit;
  } else {
    header("Location: students_manage.php?err=".urlencode('Full Name, CNIC, Contact are required'));
    exit;
  }
}

// ---------------------------------------------
// UPDATE
// ---------------------------------------------
if ($_SERVER['REQUEST_METHOD']==='POST' && (_post('action')==='update')) {
  $id            = (int)_post('id',0);
  $full_name     = _post('full_name');
  $father_name   = _post('father_name');
  $father_number = _post('father_number');
  $gender        = _post('gender');
  $cnic          = _post('cnic');
  $dob           = _post('dob');
  $contact       = _post('contact_number');
  $email         = _post('email');
  $address       = _post('address');

  if ($id>0 && $full_name!=='' && $cnic!=='' && $contact!=='') {
    $sql = "UPDATE students
              SET full_name=?, father_name=?, father_number=?, gender=?, cnic=?, dob=?, contact_number=?, email=?, address=?
            WHERE id=?";
    $st = mysqli_prepare($conn, $sql);
    if(!$st){ die("Prepare failed: ".mysqli_error($conn)); }
    mysqli_stmt_bind_param($st, "sssssssssi",
      $full_name,$father_name,$father_number,$gender,$cnic,$dob,$contact,$email,$address,$id
    );
    if(!mysqli_stmt_execute($st)){
      if (strpos(mysqli_stmt_error($st), "Unknown column 'gender'") !== false) {
        mysqli_stmt_close($st);
        $sql2 = "UPDATE students
                   SET full_name=?, father_name=?, father_number=?, cnic=?, dob=?, contact_number=?, email=?, address=?
                 WHERE id=?";
        $st2 = mysqli_prepare($conn, $sql2);
        mysqli_stmt_bind_param($st2, "ssssssssi",
          $full_name,$father_name,$father_number,$cnic,$dob,$contact,$email,$address,$id
        );
        if(!mysqli_stmt_execute($st2)){ die("Update failed: ".mysqli_stmt_error($st2)); }
        mysqli_stmt_close($st2);
      } else {
        die("Update failed: ".mysqli_stmt_error($st));
      }
    } else {
      mysqli_stmt_close($st);
    }
    header("Location: students_manage.php?msg=".urlencode('Student updated'));
    exit;
  } else {
    header("Location: students_manage.php?err=".urlencode('Required fields missing'));
    exit;
  }
}

// ---------------------------------------------
// DELETE (block if has registrations)
// ---------------------------------------------
if ($_SERVER['REQUEST_METHOD']==='POST' && (_post('action')==='delete')) {
  $id = (int)_post('id',0);
  if ($id>0) {
    $ck = mysqli_prepare($conn, "SELECT COUNT(*) c FROM registrations WHERE student_id=?");
    mysqli_stmt_bind_param($ck, "i", $id);
    mysqli_stmt_execute($ck);
    $res = mysqli_stmt_get_result($ck);
    $num = (int)mysqli_fetch_assoc($res)['c'];
    mysqli_stmt_close($ck);

    if ($num>0) {
      header("Location: students_manage.php?err=".urlencode('Cannot delete: student has registrations'));
      exit;
    }
    $del = mysqli_prepare($conn, "DELETE FROM students WHERE id=?");
    mysqli_stmt_bind_param($del, "i", $id);
    mysqli_stmt_execute($del);
    mysqli_stmt_close($del);

    header("Location: students_manage.php?msg=".urlencode('Student deleted'));
    exit;
  }
}

// ---------------------------------------------
// SEARCH + PAGINATION (stacked UI, simple)
// ---------------------------------------------
$q        = _get('q','');
$page     = max(1, (int)_get('page',1));
$per_page = 20;
$offset   = ($page-1)*$per_page;

$where = " WHERE 1=1 ";
if ($q!=='') {
  $esc = mysqli_real_escape_string($conn, $q);
  $where .= " AND (s.full_name LIKE '%$esc%' OR s.cnic LIKE '%$esc%' OR s.contact_number LIKE '%$esc%' OR s.email LIKE '%$esc%') ";
}

$total = (int)mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) c FROM students s $where"))['c'];
$pages = max(1, (int)ceil($total/$per_page));

// list
$sql = "
SELECT id, full_name, father_name, father_number, gender, cnic, dob, contact_number, email, address, created_at
FROM students s
$where
ORDER BY created_at DESC
LIMIT $per_page OFFSET $offset
";
$rows = mysqli_query($conn, $sql);

// --------------------------------------------------
// UI
// --------------------------------------------------
admin_header('Students — Manage');
?>
<h2 style="margin:0 0 8px">Students — Manage</h2>

<?php if($msg): ?><div class="card col-12 flash info" style="margin-bottom:10px"><?=h($msg)?></div><?php endif; ?>
<?php if($err): ?><div class="card col-12 flash error" style="margin-bottom:10px"><?=h($err)?></div><?php endif; ?>

<!-- 1) Search (Section 1) -->
<div class="card col-12" style="margin-bottom:12px">
  <h3 style="margin:0 0 8px;color:#2563eb">Search</h3>
  <form method="get" style="display:flex;gap:8px;flex-wrap:wrap">
    <input name="q" value="<?=h($q)?>" placeholder="Search by name / CNIC / phone / email..." style="min-width:280px">
    <button class="btn">Apply</button>
    <a class="btn" href="students_manage.php">Reset</a>
  </form>
  <div style="margin-top:8px;font-size:12px;color:#64748b">Showing <?=min($per_page,$total-$offset)?> of <?=$total?> results</div>
</div>

<!-- 2) Add Student (Section 2) -->
<div class="card col-12" style="margin-bottom:12px; position:relative; overflow:hidden">
  <div style="position:absolute;right:-24px;top:-24px;width:120px;height:120px;background:linear-gradient(135deg,#bfdbfe,#93c5fd);opacity:.25;border-radius:50%"></div>
  <h3 style="margin:0 0 12px;color:#2563eb">Add Student</h3>
  <form method="post" style="display:grid;gap:10px">
    <input type="hidden" name="action" value="create">

    <label>Full Name</label>
    <input name="full_name" required>

    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
      <div style="grid-column:span 6"><label>Father’s Name</label><input name="father_name"></div>
      <div style="grid-column:span 6"><label>Father’s Number</label><input name="father_number" placeholder="03xx-xxxxxxx"></div>
    </div>

    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
      <div style="grid-column:span 3">
        <label>Gender</label>
        <select name="gender">
          <option value="">— Select —</option>
          <option>Male</option><option>Female</option><option>Other</option>
        </select>
      </div>
      <div style="grid-column:span 3">
        <label>CNIC / B-Form</label>
        <input name="cnic" placeholder="xxxxx-xxxxxxx-x" required>
      </div>
      <div style="grid-column:span 3">
        <label>DOB</label>
        <input type="date" name="dob">
      </div>
      <div style="grid-column:span 3">
        <label>Contact</label>
        <input name="contact_number" placeholder="03xx-xxxxxxx" required>
      </div>
    </div>

    <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
      <div style="grid-column:span 6"><label>Email</label><input type="email" name="email"></div>
      <div style="grid-column:span 6"><label>Address</label><input name="address"></div>
    </div>

    <div style="display:flex;justify-content:flex-end">
      <button class="btn primary">Add Student</button>
    </div>
  </form>
</div>

<!-- 3) Students Table (Section 3) -->
<div class="card col-12">
  <h3 style="margin:0 0 8px;color:#2563eb">Students List</h3>
  <div class="table-wrap">
    <table style="min-width:1100px">
      <thead>
        <tr>
          <th>#</th>
          <th style="text-align:left">Name</th>
          <th>CNIC</th>
          <th>Contact</th>
          <th style="text-align:left">Email</th>
          <th>DOB</th>
          <th style="text-align:left">Address</th>
          <th>Joined</th>
          <th style="width:220px">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $has=false;
        while($r = mysqli_fetch_assoc($rows)): $has=true; ?>
          <tr id="row-<?=$r['id']?>">
            <td style="text-align:center"><?= (int)$r['id'] ?></td>
            <td style="font-weight:600">
              <?=h($r['full_name'])?>
              <?php if(!empty($r['gender'])): ?>
                <span class="badge" style="margin-left:6px;background:#e2e8f0;border:1px solid #cbd5e1;color:#334155"><?=h($r['gender'])?></span>
              <?php endif; ?>
              <?php if(!empty($r['father_name'])): ?>
                <div style="font-size:12px;color:#64748b">Father: <?=h($r['father_name'])?> <?=!empty($r['father_number'])?'('.h($r['father_number']).')':''?></div>
              <?php endif; ?>
            </td>
            <td style="text-align:center"><?=h($r['cnic'])?></td>
            <td style="text-align:center"><?=h($r['contact_number'])?></td>
            <td><?=h($r['email'])?></td>
            <td style="text-align:center"><?=h($r['dob'])?></td>
            <td><?=h($r['address'])?></td>
            <td style="text-align:center"><?=h(substr($r['created_at'],0,10))?></td>
            <td style="text-align:center;white-space:nowrap">
              <button class="btn editBtn" data-id="<?=$r['id']?>" style="padding:6px 10px;border-color:#bfdbfe">Edit</button>
              <form method="post" style="display:inline" onsubmit="return confirm('Delete this student? This cannot be undone.')">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?=$r['id']?>">
                <button class="btn" style="padding:6px 10px;margin-left:6px;border-color:#fecaca;color:#991b1b">Delete</button>
              </form>
            </td>
          </tr>

          <!-- inline editor row -->
          <tr id="edit-<?=$r['id']?>" class="editRow" style="display:none;background:#f8fafc">
            <td colspan="9">
              <form method="post" style="display:grid;gap:10px">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?=$r['id']?>">

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

                <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                  <div style="grid-column:span 3">
                    <label>Gender</label>
                    <select name="gender">
                      <option value="">— Select —</option>
                      <option <?=($r['gender']==='Male'?'selected':'')?>>Male</option>
                      <option <?=($r['gender']==='Female'?'selected':'')?>>Female</option>
                      <option <?=($r['gender']==='Other'?'selected':'')?>>Other</option>
                    </select>
                  </div>
                  <div style="grid-column:span 3"><label>CNIC</label><input name="cnic" value="<?=h($r['cnic'])?>" required></div>
                  <div style="grid-column:span 3"><label>DOB</label><input type="date" name="dob" value="<?=h($r['dob'])?>"></div>
                  <div style="grid-column:span 3"><label>Contact</label><input name="contact_number" value="<?=h($r['contact_number'])?>" required></div>
                </div>

                <div class="grid" style="grid-template-columns:repeat(12,1fr);gap:10px">
                  <div style="grid-column:span 6"><label>Email</label><input type="email" name="email" value="<?=h($r['email'])?>"></div>
                  <div style="grid-column:span 6"><label>Address</label><input name="address" value="<?=h($r['address'])?>"></div>
                </div>

                <div style="display:flex;justify-content:flex-end">
                  <button class="btn primary">Save Changes</button>
                </div>
              </form>
            </td>
          </tr>
        <?php endwhile; ?>
        <?php if(!$has): ?>
          <tr><td colspan="9" style="text-align:center;padding:24px;color:#64748b">No students found.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- pagination -->
  <div style="display:flex;gap:6px;justify-content:flex-end;margin-top:10px" class="pager">
    <?php
      if ($pages>1) {
        $base = $_GET; unset($base['page']);
        for($p=1;$p<=$pages;$p++){
          $qs = http_build_query(array_merge($base,['page'=>$p]));
          $cls = ($p==$page)?'active':'';
          echo '<a class="'.$cls.'" href="students_manage.php?'.$qs.'" style="padding:6px 10px;border:1px solid #e5e7eb;border-radius:8px;text-decoration:none'.($cls?' ;background:#2563eb;color:#fff;border-color:#2563eb':'').'">'.$p.'</a>';
        }
      }
    ?>
  </div>
</div>

<script>
// open/close inline edit rows (stacked UI me same page)
document.querySelectorAll('.editBtn').forEach(btn=>{
  btn.addEventListener('click', ()=>{
    const id = btn.dataset.id;
    const row = document.getElementById('edit-'+id);
    document.querySelectorAll('.editRow').forEach(r=>{ if(r!==row) r.style.display='none'; });
    row.style.display = (row.style.display==='none'||row.style.display==='') ? 'table-row' : 'none';
    row.scrollIntoView({behavior:'smooth', block:'center'});
  });
});
</script>

<?php admin_footer(); ?>
