<?php
// admin/users/students.php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

$db_path = "../../config/database.php";
if (!file_exists($db_path)) { die("Error: database.php not found at $db_path"); }
require_once $db_path;

// --- FLEXIBLE SECURITY CHECK ---
// This allows you to at least LOAD the page if you are an 'admin' or 'superadmin'
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['superadmin', 'admin'])) {
    header("Location: ../../auth/login.php");
    exit("Access Denied.");
}

// 1. DELETE LOGIC (Restricted to Superadmin for safety)
if (isset($_GET['delete_id']) && $_SESSION['role'] === 'superadmin') {
    $id = (int)$_GET['delete_id'];
    $stmt = $pdo->prepare("SELECT photo FROM students WHERE id = ?");
    $stmt->execute([$id]);
    $photo = $stmt->fetchColumn();
    if ($photo && $photo != 'default.png') { @unlink("../../uploads/students/" . $photo); }
    
    $pdo->prepare("DELETE FROM results WHERE student_id = ?")->execute([$id]);
    $pdo->prepare("DELETE FROM students WHERE id = ?")->execute([$id]);
    
    header("Location: students.php?success=1");
    exit();
}

// 2. REGISTRATION LOGIC
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_student'])) {
    try {
        $pdo->beginTransaction();
        
        $fn = trim($_POST['first_name']);
        $ln = trim($_POST['last_name']);
        $gender = $_POST['gender'];
        $dob = $_POST['dob']; 
        $parent_name = trim($_POST['parent_name']); 
        $parent_phone = trim($_POST['parent_phone']); 
        $address = trim($_POST['address']);
        $reg = trim($_POST['reg_number']);
        $pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $class_id = (int)$_POST['class_id'];
        
        $photo_name = "default.png";
        if (!empty($_FILES['photo']['name'])) {
            $target_dir = "../../uploads/students/";
            if (!is_dir($target_dir)) { mkdir($target_dir, 0777, true); }
            $clean_reg = str_replace(['/', '\\'], '_', $reg);
            $photo_name = $clean_reg . "_" . time() . "." . pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION);
            move_uploaded_file($_FILES["photo"]["tmp_name"], $target_dir . $photo_name);
        }

        // result_access defaults to 1 (Cleared)
        $sql = "INSERT INTO students (first_name, last_name, fullname, gender, dob, parent_name, parent_phone, address, reg_number, password, class_id, photo, result_access) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$fn, $ln, $fn.' '.$ln, $gender, $dob, $parent_name, $parent_phone, $address, $reg, $pass, $class_id, $photo_name]);
        
        $new_student_id = $pdo->lastInsertId();

        $stmtSubs = $pdo->prepare("SELECT id FROM subjects WHERE class_id = ?");
        $stmtSubs->execute([$class_id]);
        $subjects = $stmtSubs->fetchAll(PDO::FETCH_ASSOC);

        if (count($subjects) > 0) {
            $insResult = $pdo->prepare("INSERT INTO results (student_id, subject_id, class_id) VALUES (?, ?, ?)");
            foreach ($subjects as $sub) {
                $insResult->execute([$new_student_id, $sub['id'], $class_id]);
            }
        }

        $pdo->commit();
        $success_msg = "Student $fn registered successfully!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_msg = "Error: " . $e->getMessage();
    }
}

// 3. FETCH DATA
$classes = $pdo->query("SELECT * FROM classes ORDER BY class_name ASC")->fetchAll();
$selected_class = $_GET['filter_class'] ?? '';

if (!empty($selected_class)) {
    $stmt = $pdo->prepare("SELECT s.*, c.class_name FROM students s JOIN classes c ON s.class_id = c.id WHERE s.class_id = ? ORDER BY s.fullname ASC");
    $stmt->execute([$selected_class]);
    $students = $stmt->fetchAll();
} else {
    $students = $pdo->query("SELECT s.*, c.class_name FROM students s JOIN classes c ON s.class_id = c.id ORDER BY s.id DESC LIMIT 15")->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Students | Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #2c3e50; --accent: #3498db; --success: #27ae60; --danger: #e74c3c; }
        body { font-family: 'Inter', 'Segoe UI', sans-serif; background: #f0f2f5; padding: 10px; color: #333; margin: 0; }
        .container { display: flex; flex-wrap: wrap; gap: 20px; max-width: 1400px; margin: auto; }
        .card { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.08); box-sizing: border-box; }
        .form-side { flex: 1; min-width: 320px; max-width: 450px; }
        .list-side { flex: 2; min-width: 320px; }
        h3 { margin-top: 0; color: var(--primary); border-bottom: 2px solid var(--accent); padding-bottom: 10px; margin-bottom: 20px; font-size: 18px; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-size: 11px; font-weight: bold; color: #7f8c8d; text-transform: uppercase; }
        input, select, textarea { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; box-sizing: border-box; font-size: 14px; background: #fff; }
        .flex-group { display: flex; gap: 10px; }
        .filter-bar { background: #fff; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; flex-wrap: wrap; align-items: center; gap: 10px; border: 1px solid #ddd; }
        table { width: 100%; border-collapse: collapse; }
        th { background: var(--primary); color: white; padding: 12px; text-align: left; font-size: 12px; text-transform: uppercase; }
        td { padding: 12px; border-bottom: 1px solid #eee; font-size: 13px; }
        .student-img { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; border: 2px solid var(--accent); }
        .btn-add { background: var(--success); color: white; border: none; padding: 15px; width: 100%; border-radius: 8px; cursor: pointer; font-weight: bold; font-size: 16px; transition: 0.3s; }
        .btn-add:hover { background: #219150; }
        .btn-del { background: var(--danger); color: white; padding: 6px 10px; text-decoration: none; border-radius: 4px; font-size: 11px; }
        .btn-edit { background: var(--accent); color: white; padding: 6px 10px; text-decoration: none; border-radius: 4px; font-size: 11px; }
        
        /* Toggle Switch Styles */
        .switch { position: relative; display: inline-block; width: 34px; height: 18px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
        .slider:before { position: absolute; content: ""; height: 12px; width: 12px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .slider { background-color: var(--success); }
        input:checked + .slider:before { transform: translateX(16px); }

        @media (max-width: 992px) { .container { flex-direction: column; } .form-side { max-width: 100%; } }
    </style>
</head>
<body>

<div style="margin: 10px 0 20px 0;">
    <a href="../dashboard.php" style="text-decoration:none; color:var(--accent); font-weight:bold;">
        <i class="fa fa-arrow-left"></i> Back to Dashboard
    </a>
</div>

<div class="container">
    <div class="form-side card">
        <h3><i class="fa fa-user-plus"></i> Enroll Student</h3>
        
        <?php if(isset($success_msg)) echo "<div style='color:green; background:#d4edda; padding:10px; border-radius:5px; margin-bottom:15px; font-size:14px;'>$success_msg</div>"; ?>
        <?php if(isset($error_msg)) echo "<div style='color:red; background:#f8d7da; padding:10px; border-radius:5px; margin-bottom:15px; font-size:14px;'>$error_msg</div>"; ?>

        <form method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label>Legal Name</label>
                <div class="flex-group">
                    <input type="text" name="first_name" placeholder="First Name" required>
                    <input type="text" name="last_name" placeholder="Last Name" required>
                </div>
            </div>

            <div class="flex-group">
                <div class="form-group" style="flex:1;">
                    <label>Gender</label>
                    <select name="gender" required>
                        <option value="">Select</option>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                    </select>
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Date of Birth</label>
                    <input type="date" name="dob" required>
                </div>
            </div>

            <div class="form-group">
                <label>Academic Info</label>
                <div class="flex-group">
                    <input type="text" name="reg_number" placeholder="Reg No (e.g. 2024/001)" required>
                    <select name="class_id" required>
                        <option value="">-- Class --</option>
                        <?php foreach($classes as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= $c['class_name'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label>Parent/Guardian</label>
                <input type="text" name="parent_name" placeholder="Parent Full Name" required style="margin-bottom: 8px;">
                <input type="tel" name="parent_phone" placeholder="Parent Phone Number" required>
            </div>

            <div class="form-group">
                <label>Home Address</label>
                <textarea name="address" placeholder="Full Residential Address" required></textarea>
            </div>

            <div class="form-group">
                <label>Login Credentials & Photo</label>
                <input type="password" name="password" placeholder="Assign Password" required style="margin-bottom: 8px;">
                <input type="file" name="photo" accept="image/*">
            </div>

            <button type="submit" name="add_student" class="btn-add">Register Student</button>
        </form>
    </div>

    <div class="list-side card">
        <form method="GET" class="filter-bar">
            <strong><i class="fa fa-filter"></i> Filter:</strong>
            <select name="filter_class" style="width: auto; flex: 1;">
                <option value="">Recent Admissions</option>
                <?php foreach($classes as $c): ?>
                    <option value="<?= $c['id'] ?>" <?= $selected_class == $c['id'] ? 'selected' : '' ?>><?= $c['class_name'] ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" style="padding: 10px 20px; background: var(--accent); color: white; border: none; border-radius: 8px; cursor: pointer; font-weight:bold;">Filter</button>
        </form>

        <table>
            <thead>
                <tr>
                    <th>Photo</th>
                    <th>Full Name</th>
                    <th>Reg No.</th>
                    <th>Access Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($students as $s): ?>
                <tr>
                    <td><img src="../../uploads/students/<?= $s['photo'] ?>" class="student-img" onerror="this.src='../../uploads/students/default.png'"></td>
                    <td>
                        <strong><?= htmlspecialchars($s['fullname']) ?></strong><br>
                        <span style="font-size: 11px; color:var(--accent);"><?= htmlspecialchars($s['class_name']) ?></span>
                    </td>
                    <td><code><?= htmlspecialchars($s['reg_number']) ?></code></td>
                    <td>
                        <label class="switch">
                            <input type="checkbox" class="access-toggle" 
                                   data-id="<?= $s['id'] ?>" 
                                   <?= (isset($s['result_access']) && $s['result_access'] == 1) ? 'checked' : '' ?>>
                            <span class="slider"></span>
                        </label>
                        <div id="status-text-<?= $s['id'] ?>" style="font-size: 10px; font-weight: bold; margin-top: 5px; color: <?= ($s['result_access'] == 1) ? '#27ae60' : '#e74c3c' ?>;">
                            <?= ($s['result_access'] == 1) ? 'CLEARED' : 'RESTRICTED' ?>
                        </div>
                    </td>
                    <td>
                        <a href="edit_student.php?id=<?= $s['id'] ?>" class="btn-edit"><i class="fa fa-edit"></i></a>
                        <?php if($_SESSION['role'] === 'superadmin'): ?>
                        <a href="?delete_id=<?= $s['id'] ?>" class="btn-del" onclick="return confirm('Delete Student?')"><i class="fa fa-trash"></i></a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.querySelectorAll('.access-toggle').forEach(toggle => {
    toggle.addEventListener('change', function() {
        const studentId = this.getAttribute('data-id');
        const status = this.checked ? 1 : 0;
        const statusText = document.getElementById('status-text-' + studentId);
        
        const formData = new FormData();
        formData.append('student_id', studentId);
        formData.append('status', status);

        fetch('update_access_status.php', { method: 'POST', body: formData })
        .then(response => response.json())
        .then(data => { 
            if(data.success) {
                if(status === 1) {
                    statusText.innerText = 'CLEARED';
                    statusText.style.color = '#27ae60';
                } else {
                    statusText.innerText = 'RESTRICTED';
                    statusText.style.color = '#e74c3c';
                }
            } else { 
                alert(data.message || 'Update failed'); 
                this.checked = !this.checked; // Revert switch if error
            } 
        })
        .catch(err => {
            alert('Error connecting to server');
            this.checked = !this.checked;
        });
    });
});
</script>
</body>
</html>