<?php
// Filename: admin_students.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'principal', 'assistant', 'assistant_hem', 'timetable_coord'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

$msg = ''; $msg_type = '';

// --- FETCH DATA FOR DROPDOWNS ---
// Ordered by Form Level -> Class Name
$classes = $pdo->query("SELECT * FROM classes ORDER BY form_level ASC, class_name ASC")->fetchAll();

// Group Classes by Form for Dropdown
$grouped_classes = [];
foreach ($classes as $c) {
    $form = $c['form_level'] ?: 'Other';
    $grouped_classes[$form][] = $c;
}

// Fetch Elective Subjects
$electives = $pdo->query("SELECT * FROM subjects WHERE type = 'elective' ORDER BY subject_name ASC")->fetchAll();

// --- ACTIONS ---

// 1. HANDLE ADD SINGLE STUDENT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_single') {
    $name = trim($_POST['name']);
    $ic = trim($_POST['ic']);
    $class_id = $_POST['class_id'];
    $parent = trim($_POST['parent_phone']);
    $sex = $_POST['sex'];
    $religion = $_POST['religion'];

    if (empty($name) || empty($ic) || empty($class_id)) {
        $msg = "Name, IC Number, and Class are required.";
        $msg_type = "danger";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO students (full_name, ic_number, class_id, parent_phone, sex, religion) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $ic, $class_id, $parent, $sex, $religion]);
            $msg = "Student <strong>".htmlspecialchars($name)."</strong> added successfully.";
            $msg_type = "success";
        } catch (PDOException $e) {
            $msg = "Error: IC Number likely already exists.";
            $msg_type = "danger";
        }
    }
}

// 2. HANDLE BULK UPLOAD (CSV / EXCEL / GOOGLE SHEETS)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_upload') {
    $handle = null;
    $import_source = "";

    // A. GOOGLE SHEETS
    if (!empty($_POST['google_link'])) {
        $url = $_POST['google_link'];
        if (preg_match('/\/d\/([a-zA-Z0-9-_]+)/', $url, $matches)) {
            $sheetId = $matches[1];
            $csvUrl = "https://docs.google.com/spreadsheets/d/$sheetId/export?format=csv";
            $sheetData = @file_get_contents($csvUrl);
            
            if ($sheetData === FALSE) {
                $msg = "Error: Could not read Google Sheet. Check permissions (Must be 'Anyone with link')."; $msg_type = "danger";
            } else {
                $handle = fopen('php://memory', 'r+');
                fwrite($handle, $sheetData);
                rewind($handle);
                $import_source = "Google Sheet";
            }
        } else {
            $msg = "Error: Invalid Google Sheet Link."; $msg_type = "danger";
        }
    }
    // B. EXCEL/ODS (Converted via JS)
    elseif (!empty($_POST['converted_csv_data'])) {
        $handle = fopen('php://memory', 'r+');
        fwrite($handle, $_POST['converted_csv_data']);
        rewind($handle);
        $import_source = "Excel/ODS";
    }
    // C. STANDARD CSV
    elseif (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == 0) {
        $filename = $_FILES['csv_file']['name'];
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if($ext === 'csv') {
            $handle = fopen($_FILES['csv_file']['tmp_name'], 'r');
            $import_source = "CSV";
        }
    }

    // PROCESS DATA
    if ($handle) {
        fgetcsv($handle); // Skip header
        
        $count = 0; $errors = 0;
        $pdo->beginTransaction();
        try {
            $class_map = [];
            foreach($classes as $c) $class_map[strtoupper($c['class_name'])] = $c['id'];

            $stmt_insert = $pdo->prepare("INSERT INTO students (full_name, ic_number, class_id, sex, religion) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE class_id = VALUES(class_id), full_name = VALUES(full_name), sex = VALUES(sex), religion = VALUES(religion)");

            while (($row = fgetcsv($handle)) !== FALSE) {
                if (count($row) >= 3) {
                    $name = trim($row[0] ?? '');
                    $ic = trim($row[1] ?? '');
                    $className = strtoupper(trim($row[2] ?? ''));
                    $sex = isset($row[3]) ? ucfirst(strtolower(trim($row[3]))) : null;
                    $religion = trim($row[4] ?? '');
                    
                    if(empty($name) || empty($ic)) continue; 

                    if($sex !== 'Male' && $sex !== 'Female') $sex = null;

                    if (isset($class_map[$className])) {
                        $stmt_insert->execute([$name, $ic, $class_map[$className], $sex, $religion]);
                        $count++;
                    } else { $errors++; }
                }
            }
            $pdo->commit();
            $msg = "Import ($import_source): $count students added/updated. ($errors skipped due to invalid class)"; $msg_type = ($count > 0) ? "success" : "warning";
        } catch (Exception $e) { $pdo->rollBack(); $msg = "Import Error: " . $e->getMessage(); $msg_type = "danger"; }
        fclose($handle);
    } elseif(empty($msg)) {
        $msg = "Please provide a valid file or link."; $msg_type = "danger";
    }
}

// 3. HANDLE EDIT STUDENT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_student') {
    try {
        $pdo->prepare("UPDATE students SET full_name=?, ic_number=?, class_id=?, parent_phone=?, sex=?, religion=? WHERE id=?")
            ->execute([$_POST['name'], $_POST['ic'], $_POST['class_id'], $_POST['parent_phone'], $_POST['sex'], $_POST['religion'], $_POST['student_id']]);
        $msg = "Student details updated."; $msg_type="success";
    } catch (Exception $e) { $msg="Error updating."; $msg_type="danger"; }
}

// 4. HANDLE DELETE (Single)
if (isset($_GET['delete_id'])) {
    $pdo->prepare("DELETE FROM students WHERE id = ?")->execute([$_GET['delete_id']]);
    $msg = "Student record deleted."; $msg_type = "warning";
}

// 5. HANDLE BULK MOVE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_move') {
    $target_class = $_POST['target_class_id'] ?? '';
    $ids = $_POST['student_ids'] ?? [];

    if (!empty($ids) && !empty($target_class)) {
        $placeholders = implode(',', array_fill(0, count($ids), '?'));
        $sql = "UPDATE students SET class_id = ? WHERE id IN ($placeholders)";
        $params = array_merge([$target_class], $ids);
        $pdo->prepare($sql)->execute($params);
        $msg = count($ids) . " students moved to new class."; $msg_type = "success";
    }
}

// 6. HANDLE BULK DELETE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bulk_delete') {
    $ids = $_POST['student_ids'] ?? [];
    $count = count($ids);

    if (!empty($ids)) {
        try {
            $placeholders = implode(',', array_fill(0, $count, '?'));
            $sql = "DELETE FROM students WHERE id IN ($placeholders)";
            $pdo->prepare($sql)->execute($ids);
            $msg = "$count students successfully deleted."; $msg_type = "warning";
        } catch (Exception $e) { 
            $msg = "Error deleting students."; $msg_type = "danger"; 
        }
    }
}

// 7. HANDLE ELECTIVE ENROLLMENT (New)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_electives') {
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id_elective'];
    $enrolled_ids = $_POST['enrolled_students'] ?? [];

    try {
        $pdo->beginTransaction();
        
        // 1. Get all students in this class
        $class_students = $pdo->prepare("SELECT id FROM students WHERE class_id = ?");
        $class_students->execute([$class_id]);
        $all_ids = $class_students->fetchAll(PDO::FETCH_COLUMN);

        // 2. Clear existing enrollments for this subject for ALL students in this class
        // (This ensures unchecking a box removes them)
        if (!empty($all_ids)) {
            $placeholders = implode(',', array_fill(0, count($all_ids), '?'));
            $sql = "DELETE FROM student_electives WHERE subject_id = ? AND student_id IN ($placeholders)";
            $params = array_merge([$subject_id], $all_ids);
            $pdo->prepare($sql)->execute($params);
        }

        // 3. Insert checked students
        if (!empty($enrolled_ids)) {
            $ins = $pdo->prepare("INSERT IGNORE INTO student_electives (student_id, subject_id) VALUES (?, ?)");
            foreach ($enrolled_ids as $sid) {
                $ins->execute([$sid, $subject_id]);
            }
        }
        
        $pdo->commit();
        $msg = "Elective enrollment updated."; $msg_type = "success";
    } catch (Exception $e) {
        $pdo->rollBack();
        $msg = "Error saving electives: " . $e->getMessage(); $msg_type = "danger";
    }
}

// --- FETCH STUDENT DATA ---
$search = $_GET['search'] ?? '';
$filter_class = $_GET['class_id'] ?? '';

$sql = "SELECT s.*, c.class_name, c.form_level FROM students s JOIN classes c ON s.class_id = c.id WHERE 1=1";
$params = [];

if ($filter_class) { $sql .= " AND s.class_id = ?"; $params[] = $filter_class; }
if ($search) { $sql .= " AND (s.full_name LIKE ? OR s.ic_number LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }

$sql .= " ORDER BY c.form_level ASC, c.class_name ASC, s.full_name ASC LIMIT 500"; 
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$students = $stmt->fetchAll();

// Class Summary Logic
$class_summary_name = "All Students";
$class_summary_count = count($students);
if ($filter_class) {
    foreach($classes as $c) { if($c['id'] == $filter_class) { $class_summary_name = $c['class_name']; break; } }
}

$total_students = $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Students</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>

    <style>
        /* --- FIXED CSS VARIABLES HERE --- */
        :root {
            /* The gradient from your settings */
            --primary-grad: <?= getHeaderTheme() ?>;
            
            /* SOLID COLORS needed for text and buttons */
            --primary-color: #8B5CF6; 
            --bg-color: #f8f9fd;
            --text-dark: #1e293b;
            --text-gray: #64748b;
        }

        /* Uses standard body padding; clearance is added to the last student item */
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        /* HEADER (Full width, gradient, large text) */
        .app-header { 
            background: var(--primary-grad); 
            padding: 30px 20px 80px 20px; 
            border-radius: 0 0 35px 35px; 
            color: white; 
            text-align: center; 
        }
        .app-header h2 { margin-top: 5px; }

        /* FLOATING CARD (Curved corners, lifted up) */
        .floating-card { 
            background: white; 
            margin: -60px 20px 20px 20px; 
            border-radius: 24px; 
            padding: 20px; 
            box-shadow: 0 15px 35px rgba(0,0,0,0.1); 
            position: relative; 
            z-index: 10; 
        }

        /* TABS (Pills forced into one line) */
        .nav-pills { 
            margin-bottom: 20px !important; 
            flex-wrap: nowrap; 
            overflow-x: auto; 
        }
        .nav-pills .nav-item {
            flex-shrink: 0; 
        }
        .nav-pills .nav-link { 
            border-radius: 50px; color: #64748b; font-weight: 700; padding: 8px 18px; 
            background: #f1f5f9; margin-right: 0 !important; 
            margin-left: 5px; 
            font-size: 0.85rem;
        }
        .nav-pills .nav-link:first-child {
             margin-left: 0;
        }
        .nav-pills .nav-link.active { 
            background: var(--primary-color); 
            color: white; 
            box-shadow: 0 4px 10px rgba(139, 92, 246, 0.3); 
        }

        /* SEARCH/FILTER BAR */
        .filter-bar {
            position: relative;
            display: flex;
            gap: 5px;
            margin-bottom: 20px;
        }
        .filter-bar .form-control {
            border-radius: 50px;
            padding: 10px 15px 10px 40px; 
            background-color: #f1f5f9;
            border: none;
            font-size: 0.9rem;
        }
        .filter-bar .bi-search {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            z-index: 5;
        }
        .filter-bar .form-select {
            max-width: 150px;
            padding-left: 15px;
            padding-right: 30px;
            border-radius: 50px;
            background-color: #f1f5f9;
            border: none;
            font-size: 0.9rem;
        }

        /* STUDENT LIST ITEM STYLES */
        .list-header { 
            font-size: 0.8rem; 
            font-weight: 700; 
            color: var(--text-dark);
            margin-top: 15px; 
            padding-bottom: 5px;
        }
        .student-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .student-item:last-child {
            border-bottom: none;
        }
        
        /* Margin added to push last item above menu (Guaranteed Fix) */
        .student-list-container .student-item:last-child {
            margin-bottom: 85px; /* Increased margin for absolute clearance above the 80-90px menu height */
        }
        
        /* Style for truncated name/IC on mobile */
        .student-details {
            flex-grow: 1;
            padding-left: 10px;
            max-width: 45%; 
            min-width: 100px;
        }
        .student-details .fw-bold, .student-details .small {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: block; 
        }
        .student-details .fw-bold {
            font-size: 0.9rem;
            line-height: 1.2;
            color: var(--text-dark);
        }
        .student-details .small {
            font-size: 0.75rem;
            color: var(--text-gray);
        }
        .student-gender-rel {
            min-width: 130px;
            text-align: right;
            font-size: 0.75rem;
            color: #64748b;
            line-height: 1.2;
        }
        .student-gender-rel i {
            font-size: 1.1rem;
        }
        .student-actions {
            flex-shrink: 0;
            width: 30px;
            text-align: right;
        }

        /* BULK ACTION BAR */
        .bulk-bar {
            background: #f1f5f9; 
            padding: 10px 15px;
            border-radius: 12px;
            margin-bottom: 15px; 
            display: none; 
            align-items: center; 
            justify-content: space-between; 
        }
        .bulk-bar.show { display: flex; }
        .bulk-bar .badge { 
            font-size: 0.8rem; 
            padding: 5px 10px; 
            background-color: var(--primary-color) !important;
        }
        .bulk-bar .btn-sm {
            padding: 5px 15px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.8rem;
        }

        /* Checkbox styling */
        .form-check-input {
            width: 20px;
            height: 20px;
            border-radius: 6px;
            margin-right: 15px;
            flex-shrink: 0;
        }

        /* ELECTIVE ROW */
        .elective-row {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #f0f0f0;
            background: white;
            transition: 0.1s;
        }
        .elective-row:active { background: #f8fafc; }
        .elective-row input:checked + div { color: var(--primary-color); font-weight: bold; }

        /* BOTTOM NAV */
        .bottom-nav { 
            position: fixed; bottom: 0; left: 0; right: 0; background: white; 
            padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; 
            border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); 
            z-index: 9990;
        }
        .nav-btn { 
            display: flex; flex-direction: column; align-items: center; color: #94a3b8; 
            text-decoration: none; font-size: 0.7rem; font-weight: 600; 
        }
        .nav-btn.active { color: var(--primary-color); }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; }
    </style>
</head>
<body class="p-0">

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="#" onclick="window.history.back();" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Student Management</div>
            <div style="width: 24px;"></div>
        </div>
        <h2 class="mb-0 fw-bold"><?= $total_students ?></h2>
        <div class="opacity-75 small">Total Registered Students</div>
    </div>

    <div class="container-fluid">
        <div class="floating-card">
            <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>
            
            <ul class="nav nav-pills mb-3 justify-content-center" id="actionTabs">
                <li class="nav-item"><button class="nav-link active" data-bs-toggle="pill" data-bs-target="#list-view">Student List</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#single-add">Add New</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#electives">Electives</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="pill" data-bs-target="#bulk-upload">Import</button></li>
            </ul>
            
            <div class="tab-content">
                
                <div class="tab-pane fade show active" id="list-view">
                    
                    <form method="GET" class="filter-bar">
                        <div class="position-relative flex-grow-1">
                            <i class="bi bi-search"></i>
                            <input type="text" name="search" class="form-control" placeholder="Search by name or IC..." value="<?=htmlspecialchars($search)?>">
                        </div>
                        <select name="class_id" class="form-select" onchange="this.form.submit()">
                            <option value="">Filter Class</option>
                            <?php foreach($grouped_classes as $form => $cls_list): ?>
                                <optgroup label="Form <?= $form ?>">
                                    <?php foreach($cls_list as $c): ?>
                                        <option value="<?=$c['id']?>" <?=($filter_class==$c['id'])?'selected':''?>><?=htmlspecialchars($c['class_name'])?></option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </form>

                    <div class="d-flex align-items-center list-header">
                        <span>
                             <?= htmlspecialchars($class_summary_name) ?> 
                        </span>
                        <span class="ms-1 text-muted fw-normal" style="font-size: 0.75rem;">(<?= $class_summary_count ?> Students Found)</span>
                    </div>

                    <form method="POST" id="bulkForm">
                        <input type="hidden" name="action" value="bulk_move" id="bulk_action_type">
                        
                        <div class="bulk-bar" id="bulkBar">
                            <div class="d-flex align-items-center">
                                <span class="badge rounded-pill me-2" id="countBadge">0</span>
                                <span class="fw-bold small">Students Selected</span>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#bulkMoveModal">Move</button>

                                <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete all selected students? This action is irreversible.') ? setBulkAction('bulk_delete') : false;">Delete</button>
                            </div>
                        </div>

                        <div class="student-list-container">
                            <?php if(empty($students)): ?>
                                <div class="text-center py-4 text-muted">No students found.</div>
                            <?php endif; ?>
                            
                            <?php foreach($students as $s): ?>
                            <div class="student-item">
                                <input type="checkbox" name="student_ids[]" value="<?=$s['id']?>" class="form-check-input student-check">
                                
                                <div class="student-details">
                                    <div class="fw-bold text-truncate"><?=htmlspecialchars($s['full_name'])?></div>
                                    <div class="small font-monospace text-truncate"><?=htmlspecialchars($s['ic_number'])?></div>
                                </div>
                                
                                <div class="d-flex align-items-center justify-content-end student-gender-rel">
                                    <span class="small me-2 text-dark"><?= htmlspecialchars($s['class_name']) ?></span> 
                                    <?php if(!empty($s['religion'])): ?>
                                        <span class="small me-2">&bull; <?= htmlspecialchars($s['religion']) ?></span>
                                    <?php endif; ?>
                                    <?php if($s['sex']=='Male'): ?><i class="bi bi-gender-male text-primary"></i><?php else: ?><i class="bi bi-gender-female text-danger"></i><?php endif; ?>
                                </div>
                                
                                <div class="student-actions">
                                    <button type="button" class="btn btn-sm btn-light border rounded-circle p-1" style="width: 30px; height: 30px;" onclick="openEditModal(<?=$s['id']?>, '<?=addslashes($s['full_name'])?>', '<?=$s['ic_number']?>', '<?=$s['parent_phone']?>', <?=$s['class_id']?>, '<?=$s['sex']?>', '<?=$s['religion']?>')"><i class="bi bi-pencil" style="font-size: 0.8rem;"></i></button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </form>
                </div>

                <div class="tab-pane fade" id="electives">
                    <div class="alert alert-info border-0 shadow-sm small mb-3">
                        <i class="bi bi-info-circle-fill me-1"></i> Use this tab to enroll students into <strong>elective subjects</strong> (e.g., Biology, Physics, Accounting) for split classes.
                    </div>

                    <form id="electiveFetchForm">
                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <label class="form-label small">Class</label>
                                <select id="el_class_select" class="form-select bg-light" onchange="fetchElectiveStudents()">
                                    <option value="">Select...</option>
                                    <?php foreach($grouped_classes as $form => $cls_list): ?>
                                        <optgroup label="Form <?= $form ?>">
                                            <?php foreach($cls_list as $c): ?>
                                                <option value="<?=$c['id']?>"><?=$c['class_name']?></option>
                                            <?php endforeach; ?>
                                        </optgroup>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="form-label small">Subject</label>
                                <select id="el_subject_select" class="form-select bg-light" onchange="fetchElectiveStudents()">
                                    <option value="">Select...</option>
                                    <?php foreach($electives as $e): ?>
                                        <option value="<?=$e['id']?>"><?=$e['subject_name']?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </form>

                    <form method="POST" id="enrollForm" style="display:none;">
                        <input type="hidden" name="action" value="save_electives">
                        <input type="hidden" name="class_id_elective" id="hid_class_id">
                        <input type="hidden" name="subject_id" id="hid_subject_id">

                        <div class="d-flex justify-content-between align-items-center mb-2 px-1">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="checkAllElective" onchange="toggleElectiveChecks(this)">
                                <label class="form-check-label small fw-bold" for="checkAllElective">Select All</label>
                            </div>
                            <button class="btn btn-sm btn-primary rounded-pill fw-bold px-3">Save Changes</button>
                        </div>

                        <div id="electiveStudentList" class="border rounded bg-white overflow-hidden mb-3">
                            </div>
                    </form>
                    
                    <div id="electiveLoader" class="text-center py-4 text-muted" style="display:none;">
                        <div class="spinner-border spinner-border-sm mb-2"></div><br>Loading students...
                    </div>
                     <div id="electivePlaceholder" class="text-center py-5 text-muted opacity-50">
                        <i class="bi bi-ui-checks display-1"></i>
                        <p class="mt-2 fw-bold small">Select Class & Subject to begin.</p>
                    </div>

                </div>

                <div class="tab-pane fade" id="single-add">
                    <form method="POST" class="row g-3">
                        <input type="hidden" name="action" value="add_single">
                        <div class="col-12"><label class="form-label">Full Name</label><input type="text" name="name" class="form-control" required></div>
                        <div class="col-6"><label class="form-label">IC Number</label><input type="text" name="ic" class="form-control" required></div>
                        <div class="col-6"><label class="form-label">Parent Phone</label><input type="text" name="parent_phone" class="form-control"></div>
                        
                        <div class="col-12">
                            <label class="form-label">Class</label>
                            <select name="class_id" class="form-select" required>
                                <option value="">Select Class</option>
                                <?php foreach($grouped_classes as $form => $cls_list): ?>
                                    <optgroup label="Form <?= $form ?>">
                                        <?php foreach($cls_list as $c): ?>
                                            <option value="<?=$c['id']?>"><?=htmlspecialchars($c['class_name'])?></option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-6">
                            <label class="form-label">Gender</label>
                            <select name="sex" class="form-select">
                                <option value="Male">Male</option>
                                <option value="Female">Female</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Religion</label>
                            <select name="religion" class="form-select">
                                <option value="Islam">Islam</option>
                                <option value="Christianity">Christianity</option>
                                <option value="Buddhism">Buddhism</option>
                                <option value="Hinduism">Hinduism</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        
                        <div class="col-12 mt-4"><button class="btn btn-primary w-100 fw-bold rounded-pill py-2">Add Student</button></div>
                    </form>
                </div>

                <div class="tab-pane fade" id="bulk-upload">
                    <div class="text-center py-4">
                        <i class="bi bi-file-earmark-spreadsheet text-success display-1"></i>
                        <h6 class="fw-bold mt-3">Bulk Import Students</h6>
                        
                        <form method="POST" enctype="multipart/form-data" class="text-start bg-light p-3 rounded-4">
                            <input type="hidden" name="action" value="bulk_upload">
                            <input type="hidden" name="converted_csv_data" id="converted_csv_data">
                            
                            <div class="alert alert-info small mb-3">
                                <h6 class="fw-bold text-primary small"><i class="bi bi-info-circle-fill me-1"></i> Data Format</h6>
                                <div class="row g-1 small" style="font-size:0.75rem;">
                                    <div class="col-4"><strong>Col 1:</strong> Name</div>
                                    <div class="col-4"><strong>Col 2:</strong> IC No</div>
                                    <div class="col-4"><strong>Col 3:</strong> Class Name</div>
                                    <div class="col-6"><strong>Col 4:</strong> Male/Female</div>
                                    <div class="col-6"><strong>Col 5:</strong> Religion</div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Upload File (Excel/CSV)</label>
                                <input type="file" name="csv_file" id="fileInput" class="form-control" accept=".csv, .xlsx, .xls, .ods">
                                <div id="fileStatus" class="alert alert-info small border-0 mt-2 py-2" style="display:none;"></div>
                            </div>
                            <div class="text-center text-muted fw-bold small my-2">- OR -</div>
                            <div class="mb-3">
                                <label class="form-label">Google Sheet Link</label>
                                <input type="url" name="google_link" class="form-control" placeholder="Public Link">
                            </div>
                            <button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold">Start Import</button>
                        </form>
                    </div>
                </div>

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

    <div class="modal fade" id="bulkMoveModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content border-0 shadow"><form method="POST" id="moveModalForm" onsubmit="return setBulkAction('bulk_move')"><div class="modal-header bg-primary text-white"><h6 class="modal-title fw-bold">Bulk Move Students</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <div class="modal-body p-4">
        <input type="hidden" name="action" value="bulk_move">
        
        <div class="mb-3">
            <p class="small text-muted">Move <strong id="moveCountBadge">0</strong> selected students to:</p>
            <label class="form-label">Target Class</label>
            <select name="target_class_id" class="form-select bg-light" id="move_target_class" required>
                <option value="">Select Class</option>
                <?php foreach($grouped_classes as $form => $cls_list): ?>
                    <optgroup label="Form <?= $form ?>">
                        <?php foreach($cls_list as $c): ?>
                            <option value="<?=$c['id']?>"><?=$c['class_name']?></option>
                        <?php endforeach; ?>
                    </optgroup>
                <?php endforeach; ?>
            </select>
        </div>
        <p class="small text-danger">Note: Only currently selected students will be moved.</p>
    </div><div class="modal-footer border-0 bg-light"><button type="submit" class="btn btn-primary w-100 fw-bold rounded-pill">Confirm Move</button></div></form></div></div></div>


    <div class="modal fade" id="editModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content border-0 shadow"><form method="POST"><div class="modal-header bg-primary text-white"><h6 class="modal-title fw-bold">Edit Student</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <div class="modal-body p-4">
        <input type="hidden" name="action" value="edit_student"><input type="hidden" name="student_id" id="edit_sid">
        <div class="mb-3"><label class="small fw-bold text-muted">Name</label><input type="text" name="name" id="edit_name" class="form-control bg-light" required></div>
        <div class="mb-3"><label class="small fw-bold text-muted">IC Number</label><input type="text" name="ic" id="edit_ic" class="form-control bg-light" required></div>
        <div class="row g-2 mb-3">
            <div class="col-6"><label class="small fw-bold text-muted">Gender</label><select name="sex" id="edit_sex" class="form-select bg-light"><option value="Male">Male</option><option value="Female">Female</option></select></div>
            <div class="col-6"><label class="small fw-bold text-muted">Religion</label><select name="religion" id="edit_rel" class="form-select bg-light"><option value="Islam">Islam</option><option value="Christianity">Christianity</option><option value="Buddhism">Buddhism</option><option value="Hinduism">Hinduism</option><option value="Other">Other</option></select></div>
        </div>
        <div class="mb-3"><label class="small fw-bold text-muted">Phone</label><input type="text" name="parent_phone" id="edit_phone" class="form-control bg-light"></div>
        
        <div class="mb-0">
            <label class="small fw-bold text-muted">Class</label>
            <select name="class_id" id="edit_class" class="form-select bg-light">
                <?php foreach($grouped_classes as $form => $cls_list): ?>
                    <optgroup label="Form <?= $form ?>">
                        <?php foreach($cls_list as $c): ?>
                            <option value="<?=$c['id']?>"><?=$c['class_name']?></option>
                        <?php endforeach; ?>
                    </optgroup>
                <?php endforeach; ?>
            </select>
        </div>
    </div><div class="modal-footer border-0 bg-light"><button class="btn btn-primary w-100 fw-bold rounded-pill">Save Changes</button></div></form></div></div></div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Function to set the action type before form submission
        function setBulkAction(actionType) {
            document.getElementById('bulk_action_type').value = actionType;
            return true;
        }

        // --- EDIT STUDENT MODAL LOGIC ---
        const editModal = new bootstrap.Modal(document.getElementById('editModal'));
        function openEditModal(id, name, ic, phone, cid, sex, rel) {
            document.getElementById('edit_sid').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_ic').value = ic;
            document.getElementById('edit_phone').value = phone;
            document.getElementById('edit_class').value = cid;
            document.getElementById('edit_sex').value = sex;
            document.getElementById('edit_rel').value = rel;
            editModal.show();
        }

        // --- BULK ACTION BAR (Visibility based on selection) ---
        const bulkBar = document.getElementById('bulkBar');
        const countBadge = document.getElementById('countBadge');
        const moveCountBadge = document.getElementById('moveCountBadge');
        const checkboxes = document.querySelectorAll('.student-check');
        const bulkMoveModal = document.getElementById('bulkMoveModal');

        if (bulkMoveModal) {
            bulkMoveModal.addEventListener('show.bs.modal', function(event) {
                const checkedCount = document.querySelectorAll('.student-check:checked').length;
                moveCountBadge.textContent = checkedCount;

                if (checkedCount === 0) {
                     event.preventDefault();
                     alert("Please select students first.");
                     return;
                }

                // 1. Get the form from the modal
                const modalForm = document.getElementById('moveModalForm');
                
                // 2. Remove any old student_ids inputs generated by previous modal opens
                modalForm.querySelectorAll('input[name="student_ids[]"]').forEach(input => input.remove());

                // 3. Clone the currently checked boxes from the list view into the modal form
                document.querySelectorAll('.student-check:checked').forEach(checkedBox => {
                    const clone = checkedBox.cloneNode(true);
                    // Ensure the clone has the correct name and type for form submission
                    clone.setAttribute('name', 'student_ids[]');
                    clone.setAttribute('type', 'hidden'); 
                    clone.checked = true; // Mark as checked/selected
                    modalForm.appendChild(clone);
                });
            });
        }

        function toggleAll(source) {
            checkboxes.forEach(cb => cb.checked = source.checked);
            updateBulkBar();
        }

        checkboxes.forEach(cb => {
            cb.addEventListener('change', updateBulkBar);
        });

        function updateBulkBar() {
            const checked = document.querySelectorAll('.student-check:checked').length;
            countBadge.innerText = checked;
            if(checked > 0) bulkBar.classList.add('show');
            else bulkBar.classList.remove('show');
            
            // Default action type
            document.getElementById('bulk_action_type').value = 'bulk_move'; 
        }

        // Initialize state
        document.addEventListener('DOMContentLoaded', updateBulkBar);


        // --- FILE UPLOAD HANDLER (EXCEL/ODS to CSV) ---
        document.getElementById('fileInput').addEventListener('change', function(e) {
            const file = e.target.files[0]; 
            const statusBox = document.getElementById('fileStatus');
            const hiddenInput = document.getElementById('converted_csv_data');
            
            if(!file) { statusBox.style.display = 'none'; return; }

            // Reset
            hiddenInput.value = '';
            statusBox.style.display = 'block';
            statusBox.className = 'alert alert-info small border-0 mt-2 py-2';
            statusBox.innerHTML = '<i class="bi bi-hourglass-split me-2"></i> Reading file...';

            const name = file.name.toLowerCase();
            
            // Check if conversion needed
            if (name.endsWith('.xlsx') || name.endsWith('.xls') || name.endsWith('.ods')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        const workbook = XLSX.read(data, {type: 'array'});
                        const firstSheetName = workbook.SheetNames[0];
                        const worksheet = workbook.Sheets[firstSheetName];
                        const csvOutput = XLSX.utils.sheet_to_csv(worksheet);
                        
                        hiddenInput.value = csvOutput;
                        statusBox.className = 'alert alert-success small border-0 mt-2 py-2';
                        statusBox.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i> Ready to Import.';
                    } catch (err) {
                        statusBox.className = 'alert alert-danger small border-0 mt-2 py-2';
                        statusBox.innerHTML = 'Error parsing file.';
                        console.error(err);
                    }
                };
                reader.readAsArrayBuffer(file);
            } else {
                statusBox.className = 'alert alert-success small border-0 mt-2 py-2';
                statusBox.innerHTML = '<i class="bi bi-check-circle-fill me-1"></i> CSV Ready.';
            }
        });

        // --- ELECTIVE FETCHING AJAX ---
        function fetchElectiveStudents() {
            const cls = document.getElementById('el_class_select').value;
            const sub = document.getElementById('el_subject_select').value;
            const container = document.getElementById('electiveStudentList');
            const form = document.getElementById('enrollForm');
            const loader = document.getElementById('electiveLoader');
            const placeholder = document.getElementById('electivePlaceholder');

            if(!cls || !sub) {
                form.style.display = 'none';
                placeholder.style.display = 'block';
                return;
            }

            document.getElementById('hid_class_id').value = cls;
            document.getElementById('hid_subject_id').value = sub;
            placeholder.style.display = 'none';
            loader.style.display = 'block';
            form.style.display = 'none';
            container.innerHTML = '';

            fetch(`get_class_students.php?class_id=${cls}&subject_id=${sub}`)
                .then(r => r.json())
                .then(data => {
                    loader.style.display = 'none';
                    form.style.display = 'block';
                    
                    if(data.length === 0) {
                        container.innerHTML = '<div class="p-4 text-center text-muted">No students in this class.</div>';
                    } else {
                        let html = '';
                        data.forEach(s => {
                            const checked = s.is_enrolled ? 'checked' : '';
                            const statusColor = s.is_enrolled ? 'text-primary fw-bold' : 'text-muted';
                            
                            html += `<label class="elective-row">
                                <input class="form-check-input me-3 elective-check" type="checkbox" name="enrolled_students[]" value="${s.id}" ${checked}>
                                <div class="${statusColor}">${s.full_name}</div>
                            </label>`;
                        });
                        container.innerHTML = html;
                    }
                })
                .catch(e => {
                    loader.style.display = 'none';
                    container.innerHTML = '<div class="text-danger p-3">Error fetching students.</div>';
                });
        }

        function toggleElectiveChecks(source) {
            document.querySelectorAll('.elective-check').forEach(cb => cb.checked = source.checked);
        }
    </script>
</body>
</html>