<?php
session_start();

require_once '../includes/access_control.php';
require_once '../config/database.php';
require_once '../includes/sidebar_layout.php';
require_once '../includes/site_settings.php';

require_any_role(['admin', 'teacher']);

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$logo_image = $settings['logo_image'] ?? null;
$system_name = get_system_name($pdo);

// ── Bulk assign branch to students without branch ──────────────────────────
$bulk_msg = '';
$bulk_err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_assign_branch') {
    if ($user_role !== 'admin') {
        $bulk_err = 'শুধু অ্যাডমিন এই কাজ করতে পারবেন।';
    } else {
        $bulk_class_id  = (int)($_POST['bulk_class_id']  ?? 0);
        $bulk_branch_id = (int)($_POST['bulk_branch_id'] ?? 0);
        $bulk_session   = trim($_POST['bulk_session'] ?? '');
        if (!$bulk_class_id || !$bulk_branch_id) {
            $bulk_err = 'ক্লাস এবং শাখা উভয়ই নির্বাচন করুন।';
        } else {
            try {
                $sql = "UPDATE students SET branch_id = ?
                        WHERE class_id = ? AND (branch_id IS NULL OR branch_id = 0)";
                $bp  = [$bulk_branch_id, $bulk_class_id];
                if ($bulk_session !== '') { $sql .= ' AND session = ?'; $bp[] = $bulk_session; }
                $st = $pdo->prepare($sql);
                $st->execute($bp);
                $n = $st->rowCount();
                $bulk_msg = "✓ $n জন শিক্ষার্থীর শাখা নির্ধারণ করা হয়েছে।";
            } catch (Exception $e) {
                $bulk_err = 'ত্রুটি: ' . $e->getMessage();
            }
        }
    }
}

$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$logo_image = $settings['logo_image'] ?? null;
$system_name = get_system_name($pdo);

$teacher_id = null;
$assigned_class_ids = [];
if ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
        $stmt = $pdo->prepare("SELECT DISTINCT c.id FROM classes c WHERE (c.class_teacher_id = ? OR c.id IN (SELECT class_id FROM class_subjects WHERE teacher_id = ?)) AND c.status = 'active'");
        $stmt->execute([$teacher_id, $teacher_id]);
        $assigned_classes = $stmt->fetchAll();
        $assigned_class_ids = array_column($assigned_classes, 'id');
    }
}

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$offset = ($page - 1) * $limit;

$search            = isset($_GET['search'])         ? trim($_GET['search'])         : '';
$class_filter      = isset($_GET['class_id'])       ? (int)$_GET['class_id']        : 0;
$status_filter     = isset($_GET['status'])         ? $_GET['status']               : 'active';
$first_name        = isset($_GET['first_name'])     ? trim($_GET['first_name'])     : '';
$last_name         = isset($_GET['last_name'])      ? trim($_GET['last_name'])      : '';
$student_id_search = isset($_GET['student_id'])     ? trim($_GET['student_id'])     : '';
$roll_number_search= isset($_GET['roll_number'])    ? trim($_GET['roll_number'])    : '';
$email_search      = isset($_GET['email'])          ? trim($_GET['email'])          : '';
$phone_search      = isset($_GET['phone'])          ? trim($_GET['phone'])          : '';
$session_search    = isset($_GET['session'])        ? trim($_GET['session'])        : '';
$group_name_search = isset($_GET['group_name'])     ? trim($_GET['group_name'])     : '';
$guardian_name_search  = isset($_GET['guardian_name'])  ? trim($_GET['guardian_name'])  : '';
$guardian_phone_search = isset($_GET['guardian_phone']) ? trim($_GET['guardian_phone']) : '';
$gender_filter     = isset($_GET['gender'])         ? $_GET['gender']               : '';
$section_filter    = isset($_GET['section'])        ? trim($_GET['section'])        : '';

$sort_by    = isset($_GET['sort_by'])    ? $_GET['sort_by']    : 'roll_number';
$sort_order = isset($_GET['sort_order']) ? $_GET['sort_order'] : 'ASC';
$allowed_sort_fields  = ['first_name','last_name','student_id','roll_number','created_at','class_name'];
$allowed_sort_orders  = ['ASC','DESC'];
if (!in_array($sort_by, $allowed_sort_fields))  $sort_by    = 'created_at';
if (!in_array($sort_order, $allowed_sort_orders)) $sort_order = 'DESC';

$where_conditions = ["s.status = :status"];
$params = ['status' => $status_filter];

if (!empty($search)) {
    $where_conditions[] = "(s.first_name LIKE :sf OR s.last_name LIKE :sl OR s.student_id LIKE :si OR s.email LIKE :se OR s.phone LIKE :sp)";
    $params['sf'] = $params['sl'] = $params['si'] = $params['se'] = $params['sp'] = "%$search%";
}
if (!empty($first_name))           { $where_conditions[] = "s.first_name LIKE :first_name";           $params['first_name']           = "%$first_name%"; }
if (!empty($last_name))            { $where_conditions[] = "s.last_name LIKE :last_name";             $params['last_name']            = "%$last_name%"; }
if (!empty($student_id_search))    { $where_conditions[] = "s.student_id LIKE :student_id_search";    $params['student_id_search']    = "%$student_id_search%"; }
if (!empty($roll_number_search))   { $where_conditions[] = "s.roll_number = :roll_number_search";     $params['roll_number_search']   = $roll_number_search; }
if (!empty($email_search))         { $where_conditions[] = "s.email LIKE :email_search";              $params['email_search']         = "%$email_search%"; }
if (!empty($phone_search))         { $where_conditions[] = "s.phone LIKE :phone_search";              $params['phone_search']         = "%$phone_search%"; }
if (!empty($session_search))       { $where_conditions[] = "s.session LIKE :session_search";          $params['session_search']       = "%$session_search%"; }
if (!empty($group_name_search))    { $where_conditions[] = "s.group_name LIKE :group_name_search";    $params['group_name_search']    = "%$group_name_search%"; }
if (!empty($guardian_name_search)) { $where_conditions[] = "s.guardian_name LIKE :guardian_name_search"; $params['guardian_name_search'] = "%$guardian_name_search%"; }
if (!empty($guardian_phone_search)){ $where_conditions[] = "s.guardian_phone LIKE :guardian_phone_search"; $params['guardian_phone_search'] = "%$guardian_phone_search%"; }
if (!empty($gender_filter))        { $where_conditions[] = "s.gender = :gender_filter";               $params['gender_filter']        = $gender_filter; }
if ($class_filter > 0)             { $where_conditions[] = "s.class_id = :class_id";                  $params['class_id']             = $class_filter; }
if (!empty($section_filter))       { $where_conditions[] = "c.section = :section_filter";             $params['section_filter']       = $section_filter; }

$branch_filter = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
if ($branch_filter > 0)            { $where_conditions[] = "s.branch_id = :branch_id";               $params['branch_id']            = $branch_filter; }

$where_clause = implode(' AND ', $where_conditions);

$count_stmt = $pdo->prepare("SELECT COUNT(*) FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE $where_clause");
$count_stmt->execute($params);
$total_records = $count_stmt->fetchColumn();
$total_pages   = ceil($total_records / $limit);

$sql = "SELECT s.id, s.student_id, s.first_name, s.last_name, s.photo, s.roll_number, s.session, s.group_name, s.phone, s.gender, s.status, s.created_at, c.name as class_name, c.section as class_section, sb.branch_name FROM students s LEFT JOIN classes c ON s.class_id = c.id LEFT JOIN school_branches sb ON s.branch_id = sb.id WHERE $where_clause ORDER BY $sort_by $sort_order LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
foreach ($params as $key => $value) { $stmt->bindValue(":$key", $value); }
$stmt->bindValue(':limit',  $limit,  PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$students = $stmt->fetchAll();

if ($user_role == 'teacher' && !empty($assigned_class_ids)) {
    $ph = str_repeat('?,', count($assigned_class_ids) - 1) . '?';
    $cs = $pdo->prepare("SELECT id, name, section FROM classes WHERE id IN ($ph) AND status='active' ORDER BY name, section");
    $cs->execute($assigned_class_ids);
} else {
    $cs = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section");
}
$classes = $cs->fetchAll();

$sections = $pdo->query("SELECT DISTINCT section FROM classes WHERE status='active' ORDER BY section")->fetchAll(PDO::FETCH_COLUMN);

$branches = $pdo->query("SELECT id, branch_name FROM school_branches WHERE status='active' ORDER BY branch_name")->fetchAll();
$groups = $pdo->query("SELECT group_name, group_code FROM student_groups WHERE status='active' ORDER BY group_name")->fetchAll();
$sessions_list = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC")->fetchAll(PDO::FETCH_COLUMN);

$stats_stmt = $pdo->query("SELECT COUNT(*) as total, SUM(CASE WHEN status='active' THEN 1 ELSE 0 END) as active_count, SUM(CASE WHEN gender='male' THEN 1 ELSE 0 END) as male_count, SUM(CASE WHEN gender='female' THEN 1 ELSE 0 END) as female_count FROM students");
$stats = $stats_stmt->fetch();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>ছাত্র-ছাত্রী তালিকা</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<link href="../assets/css/sidebar.css" rel="stylesheet">
<style>
:root{--g:#006747;--b:#1565c0;--o:#fb8500;--p:#7209b7;--pk:#e63946;--t:#06d6a0}
body{background:#f0f4ff;font-size:.82rem}
.tc{border:none;border-radius:10px;box-shadow:0 2px 12px rgba(0,0,0,.08);overflow:hidden}
.tc .ch{background:linear-gradient(135deg,var(--g),#004d35);color:#fff;padding:8px 14px;font-weight:700;font-size:.85rem;display:flex;align-items:center;justify-content:space-between}
.tc .cb{padding:10px}
.sc{border-radius:10px;padding:10px 14px;color:#fff;position:relative;overflow:hidden;border:none;box-shadow:0 3px 10px rgba(0,0,0,.1);transition:.2s}
.sc:hover{transform:translateY(-2px);box-shadow:0 6px 16px rgba(0,0,0,.15)}
.sc .si{position:absolute;right:10px;top:50%;transform:translateY(-50%);font-size:2rem;opacity:.18}
.sc .sn{font-size:1.4rem;font-weight:800;line-height:1}
.sc .sl{font-size:.72rem;opacity:.9;margin-top:2px}
.sc-s{background:linear-gradient(135deg,#4361ee,#3a0ca3)}
.sc-a{background:linear-gradient(135deg,#06d6a0,#028a5b)}
.sc-m{background:linear-gradient(135deg,#4cc9f0,#0077b6)}
.sc-f{background:linear-gradient(135deg,#f72585,#b5179e)}
.qs{background:#fff;border-radius:50px;box-shadow:0 2px 10px rgba(0,0,0,.08);display:flex;align-items:center;padding:4px 4px 4px 16px;gap:6px}
.qs input{border:none;outline:none;flex:1;font-size:.85rem;background:transparent}
.qs .btn-s{background:linear-gradient(135deg,var(--g),#004d35);color:#fff;border:none;border-radius:50px;padding:6px 16px;font-weight:600;font-size:.8rem}
.sl-tbl{width:100%;border-collapse:collapse;font-size:.8rem}
.sl-tbl thead tr{background:linear-gradient(90deg,#1a1a2e,#16213e);color:#fff}
.sl-tbl thead th{padding:8px 10px;font-size:.74rem;font-weight:700;border:none;white-space:nowrap}
.sl-tbl thead th a{color:#fff;text-decoration:none}
.sl-tbl thead th a:hover{color:#ffd700}
.sl-tbl tbody tr{border-bottom:1px solid #f0f0f0;transition:.15s}
.sl-tbl tbody tr:hover{background:#f0faf5 !important}
.sl-tbl tbody td{padding:7px 10px;vertical-align:middle}
.sl-tbl tbody tr:nth-child(odd){background:#f8f9ff}
.cb{background:linear-gradient(135deg,#4361ee22,#4361ee44);color:#4361ee;border-radius:6px;padding:2px 8px;font-size:.72rem;font-weight:700;white-space:nowrap}
.sb{background:#f0faf5;color:var(--g);border-radius:6px;padding:2px 8px;font-size:.72rem;font-weight:600}
.gb{background:linear-gradient(135deg,#fb850022,#fb850044);color:#c96a00;border-radius:6px;padding:2px 8px;font-size:.72rem;font-weight:600}
.sa{background:#d4f5e9;color:#028a5b;border-radius:20px;padding:2px 10px;font-size:.72rem;font-weight:700}
.si-in{background:#fde8e8;color:#c0392b;border-radius:20px;padding:2px 10px;font-size:.72rem;font-weight:700}
.ab{width:26px;height:26px;border-radius:6px;border:none;display:inline-flex;align-items:center;justify-content:center;font-size:.72rem;cursor:pointer;transition:.2s;text-decoration:none}
.ab-v{background:#e8f4fd;color:#0077b6}.ab-e{background:#fff3e0;color:#e65100}.ab-d{background:#fde8e8;color:#c0392b}
.ab-v:hover{background:#0077b6;color:#fff}.ab-e:hover{background:#e65100;color:#fff}.ab-d:hover{background:#c0392b;color:#fff}
.rn{font-weight:800;color:#4361ee;font-size:.85rem}
.av{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid #e0e0e0}
.avp{width:32px;height:32px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-size:.8rem;color:#fff;font-weight:700}
.pg{min-width:28px;height:28px;border-radius:6px;border:1px solid #e0e0e0;background:#fff;color:#333;font-size:.78rem;font-weight:600;display:inline-flex;align-items:center;justify-content:center;text-decoration:none;transition:.2s;padding:0 6px}
.pg:hover,.pg.act{background:linear-gradient(135deg,var(--g),#004d35);color:#fff;border-color:transparent}
.pg.dis{opacity:.4;pointer-events:none}
.fs{font-size:.68rem !important}
.ff{display:none}
@media print{.no-print{display:none !important}body{background:#fff}.tc{box-shadow:none;border:1px solid #ccc}}
</style>
</head>
<body>
<div class="sidebar-container">
<?php echo renderSidebar('students/list.php', $user_role, $user_name); ?>
<div class="main-content"><div class="container-fluid py-2 px-3">

<?php if ($success_message ?? null): ?><div class="alert alert-success alert-dismissible fade show py-1 px-3 mb-2 small"><i class="fas fa-check-circle"></i> <?=$success_message?><button type="button" class="btn-close btn-close-sm" data-bs-dismiss="alert"></button></div><?php endif;?>

<!-- Stats -->
<div class="row g-2 mb-2">
<div class="col-6 col-md-3"><div class="sc sc-s"><div class="sn"><?=number_format($stats['total']??0)?></div><div class="sl"><i class="fas fa-users me-1"></i>মোট</div><div class="si"><i class="fas fa-users"></i></div></div></div>
<div class="col-6 col-md-3"><div class="sc sc-a"><div class="sn"><?=number_format($stats['active_count']??0)?></div><div class="sl"><i class="fas fa-check-circle me-1"></i>সক্রিয়</div><div class="si"><i class="fas fa-check-circle"></i></div></div></div>
<div class="col-6 col-md-3"><div class="sc sc-m"><div class="sn"><?=number_format($stats['male_count']??0)?></div><div class="sl"><i class="fas fa-mars me-1"></i>ছাত্র</div><div class="si"><i class="fas fa-mars"></i></div></div></div>
<div class="col-6 col-md-3"><div class="sc sc-f"><div class="sn"><?=number_format($stats['female_count']??0)?></div><div class="sl"><i class="fas fa-venus me-1"></i>ছাত্রী</div><div class="si"><i class="fas fa-venus"></i></div></div></div>
</div>

<!-- Bulk Branch Assignment Panel (admin only) -->
<?php if ($user_role === 'admin' && !empty($branches)): ?>
<?php
// Count students without branch per class for display hint
$noBranchCount = 0;
if (!empty($_POST['bulk_class_id']) || true) {
    try {
        $noBranchCount = $pdo->query("SELECT COUNT(*) FROM students WHERE (branch_id IS NULL OR branch_id = 0) AND status='active'")->fetchColumn();
    } catch (Exception $e) {}
}
?>
<div style="background:rgba(67,97,238,.06);border:1.5px solid rgba(67,97,238,.2);border-radius:10px;padding:12px 16px;margin-bottom:12px">
  <div class="d-flex align-items-center gap-2 mb-2 flex-wrap">
    <i class="fas fa-code-branch" style="color:#4361ee"></i>
    <strong style="font-size:.85rem;color:#1a1a2e">ক্লাসভিত্তিক শাখা বাল্ক নির্ধারণ</strong>
    <span style="font-size:.72rem;color:#888">(যেসব শিক্ষার্থীর শাখা নেই তাদের জন্য)</span>
    <?php if ($noBranchCount > 0): ?>
    <span class="badge bg-warning text-dark" style="font-size:.72rem"><?= $noBranchCount ?> জনের শাখা নেই</span>
    <?php endif; ?>
  </div>

  <?php if ($bulk_msg): ?>
  <div class="alert alert-success py-1 px-3 mb-2" style="font-size:.82rem"><i class="fas fa-check-circle me-1"></i><?= htmlspecialchars($bulk_msg) ?></div>
  <?php endif; ?>
  <?php if ($bulk_err): ?>
  <div class="alert alert-danger py-1 px-3 mb-2" style="font-size:.82rem"><i class="fas fa-exclamation-triangle me-1"></i><?= htmlspecialchars($bulk_err) ?></div>
  <?php endif; ?>

  <form method="POST" onsubmit="return confirmBulk(this)">
    <input type="hidden" name="action" value="bulk_assign_branch">
    <div class="row g-2 align-items-end">
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">
          ক্লাস <span class="text-danger">*</span>
        </label>
        <select name="bulk_class_id" class="form-select form-select-sm" required
                onchange="loadNoBranchCount(this.value)">
          <option value="">-- ক্লাস নির্বাচন --</option>
          <?php foreach ($classes as $c): ?>
            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['name'] . ($c['section'] ? '-' . $c['section'] : '')) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">সেশন (ঐচ্ছিক)</label>
        <select name="bulk_session" class="form-select form-select-sm">
          <option value="">সব সেশন</option>
          <?php foreach ($sessions_list as $ses): ?>
            <option value="<?= htmlspecialchars($ses) ?>"><?= htmlspecialchars($ses) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-3">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">
          শাখা <span class="text-danger">*</span>
        </label>
        <select name="bulk_branch_id" class="form-select form-select-sm" required>
          <option value="">-- শাখা নির্বাচন --</option>
          <?php foreach ($branches as $br): ?>
            <option value="<?= $br['id'] ?>"><?= htmlspecialchars($br['branch_name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-6 col-md-2">
        <label style="font-size:.75rem;font-weight:600;color:#555;display:block;margin-bottom:2px">
          শাখাহীন শিক্ষার্থী
        </label>
        <div id="noBranchInfo" style="font-size:.8rem;padding:5px 0;color:#4361ee;font-weight:600">
          <i class="fas fa-users me-1"></i><span id="noBranchNum">—</span> জন
        </div>
      </div>
      <div class="col-12 col-md-2">
        <button type="submit" class="btn btn-sm w-100 fw-bold"
                style="background:linear-gradient(135deg,#4361ee,#3a0ca3);color:#fff;border:none;border-radius:7px">
          <i class="fas fa-code-branch me-1"></i> শাখা নির্ধারণ করুন
        </button>
      </div>
    </div>
  </form>
</div>
<?php endif; ?>

<!-- Quick Search -->
<div class="row g-2 mb-2 align-items-center">
<div class="col-md-5">
<form method="GET" class="qs">
<?php foreach ($_GET as $k=>$v): if ($k==='search'||$k==='page') continue; ?><input type="hidden" name="<?=htmlspecialchars($k)?>" value="<?=htmlspecialchars($v)?>"><?php endforeach;?>
<i class="fas fa-search text-muted"></i>
<input type="text" name="search" placeholder="নাম, আইডি, ফোন দিয়ে খুঁজুন..." value="<?=htmlspecialchars($search)?>">
<button type="submit" class="btn-s"><i class="fas fa-search me-1"></i>খুঁজুন</button>
</form>
</div>
<div class="col-md-7 d-flex gap-1 justify-content-md-end flex-wrap align-items-center">
<select class="form-select form-select-sm fs" style="width:auto;border-radius:8px" onchange="location='?'+this.value">
<?php foreach([10,25,50,100] as$l):?>
<option value="<?=http_build_query(array_merge($_GET,['limit'=>$l,'page'=>1]))?>" <?=$limit==$l?'selected':''?>><?=$l?> টি/পাতা</option>
<?php endforeach;?>
</select>
<button type="button" class="btn btn-sm btn-outline-primary fs" style="border-radius:8px" data-bs-toggle="modal" data-bs-target="#filterModal"><i class="fas fa-sliders-h me-1"></i> ফিল্টার</button>
<a href="list.php" class="btn btn-sm btn-outline-secondary fs" style="border-radius:8px"><i class="fas fa-redo me-1"></i>রিসেট</a>
<a href="add.php" class="btn btn-sm fw-bold fs" style="border-radius:8px;background:linear-gradient(135deg,var(--g),#004d35);color:#fff"><i class="fas fa-plus me-1"></i>নতুন</a>
</div>
</div>

<!-- Filter Modal -->
<div class="modal fade" id="filterModal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-scrollable">
<div class="modal-content" style="border-radius:12px;overflow:hidden">
<div class="modal-header py-2" style="background:linear-gradient(135deg,var(--b),var(--p));color:#fff">
<h6 class="modal-title fw-bold"><i class="fas fa-sliders-h me-1"></i>অ্যাডভান্সড ফিল্টার</h6>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<form method="GET" id="filterForm">
<?php if(!empty($search)):?><input type="hidden" name="search" value="<?=htmlspecialchars($search)?>"><?php endif;?>
<div class="row g-2">
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">প্রথম নাম</label><input type="text" class="form-control form-control-sm" name="first_name" value="<?=htmlspecialchars($first_name)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">শেষ নাম</label><input type="text" class="form-control form-control-sm" name="last_name" value="<?=htmlspecialchars($last_name)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">ছাত্র আইডি</label><input type="text" class="form-control form-control-sm" name="student_id" value="<?=htmlspecialchars($student_id_search)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">রোল</label><input type="text" class="form-control form-control-sm" name="roll_number" value="<?=htmlspecialchars($roll_number_search)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">ফোন</label><input type="text" class="form-control form-control-sm" name="phone" value="<?=htmlspecialchars($phone_search)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">ইমেইল</label><input type="text" class="form-control form-control-sm" name="email" value="<?=htmlspecialchars($email_search)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">সেশন</label><input type="text" class="form-control form-control-sm" name="session" value="<?=htmlspecialchars($session_search)?>"></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">গ্রুপ</label><select class="form-select form-select-sm" name="group_name"><option value="">সব</option><?php foreach($groups as$g):?><option value="<?=htmlspecialchars($g['group_name'])?>" <?=$group_name_search===$g['group_name']?'selected':''?>><?=htmlspecialchars($g['group_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">ক্লাস</label><select class="form-select form-select-sm" name="class_id"><option value="0">সব</option><?php foreach($classes as$c):?><option value="<?=$c['id']?>" <?=$class_filter==$c['id']?'selected':''?>><?=htmlspecialchars($c['name'].'-'.$c['section'])?></option><?php endforeach;?></select></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">শাখা</label><select class="form-select form-select-sm" name="branch_id"><option value="0">সব</option><?php foreach($branches as$br):?><option value="<?=$br['id']?>" <?=$branch_filter==$br['id']?'selected':''?>><?=htmlspecialchars($br['branch_name'])?></option><?php endforeach;?></select></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">লিঙ্গ</label><select class="form-select form-select-sm" name="gender"><option value="">সব</option><option value="male" <?=$gender_filter=='male'?'selected':''?>>পুরুষ</option><option value="female" <?=$gender_filter=='female'?'selected':''?>>মহিলা</option></select></div>
<div class="col-md-3 col-6"><label class="form-label fw-bold" style="font-size:.78rem">অবস্থা</label><select class="form-select form-select-sm" name="status"><option value="active" <?=$status_filter=='active'?'selected':''?>>সক্রিয়</option><option value="inactive" <?=$status_filter=='inactive'?'selected':''?>>নিষ্ক্রিয়</option></select></div>
</div>
</form>
</div>
<div class="modal-footer py-2">
<a href="list.php" class="btn btn-sm btn-outline-secondary" style="border-radius:8px"><i class="fas fa-times me-1"></i>মুছুন</a>
<button type="submit" class="btn btn-sm fw-bold px-4" style="background:linear-gradient(135deg,var(--g),#004d35);color:#fff;border-radius:8px" onclick="document.getElementById('filterForm').submit()"><i class="fas fa-search me-1"></i>ফিল্টার করুন</button>
</div>
</div>
</div>
</div>

<!-- Table -->
<div class="tc">
<div class="ch">
<span><i class="fas fa-list me-1"></i>ছাত্র-ছাত্রী তালিকা <span class="badge bg-light text-dark ms-1"><?=$total_records?> জন</span></span>
<span style="font-size:.72rem;opacity:.8"><?=min($offset+1,$total_records)?>–<?=min($offset+$limit,$total_records)?> / <?=$total_records?></span>
</div>
<div class="cb p-0">
<?php if(empty($students)):?>
<div class="text-center py-5"><i class="fas fa-user-slash fa-3x mb-2" style="color:#ccc"></i><p class="text-muted small">কোনো ছাত্র-ছাত্রী পাওয়া যায়নি</p></div>
<?php else:?>
<div class="table-responsive">
<table class="sl-tbl">
<thead><tr>
<th>#</th>
<th><a href="?<?=http_build_query(array_merge($_GET,['sort_by'=>'first_name','sort_order'=>($sort_by=='first_name'&&$sort_order=='ASC')?'DESC':'ASC']))?>">ছাত্র <?=$sort_by=='first_name'?($sort_order=='ASC'?'▲':'▼'):''?></a></th>
<th><a href="?<?=http_build_query(array_merge($_GET,['sort_by'=>'roll_number','sort_order'=>($sort_by=='roll_number'&&$sort_order=='ASC')?'DESC':'ASC']))?>">রোল <?=$sort_by=='roll_number'?($sort_order=='ASC'?'▲':'▼'):''?></a></th>
<th><a href="?<?=http_build_query(array_merge($_GET,['sort_by'=>'class_name','sort_order'=>($sort_by=='class_name'&&$sort_order=='ASC')?'DESC':'ASC']))?>">ক্লাস <?=$sort_by=='class_name'?($sort_order=='ASC'?'▲':'▼'):''?></a></th>
<th>শাখা</th>
<th>সেশন</th>
<th>গ্রুপ</th>
<th>ফোন</th>
<th>লিঙ্গ</th>
<th>অবস্থা</th>
<th style="text-align:center">কার্যক্রম</th>
</tr></thead>
<tbody>
<?php
$ac=['#4361ee','#06d6a0','#fb8500','#e63946','#7209b7','#0077b6','#f72585','#028a5b'];
foreach($students as $i=>$s):
$ini=strtoupper(substr($s['first_name'],0,1).substr($s['last_name'],0,1));
$cl=$ac[($offset+$i)%count($ac)];
$pk=!empty($s['photo'])&&file_exists(__DIR__.'/../'.ltrim($s['photo'],'/'));
?>
<tr>
<td style="color:#aaa;font-size:.72rem"><?=$offset+$i+1?></td>
<td>
<div class="d-flex align-items-center gap-1">
<?php if($pk):?><img src="../<?=htmlspecialchars($s['photo'])?>" class="av"><?php else:?><div class="avp" style="background:<?=$cl?>"><?=$ini?></div><?php endif;?>
<div><div style="font-weight:700;font-size:.82rem;color:#1a1a2e"><?=htmlspecialchars($s['first_name'].' '.$s['last_name'])?></div><div style="font-size:.68rem;color:#888"><?=htmlspecialchars($s['student_id'])?></div></div>
</div>
</td>
<td><span class="rn"><?=htmlspecialchars($s['roll_number'])?></span></td>
<td><span class="cb"><?=htmlspecialchars($s['class_name'])?></span></td>
<td><span class="cb"><?=htmlspecialchars($s['branch_name']??'—')?></span></td>
<td><span class="sb"><?=htmlspecialchars($s['session']??'—')?></span></td>
<td><?php if(!empty($s['group_name'])):?><span class="gb"><?=htmlspecialchars($s['group_name'])?></span><?php else:?><span style="color:#ccc">—</span><?php endif;?></td>
<td style="font-size:.78rem"><?=htmlspecialchars($s['phone']??'—')?></td>
<td><?php if($s['gender']=='male'):?><i class="fas fa-mars" style="color:#0077b6"></i><?php elseif($s['gender']=='female'):?><i class="fas fa-venus" style="color:#f72585"></i><?php else:?><span style="color:#ccc">—</span><?php endif;?></td>
<td><?php if($s['status']=='active'):?><span class="sa">সক্রিয়</span><?php else:?><span class="si-in">নিষ্ক্রিয়</span><?php endif;?></td>
<td style="text-align:center">
<div class="d-flex gap-1 justify-content-center">
<a href="view.php?id=<?=$s['id']?>" class="ab ab-v" title="দেখুন"><i class="fas fa-eye"></i></a>
<a href="edit.php?id=<?=$s['id']?>" class="ab ab-e" title="সম্পাদনা"><i class="fas fa-edit"></i></a>
<?php if($user_role=='admin'):?><a href="delete.php?id=<?=$s['id']?>" class="ab ab-d" title="মুছুন" onclick="return confirm('মুছে ফেলবেন?')"><i class="fas fa-trash"></i></a><?php endif;?>
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</div>

<!-- Pagination -->
<?php if($total_pages>1):?>
<div class="d-flex justify-content-between align-items-center px-3 py-2" style="border-top:1px solid #f0f0f0;font-size:.78rem">
<div>পাতা <strong><?=$page?></strong> / <strong><?=$total_pages?></strong></div>
<div class="d-flex gap-1">
<?php
$mk=function($p){return '?'.http_build_query(array_merge($_GET,['page'=>$p]));};
?>
<a href="<?=$mk(max(1,$page-1))?>" class="pg <?=$page<=1?'dis':''?>"><i class="fas fa-angle-left"></i></a>
<?php
$sp=max(1,$page-2);$ep=min($total_pages,$page+2);
if($sp>1){echo '<a href="'.$mk(1).'" class="pg">1</a>';if($sp>2)echo '<span class="pg dis">…</span>';}
for($pi=$sp;$pi<=$ep;$pi++)echo '<a href="'.$mk($pi).'" class="pg '.($pi==$page?'act':'').'">'.$pi.'</a>';
if($ep<$total_pages){if($ep<$total_pages-1)echo '<span class="pg dis">…</span>';echo '<a href="'.$mk($total_pages).'" class="pg">'.$total_pages.'</a>';}
?>
<a href="<?=$mk(min($total_pages,$page+1))?>" class="pg <?=$page>=$total_pages?'dis':''?>"><i class="fas fa-angle-right"></i></a>
</div>
</div>
<?php endif;?>
<?php endif;?>
</div></div>

</div></div>
</div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Confirm before bulk assign
function confirmBulk(form) {
    var cls  = form.querySelector('[name="bulk_class_id"] option:checked').text;
    var br   = form.querySelector('[name="bulk_branch_id"] option:checked').text;
    var num  = document.getElementById('noBranchNum').textContent;
    if (!form.querySelector('[name="bulk_class_id"]').value ||
        !form.querySelector('[name="bulk_branch_id"]').value) return true;
    return confirm('ক্লাস: ' + cls + '\nশাখা: ' + br + '\n' + num + ' জন শিক্ষার্থীর শাখা নির্ধারণ করবেন?\n(যাদের শাখা নেই শুধু তারাই আপডেট হবে)');
}

// Show count of students without branch for selected class
function loadNoBranchCount(classId) {
    var span = document.getElementById('noBranchNum');
    if (!classId) { span.textContent = '—'; return; }
    var ses = document.querySelector('[name="bulk_session"]') ? document.querySelector('[name="bulk_session"]').value : '';
    fetch('ajax_no_branch_count.php?class_id=' + encodeURIComponent(classId) + '&session=' + encodeURIComponent(ses))
        .then(function(r){ return r.json(); })
        .then(function(d){ span.textContent = d.count ?? '—'; })
        .catch(function(){ span.textContent = '?'; });
}
</script>
</html>