<?php
require __DIR__ . '/../includes/bootstrap.php';
require_login();

$pdo = db();
$errors = [];

$courses = $pdo->query('SELECT id, code, name FROM courses WHERE status = 1 ORDER BY name')->fetchAll();
$departments = $pdo->query('SELECT id, code, name FROM departments WHERE status = 1 ORDER BY name')->fetchAll();
$genders = $pdo->query('SELECT id, name FROM genders ORDER BY id')->fetchAll();
$schools = $pdo->query('SELECT id, name FROM schools WHERE status = 1 ORDER BY name')->fetchAll();

if (is_post()) {
    if (!validate_csrf_token($_POST['csrf_token'] ?? null)) {
        $errors[] = 'Invalid session token.';
    } else {
        $action = $_POST['action'] ?? 'create';

        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            $pdo->prepare('DELETE FROM students WHERE id = :id')->execute(['id' => $id]);
            add_flash('success', 'Student removed.');
            redirect('admin/students.php');
        }

        $payload = [
            'student_id' => trim($_POST['student_id'] ?? ''),
            'full_name' => trim($_POST['full_name'] ?? ''),
            'gender_id' => (int) ($_POST['gender_id'] ?? 0),
            'year_level' => (int) ($_POST['year_level'] ?? 1),
            'course_id' => (int) ($_POST['course_id'] ?? 0),
            'department_id' => (int) ($_POST['department_id'] ?? 0),
            'school_id' => (int) ($_POST['school_id'] ?? 0),
            'email' => trim($_POST['email'] ?? ''),
            'contact_number' => trim($_POST['contact_number'] ?? ''),
            'address' => trim($_POST['address'] ?? ''),
            'status' => (int) ($_POST['status'] ?? 1),
        ];

        if ($payload['student_id'] === '' || $payload['full_name'] === '') {
            $errors[] = 'Student ID and full name are required.';
        }

        if (!$errors) {
            if ($action === 'update') {
                $payload['id'] = (int) ($_POST['id'] ?? 0);
                $stmt = $pdo->prepare(
                    'UPDATE students SET student_id = :student_id, full_name = :full_name, gender_id = :gender_id,
                        year_level = :year_level, course_id = :course_id, department_id = :department_id,
                        school_id = :school_id, email = :email, contact_number = :contact_number,
                        address = :address, status = :status
                     WHERE id = :id'
                );
                $stmt->execute($payload);
                add_flash('success', 'Student updated.');
            } else {
                $qrToken = sprintf('STU-%s', strtoupper(random_token(6)));
                $stmt = $pdo->prepare(
                    'INSERT INTO students (student_id, full_name, gender_id, year_level, course_id, department_id, school_id,
                        email, contact_number, address, qr_code, status)
                     VALUES (:student_id, :full_name, :gender_id, :year_level, :course_id, :department_id, :school_id,
                        :email, :contact_number, :address, :qr_code, :status)'
                );
                $stmt->execute(array_merge($payload, ['qr_code' => $qrToken]));
                add_flash('success', 'Student registered.');
            }

            redirect('admin/students.php');
        }
    }
}

$pagination = paginate($pdo, 'SELECT COUNT(*) FROM students');
$stmt = $pdo->prepare(
    'SELECT s.*, c.name AS course_name, d.name AS department_name
     FROM students s
     LEFT JOIN courses c ON s.course_id = c.id
     LEFT JOIN departments d ON s.department_id = d.id
     ORDER BY s.full_name ASC
     LIMIT :limit OFFSET :offset'
);
$stmt->bindValue(':limit', $pagination['per_page'], PDO::PARAM_INT);
$stmt->bindValue(':offset', $pagination['offset'], PDO::PARAM_INT);
$stmt->execute();
$students = $stmt->fetchAll();

render_header('Students', ['active' => 'students']);
?>
<div class="card shadow-sm">
    <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Student Directory</h5>
            <small class="text-muted">Page <?= $pagination['page'] ?> of <?= $pagination['pages'] ?></small>
        </div>
        <div class="d-flex gap-2 align-items-center">
            <?php if ($errors): ?>
                <span class="text-danger small"><?= sanitize(implode(' ', $errors)) ?></span>
            <?php endif; ?>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#studentModal" data-mode="create">
                Add Student
            </button>
        </div>
    </div>
    <div class="card-body">
        <?php if (!$students): ?>
            <p class="text-muted mb-0 text-center">No students yet.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>Student</th>
                        <th>Course</th>
                        <th>Department</th>
                        <th>QR Token</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($students as $student): ?>
                        <?php
                        $payload = encode_record([
                            'id' => (int) $student['id'],
                            'student_id' => $student['student_id'],
                            'full_name' => $student['full_name'],
                            'gender_id' => (int) $student['gender_id'],
                            'year_level' => (int) $student['year_level'],
                            'course_id' => (int) $student['course_id'],
                            'department_id' => (int) $student['department_id'],
                            'school_id' => (int) $student['school_id'],
                            'email' => $student['email'],
                            'contact_number' => $student['contact_number'],
                            'address' => $student['address'],
                            'status' => (int) $student['status'],
                        ]);
                        ?>
                        <tr>
                            <td>
                                <strong><?= sanitize($student['full_name']) ?></strong><br>
                                <span class="text-muted-sm"><?= sanitize($student['student_id']) ?></span>
                            </td>
                            <td><?= sanitize($student['course_name'] ?? '—') ?></td>
                            <td><?= sanitize($student['department_name'] ?? '—') ?></td>
                            <td>
                                <code class="d-block mb-1"><?= sanitize($student['qr_code']) ?></code>
                                <button type="button"
                                        class="btn btn-sm btn-link px-0"
                                        data-bs-toggle="modal"
                                        data-bs-target="#qrModal"
                                        data-qr-token="<?= sanitize($student['qr_code']) ?>"
                                        data-student-id="<?= sanitize($student['student_id']) ?>"
                                        data-student-name="<?= sanitize($student['full_name']) ?>">
                                    View QR
                                </button>
                            </td>
                            <td>
                                <span class="badge <?= $student['status'] ? 'bg-success-subtle text-success' : 'bg-secondary' ?>">
                                    <?= $student['status'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-outline-primary"
                                        data-bs-toggle="modal"
                                        data-bs-target="#studentModal"
                                        data-mode="edit"
                                        data-record="<?= sanitize($payload) ?>">
                                    Edit
                                </button>
                                <button class="btn btn-sm btn-outline-danger"
                                        data-bs-toggle="modal"
                                        data-bs-target="#deleteStudentModal"
                                        data-student-name="<?= sanitize($student['full_name']) ?>"
                                        data-student-id="<?= sanitize($student['student_id']) ?>"
                                        data-record-name="<?= sanitize($student['full_name']) ?>"
                                        data-record-ref="<?= sanitize($student['student_id']) ?>"
                                        data-id="<?= (int) $student['id'] ?>">
                                    Delete
                                </button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php render_pagination($pagination); ?>
        <?php endif; ?>
    </div>
</div>

<!-- Student modal -->
<div class="modal fade" id="studentModal" tabindex="-1" aria-hidden="true"
     data-create-title="Add Student" data-edit-title="Edit Student"
     data-create-submit="Add Student" data-edit-submit="Save Changes">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <form method="post" class="needs-validation" novalidate>
                <div class="modal-header">
                    <h5 class="modal-title" data-modal-title>Add Student</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="create">
                    <input type="hidden" name="id" value="">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Student ID</label>
                            <input type="text" name="student_id" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Full Name</label>
                            <input type="text" name="full_name" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Gender</label>
                            <select name="gender_id" class="form-select">
                                <?php foreach ($genders as $gender): ?>
                                    <option value="<?= $gender['id'] ?>"><?= sanitize($gender['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Year Level</label>
                            <input type="number" min="1" max="6" name="year_level" class="form-control" value="1">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Course</label>
                            <select name="course_id" class="form-select">
                                <?php foreach ($courses as $course): ?>
                                    <option value="<?= $course['id'] ?>"><?= sanitize($course['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Department</label>
                            <select name="department_id" class="form-select">
                                <?php foreach ($departments as $department): ?>
                                    <option value="<?= $department['id'] ?>"><?= sanitize($department['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">School</label>
                            <select name="school_id" class="form-select">
                                <?php foreach ($schools as $school): ?>
                                    <option value="<?= $school['id'] ?>"><?= sanitize($school['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Email</label>
                            <input type="email" name="email" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Contact Number</label>
                            <input type="text" name="contact_number" class="form-control">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Address</label>
                            <textarea name="address" class="form-control" rows="2"></textarea>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-select">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Student</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- QR preview modal -->
<div class="modal fade" id="qrModal" tabindex="-1" aria-hidden="true" data-generator="<?= url_for('qr/generate.php') ?>">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <div class="text-muted small">QR Code</div>
                    <h5 class="modal-title mb-0" data-qr-name>Student Name</h5>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body text-center">
                <div class="mb-2 text-muted small" data-qr-id>ID: —</div>
                <div class="qr-preview mb-3">
                    <img src="" alt="QR Code" class="img-fluid" data-qr-image>
                </div>
                <code class="d-block" data-qr-token></code>
            </div>
            <div class="modal-footer">
                <a href="#" class="btn btn-primary w-100" data-qr-download download>
                    Download PNG
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Delete confirmation modal -->
<div class="modal fade" id="deleteStudentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Remove Student</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= sanitize(ensure_csrf_token()) ?>">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="">
                    <p class="mb-1">Are you sure you want to remove this student?</p>
                    <p class="fw-semibold mb-0" data-delete-name>Student Name</p>
                    <small class="text-muted" data-delete-id data-label="ID">ID: —</small>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php
render_footer();
