<?php

declare(strict_types=1);

// Production ready configuration: dynamic logs safely isolated from AJAX outputs
ini_set('display_errors', '0');
error_reporting(E_ALL);

require_once __DIR__ . '/../../library/auth.php';
require_once __DIR__ . '/../helpers/result-helper.php';

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

requirePostRequest();
verifyCsrfToken();

$school_id = (int) $_SESSION['school_id'];
$session_id = (int) ($_SESSION['session_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| VALIDATE INPUTS
|--------------------------------------------------------------------------
*/
$exam_type_id = validateId($_POST['exam_type_id'] ?? 0);
$class_id = validateId($_POST['class_id'] ?? 0);

if ($exam_type_id <= 0 || $class_id <= 0 || $session_id <= 0) {
    jsonResponse(false, 'Invalid request data!');
}

/*
|--------------------------------------------------------------------------
| VERIFY EXAM
|--------------------------------------------------------------------------
*/
$examStmt = $pdo->prepare("
    SELECT id FROM exam_types
    WHERE school_id = ? AND id = ? AND status = 'Active'
    LIMIT 1
");
$examStmt->execute([$school_id, $exam_type_id]);

if (!$examStmt->fetch()) {
    jsonResponse(false, 'Invalid exam selected!');
}

/*
|--------------------------------------------------------------------------
| VERIFY CLASS
|--------------------------------------------------------------------------
*/
$classStmt = $pdo->prepare("
    SELECT id FROM classes
    WHERE school_id = ? AND id = ?
    LIMIT 1
");
$classStmt->execute([$school_id, $class_id]);

if (!$classStmt->fetch()) {
    jsonResponse(false, 'Invalid class selected!');
}

/*
|--------------------------------------------------------------------------
| FETCH STUDENTS
|--------------------------------------------------------------------------
*/
$studentStmt = $pdo->prepare("
    SELECT
        ss.id AS student_session_id,
        ss.roll_no,
        s.id AS student_id,
        s.name,
        s.photo
    FROM student_sessions ss
    INNER JOIN students s ON s.id = ss.student_id
    WHERE ss.school_id = ?
    AND ss.session_id = ?
    AND ss.class_id = ?
    ORDER BY
        CAST(ss.roll_no AS UNSIGNED) ASC,
        s.name ASC
");
$studentStmt->execute([$school_id, $session_id, $class_id]);
$students = $studentStmt->fetchAll(PDO::FETCH_ASSOC);

/*
|--------------------------------------------------------------------------
| EMPTY CHECK
|--------------------------------------------------------------------------
*/
if (empty($students)) {
    jsonResponse(false, 'No students found!');
}

/*
|--------------------------------------------------------------------------
| BUILD HTML
|--------------------------------------------------------------------------
*/
$html = '';
$rootPath = defined('WEB_ROOT') ? WEB_ROOT : '/';

foreach ($students as $student) {
    $studentPhoto = !empty($student['photo'])
        ? $rootPath . 'student/uploads/' . $student['photo']
        : 'https://placehold.co/80x80?text=No+Photo';

    $html .= '
        <tr>
            <td>' . htmlspecialchars((string)($student['roll_no'] ?? '-'), ENT_QUOTES, 'UTF-8') . '</td>
            <td class="text-center">
                <img src="' . htmlspecialchars($studentPhoto, ENT_QUOTES, 'UTF-8') . '" class="img-thumbnail" width="60" alt="Student Photo">
            </td>
            <td><strong>' . htmlspecialchars($student['name'], ENT_QUOTES, 'UTF-8') . '</strong></td>
            <td class="text-center">
                <a href="marks-entry-list.php?student_session_id=' . (int) $student['student_session_id'] . '&exam_type_id=' . (int) $exam_type_id . '&class_id=' . (int) $class_id . '" class="btn btn-primary btn-sm">
                    <i class="fas fa-edit mr-1"></i> Enter Marks
                </a>
            </td>
        </tr>
    ';
}

/*
|--------------------------------------------------------------------------
| STANDARD JSON RESPONSE (Debug print_r and exit loops removed)
|--------------------------------------------------------------------------
*/
jsonResponse(true, 'Students loaded successfully!', [
    'html' => $html
]);