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

$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_admin_roles = ['admin', 'principal', 'assistant'];
$is_admin_or_assistant = !empty(array_intersect($user_roles, $allowed_admin_roles));

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

// --- 1. ACCESS CHECK & CLASS FETCHING ---
// Fetch Class Info (Teacher's own class)
$stmt = $pdo->prepare("SELECT * FROM classes WHERE class_teacher_id = ?");
$stmt->execute([$uid]);
$my_class = $stmt->fetch();

// Allow Admin to view/debug if needed, but primarily for Class Teachers
if (!$is_admin_or_assistant && !$my_class) {
    die("<div class='container mt-5 text-center'><div class='alert alert-warning rounded-4 shadow-sm border-0'><strong>Access Denied</strong><br>You must be a Class Teacher to access this page.<br><a href='dashboard.php' class='btn btn-sm btn-dark mt-3 rounded-pill px-4'>Back to Dashboard</a></div></div>");
}

$class_id = $my_class['id'] ?? 0;
$class_name = $my_class['class_name'] ?? 'Unknown Class';

// --- 2. FETCH ELECTIVE SUBJECTS ---
$electives = $pdo->query("SELECT * FROM subjects WHERE type = 'elective' ORDER BY subject_name ASC")->fetchAll();

// --- 3. ACTIONS ---

// A. SAVE ELECTIVES
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_electives') {
    $subject_id = $_POST['subject_id'];
    $enrolled_ids = $_POST['enrolled_students'] ?? [];

    if ($class_id && $subject_id) {
        try {
            $pdo->beginTransaction();

            // 1. Get all students in THIS class to safely clear their old records for this subject
            $class_students = $pdo->prepare("SELECT id FROM students WHERE class_id = ?");
            $class_students->execute([$class_id]);
            $all_ids = $class_students->fetchAll(PDO::FETCH_COLUMN);

            if (!empty($all_ids)) {
                // Clear existing enrollment for this subject for students in this class
                $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);
            }

            // 2. Insert new 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 successfully."; $msg_type = "success";
        } catch (Exception $e) {
            $pdo->rollBack();
            $msg = "Error updating electives: " . $e->getMessage(); $msg_type = "danger";
        }
    }
}

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

// --- 4. FETCH STUDENTS LIST ---
$students = [];
if ($class_id) {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE class_id = ? ORDER BY full_name ASC");
    $stmt->execute([$class_id]);
    $students = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>My Class: <?= htmlspecialchars($class_name) ?></title>
    
    <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">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        
        .student-item { background: white; border-bottom: 1px solid #f1f5f9; padding: 12px 0; display: flex; align-items: center; justify-content: space-between; }
        .student-item:last-child { border-bottom: none; }
        
        /* Elective Modal Styles */
        .elective-row { display: flex; align-items: center; padding: 10px; border-bottom: 1px solid #f0f0f0; transition: 0.1s; cursor: pointer; }
        .elective-row:hover { background: #f8fafc; }
        .elective-row:last-child { border-bottom: none; }
        .elective-row input:checked + div { color: #0d6efd; font-weight: bold; }
        
        .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: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; }
        .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: 100; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">My Students</div>
            <div style="width: 24px;"></div>
        </div>
        <h2 class="mb-0 fw-bold"><?= htmlspecialchars($class_name) ?></h2>
        <div class="opacity-75 small">Total: <?= count($students) ?> Students</div>
    </div>

    <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; ?>

        <div class="d-flex gap-2">
            <button class="btn btn-outline-primary w-100 rounded-pill fw-bold btn-sm" onclick="openElectiveModal()">
                <i class="bi bi-list-check me-1"></i> Manage Electives
            </button>
            <a href="student_reports.php" class="btn btn-primary w-100 rounded-pill fw-bold btn-sm">
                <i class="bi bi-bar-chart-line me-1"></i> View Report
            </a>
        </div>
    </div>

    <div class="px-3 pb-4">
        <?php if(empty($students)): ?>
            <div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-people display-1"></i><br>No students in this class.</div>
        <?php else: ?>
            <div class="bg-white rounded-4 shadow-sm p-3 border border-light">
                <?php foreach($students as $s): ?>
                <div class="student-item" onclick='viewStudent(<?= json_encode($s) ?>)'>
                    <div class="d-flex align-items-center overflow-hidden">
                        <div class="bg-light text-primary rounded-circle d-flex align-items-center justify-content-center me-3 flex-shrink-0" style="width: 40px; height: 40px; font-weight: bold;">
                            <?= substr($s['full_name'], 0, 1) ?>
                        </div>
                        <div class="text-truncate">
                            <div class="fw-bold text-dark text-truncate"><?= htmlspecialchars($s['full_name']) ?></div>
                            <div class="small text-muted"><?= htmlspecialchars($s['ic_number']) ?></div>
                        </div>
                    </div>
                    <i class="bi bi-chevron-right text-muted small"></i>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="studentModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold">Student Details</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div id="viewMode" class="modal-body p-4 text-center">
                    <div class="bg-light rounded-circle d-inline-flex align-items-center justify-content-center mb-3 text-primary fw-bold" style="width:70px; height:70px; font-size:1.5rem;" id="v_avatar">A</div>
                    <h5 class="fw-bold mb-1" id="v_name">Student Name</h5>
                    <p class="text-muted small mb-3" id="v_ic">IC Number</p>
                    
                    <div class="row g-2 mb-4 text-start bg-light p-3 rounded-3 small">
                        <div class="col-6"><span class="text-muted d-block">Gender</span><span class="fw-bold text-dark" id="v_sex">-</span></div>
                        <div class="col-6"><span class="text-muted d-block">Religion</span><span class="fw-bold text-dark" id="v_rel">-</span></div>
                    </div>

                    <div class="d-grid gap-2">
                        <a href="#" id="v_call_btn" class="btn btn-success rounded-pill fw-bold"><i class="bi bi-telephone-fill me-2"></i> Call Parent</a>
                        <button onclick="switchToEdit()" class="btn btn-outline-primary rounded-pill fw-bold">Edit Details</button>
                    </div>
                </div>

                <form id="editMode" method="POST" style="display:none;">
                    <div class="modal-body p-4">
                        <input type="hidden" name="action" id="formAction" value="edit">
                        <input type="hidden" name="student_id" id="ed_id">
                        
                        <div class="mb-3"><label class="form-label small fw-bold">Full Name</label><input type="text" name="name" id="ed_name" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label small fw-bold">IC Number</label><input type="text" name="ic" id="ed_ic" class="form-control" required></div>
                        <div class="mb-3"><label class="form-label small fw-bold">Parent Phone</label><input type="text" name="phone" id="ed_phone" class="form-control"></div>
                        <div class="row g-2 mb-3">
                            <div class="col-6"><label class="form-label small fw-bold">Gender</label><select name="sex" id="ed_sex" class="form-select"><option value="Male">Male</option><option value="Female">Female</option></select></div>
                            <div class="col-6"><label class="form-label small fw-bold">Religion</label><select name="religion" id="ed_rel" 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>
                    </div>
                    <div class="modal-footer border-0 bg-light">
                        <button type="button" class="btn btn-light text-muted fw-bold rounded-pill" onclick="switchToView()">Cancel</button>
                        <button type="submit" class="btn btn-primary fw-bold rounded-pill px-4">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="electiveModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold">Manage Electives</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="p-3 bg-light border-bottom">
                        <label class="small fw-bold text-muted mb-1 text-uppercase">Select Subject</label>
                        <select id="el_subject_select" class="form-select fw-bold border-0 shadow-sm" onchange="fetchElectiveData()">
                            <option value="">Choose Elective...</option>
                            <?php foreach($electives as $e): ?>
                                <option value="<?=$e['id']?>"><?=$e['subject_name']?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div id="el_loader" class="text-center py-5" style="display:none;">
                        <div class="spinner-border text-primary mb-2" role="status"></div>
                        <div class="small text-muted">Loading class list...</div>
                    </div>

                    <div id="el_placeholder" class="text-center py-5 text-muted opacity-50">
                        <i class="bi bi-journal-check display-1"></i>
                        <p class="mt-2 fw-bold small">Select a subject to assign students.</p>
                    </div>

                    <form method="POST" id="el_form" style="display:none;">
                        <input type="hidden" name="action" value="save_electives">
                        <input type="hidden" name="subject_id" id="hid_subject_id">
                        
                        <div class="bg-white px-2 pt-2 border-bottom">
                            <div class="form-check ms-2 mb-2">
                                <input class="form-check-input" type="checkbox" id="checkAllEl" onchange="toggleAllEl(this)">
                                <label class="form-check-label small fw-bold text-muted" for="checkAllEl">Select All Students</label>
                            </div>
                        </div>

                        <div id="el_list_container" class="p-2" style="max-height: 50vh; overflow-y: auto;">
                            </div>

                        <div class="p-3 border-top bg-light">
                            <button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold shadow-sm">Save Enrollment</button>
                        </div>
                    </form>
                </div>
            </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>
        const studentModal = new bootstrap.Modal(document.getElementById('studentModal'));
        const electiveModal = new bootstrap.Modal(document.getElementById('electiveModal'));
        
        // --- STUDENT VIEW/EDIT LOGIC ---
        function viewStudent(s) {
            document.getElementById('viewMode').style.display = 'block';
            document.getElementById('editMode').style.display = 'none';
            
            document.getElementById('v_avatar').innerText = s.full_name.charAt(0);
            document.getElementById('v_name').innerText = s.full_name;
            document.getElementById('v_ic').innerText = s.ic_number;
            document.getElementById('v_sex').innerText = s.sex || '-';
            document.getElementById('v_rel').innerText = s.religion || '-';
            
            const btn = document.getElementById('v_call_btn');
            if (s.parent_phone) {
                btn.href = "tel:" + s.parent_phone;
                btn.classList.remove('disabled', 'btn-secondary');
                btn.classList.add('btn-success');
            } else {
                btn.href = "#";
                btn.classList.add('disabled', 'btn-secondary');
                btn.classList.remove('btn-success');
            }

            // Pre-fill Edit Form
            document.getElementById('ed_id').value = s.id;
            document.getElementById('ed_name').value = s.full_name;
            document.getElementById('ed_ic').value = s.ic_number;
            document.getElementById('ed_phone').value = s.parent_phone;
            document.getElementById('ed_sex').value = s.sex;
            document.getElementById('ed_rel').value = s.religion;

            studentModal.show();
        }

        function switchToEdit() {
            document.getElementById('viewMode').style.display = 'none';
            document.getElementById('editMode').style.display = 'block';
        }
        function switchToView() {
            document.getElementById('viewMode').style.display = 'block';
            document.getElementById('editMode').style.display = 'none';
        }

        // --- ELECTIVE MANAGER LOGIC ---
        function openElectiveModal() {
            document.getElementById('el_subject_select').value = "";
            document.getElementById('el_placeholder').style.display = 'block';
            document.getElementById('el_form').style.display = 'none';
            electiveModal.show();
        }

        function fetchElectiveData() {
            const subId = document.getElementById('el_subject_select').value;
            const classId = <?= $class_id ?>;
            const container = document.getElementById('el_list_container');
            const form = document.getElementById('el_form');
            const loader = document.getElementById('el_loader');
            const placeholder = document.getElementById('el_placeholder');

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

            placeholder.style.display = 'none';
            form.style.display = 'none';
            loader.style.display = 'block';
            document.getElementById('hid_subject_id').value = subId;

            // Reuse the existing helper API
            fetch(`get_class_students.php?class_id=${classId}&subject_id=${subId}`)
                .then(r => r.json())
                .then(data => {
                    loader.style.display = 'none';
                    form.style.display = 'block';
                    container.innerHTML = '';

                    if(data.length === 0) {
                        container.innerHTML = '<div class="text-muted text-center py-3">No students found.</div>';
                    } else {
                        let html = '';
                        data.forEach(s => {
                            const isChecked = s.is_enrolled ? 'checked' : '';
                            const textColor = s.is_enrolled ? 'text-primary fw-bold' : 'text-dark';
                            
                            html += `
                            <label class="elective-row rounded">
                                <input class="form-check-input me-3 el-check" type="checkbox" name="enrolled_students[]" value="${s.id}" ${isChecked}>
                                <div class="${textColor}">${s.full_name}</div>
                            </label>`;
                        });
                        container.innerHTML = html;
                    }
                })
                .catch(e => {
                    loader.style.display = 'none';
                    container.innerHTML = '<div class="text-danger text-center py-3">Error fetching data.</div>';
                    form.style.display = 'block';
                });
        }

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