<?php

declare(strict_types=1);

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

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

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

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

if ($student_session_id <= 0 || $exam_type_id <= 0 || $class_id <= 0) {
    header('Location: marks-entry.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH STUDENT
|--------------------------------------------------------------------------
*/
$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 = ?
    AND ss.id = ?
    AND ss.status = 'Active'
    LIMIT 1
");

$studentStmt->execute([
    $school_id,
    $session_id,
    $class_id,
    $student_session_id
]);

$student = $studentStmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    header('Location: marks-entry.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH EXAM
|--------------------------------------------------------------------------
*/
$examStmt = $pdo->prepare("
    SELECT id, exam_name
    FROM exam_types
    WHERE school_id = ?
    AND id = ?
    LIMIT 1
");
$examStmt->execute([$school_id, $exam_type_id]);
$exam = $examStmt->fetch(PDO::FETCH_ASSOC);

if (!$exam) {
    header('Location: marks-entry.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH SUBJECTS FROM SCHEDULE
|--------------------------------------------------------------------------
*/
$subjectStmt = $pdo->prepare("
    SELECT
        es.id AS schedule_id,
        es.subject_id,
        es.max_marks,
        sub.name AS subject_name,
        sub.subject_code
    FROM exam_schedule es
    INNER JOIN subjects sub 
        ON sub.id = es.subject_id
        AND sub.school_id = es.school_id
    WHERE es.school_id = ?
    AND es.session_id = ?
    AND es.exam_type_id = ?
    AND es.class_id = ?
    AND es.no_exam = 0
    ORDER BY sub.name ASC
");

$subjectStmt->execute([
    $school_id,
    $session_id,
    $exam_type_id,
    $class_id
]);

$subjects = $subjectStmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($subjects)) {
    header('Location: marks-entry.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| FETCH EXISTING MARKS FOR FALLBACKS
|--------------------------------------------------------------------------
*/
$marksStmt = $pdo->prepare("
    SELECT
        subject_id,
        marks_obtained,
        attendance_status,
        remarks
    FROM exam_marks
    WHERE school_id = ?
    AND session_id = ?
    AND exam_type_id = ?
    AND class_id = ?
    AND student_id = ?
");

$marksStmt->execute([
    $school_id,
    $session_id,
    $exam_type_id,
    $class_id,
    $student['student_id']
]);

$existingMarks = [];
while ($row = $marksStmt->fetch(PDO::FETCH_ASSOC)) {
    $existingMarks[(int) $row['subject_id']] = $row;
}

require_once __DIR__ . '/../include/header.php';
require_once __DIR__ . '/../include/sidebar.php';
?>

<div class="content-wrapper">
    <section class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1>Enter Marks</h1>
                </div>
            </div>
        </div>
    </section>

    <section class="content">
        <div class="container-fluid">
            
            <div class="card card-outline card-info">
                <div class="card-header">
                    <h3 class="card-title">Student Information</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-2 text-center mb-3 mb-md-0">
                            <?php
                            $rootPath = defined('WEB_ROOT') ? WEB_ROOT : '/';
                            $photo = !empty($student['photo'])
                                ? $rootPath . 'student/uploads/' . $student['photo']
                                : 'https://placehold.co/120x120?text=No+Photo';
                            ?>
                            <img src="<?= htmlspecialchars($photo, ENT_QUOTES, 'UTF-8'); ?>" class="img-thumbnail img-fluid" style="max-width: 120px;" alt="Student Photo">
                        </div>

                        <div class="col-md-10">
                            <div class="table-responsive">
                                <table class="table table-bordered mb-0">
                                    <tr>
                                        <th width="20%">Student Name</th>
                                        <td><?= htmlspecialchars($student['name'], ENT_QUOTES, 'UTF-8'); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Roll No</th>
                                        <td><?= htmlspecialchars((string)($student['roll_no'] ?? '-'), ENT_QUOTES, 'UTF-8'); ?></td>
                                    </tr>
                                    <tr>
                                        <th>Exam</th>
                                        <td><?= htmlspecialchars($exam['exam_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card card-outline card-primary">
                <div class="card-header">
                    <h3 class="card-title">Subject Wise Marks Entry</h3>
                </div>

                <form id="marksEntryForm" method="POST">
                    <?= csrfField(); ?>
                    
                    <input type="hidden" name="student_session_id" value="<?= (int) $student_session_id; ?>">
                    <input type="hidden" name="student_id" value="<?= (int) $student['student_id']; ?>">
                    <input type="hidden" name="exam_type_id" value="<?= (int) $exam_type_id; ?>">
                    <input type="hidden" name="class_id" value="<?= (int) $class_id; ?>">

                    <div class="card-body table-responsive p-0">
                        <table class="table table-bordered table-striped mb-0">
                            <thead>
                                <tr>
                                    <th width="5%" class="text-center">#</th>
                                    <th>Subject</th>
                                    <th width="12%">Max Marks</th>
                                    <th width="18%">Obtained</th>
                                    <th width="15%">Attendance</th>
                                    <th width="25%">Remarks</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($subjects as $index => $subject): ?>
                                    <?php
                                    $subjectId = (int) $subject['subject_id'];
                                    $existing = $existingMarks[$subjectId] ?? [];
                                    $maxMarks = htmlspecialchars((string)$subject['max_marks'], ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <tr>
                                        <td class="text-center" style="vertical-align: middle;">
                                            <?= $index + 1; ?>
                                        </td>
                                        <td style="vertical-align: middle;">
                                            <strong><?= htmlspecialchars($subject['subject_name'], ENT_QUOTES, 'UTF-8'); ?></strong>
                                            <br>
                                            <small class="text-muted"><?= htmlspecialchars((string)($subject['subject_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></small>
                                        </td>
                                        <td style="vertical-align: middle;">
                                            <span class="badge badge-secondary"><?= $maxMarks; ?></span>
                                        </td>
                                        <td>
                                            <input 
                                                type="number" 
                                                step="0.01" 
                                                min="0" 
                                                max="<?= $maxMarks; ?>" 
                                                name="marks_obtained[<?= $subjectId; ?>]" 
                                                class="form-control marks-input" 
                                                value="<?= htmlspecialchars((string)($existing['marks_obtained'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>"
                                                <?= (($existing['attendance_status'] ?? 'Present') === 'Absent') ? 'readonly' : ''; ?>
                                            >
                                        </td>
                                        <td>
                                            <select name="attendance_status[<?= $subjectId; ?>]" class="form-control attendance-selector">
                                                <option value="Present" <?= (($existing['attendance_status'] ?? 'Present') === 'Present') ? 'selected' : ''; ?>>Present</option>
                                                <option value="Absent" <?= (($existing['attendance_status'] ?? '') === 'Absent') ? 'selected' : ''; ?>>Absent</option>
                                            </select>
                                        </td>
                                        <td>
                                            <input 
                                                type="text" 
                                                name="remarks[<?= $subjectId; ?>]" 
                                                class="form-control" 
                                                maxlength="255" 
                                                value="<?= htmlspecialchars($existing['remarks'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                                                placeholder="Optional notes"
                                            >

                                            <input type="hidden" name="subject_id[]" value="<?= $subjectId; ?>">
                                            <input type="hidden" name="schedule_id[<?= $subjectId; ?>]" value="<?= (int) $subject['schedule_id']; ?>">
                                            <input type="hidden" name="total_marks[<?= $subjectId; ?>]" value="<?= $maxMarks; ?>">
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="card-footer text-right">
                        <a href="marks-entry.php" class="btn btn-default float-left">
                            <i class="fas fa-arrow-left mr-1"></i> Back
                        </a>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-save mr-1"></i> Save Marks
                        </button>
                    </div>
                </form>
            </div>

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

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script src="assets/js/marks-form.js"></script>

<?php require_once __DIR__ . '/../include/footer.php'; ?>