<?php

declare(strict_types=1);

header('Content-Type: application/json');

require_once __DIR__ . '/../library/auth.php';

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

$school_id          = (int) $_SESSION['school_id'];

$current_session_id = (int) get_current_session_id($pdo);

// ======================================================
// VALID ACTION
// ======================================================

$action = trim($_GET['action'] ?? '');

$allowed_actions = [

    'load_students'

];

if (!in_array($action, $allowed_actions, true)) {

    http_response_code(400);

    echo json_encode([

        'success' => false,
        'message' => 'Invalid action.'

    ]);

    exit;
}

// ======================================================
// LOAD STUDENTS
// ======================================================

if ($action === 'load_students') {

    try {

        $class_id = (int) ($_GET['class_id'] ?? 0);

        $attendance_date = trim(
            $_GET['attendance_date'] ?? ''
        );

        // ==============================================
        // VALIDATION
        // ==============================================

        if ($class_id <= 0) {

            throw new Exception(
                'Invalid class selected.'
            );
        }

        if (
            !preg_match(
                '/^\d{4}-\d{2}-\d{2}$/',
                $attendance_date
            )
        ) {

            throw new Exception(
                'Invalid attendance date.'
            );
        }

        // ==============================================
        // VERIFY CLASS
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT

                id,
                class_name

            FROM classes

            WHERE id = ?
            AND school_id = ?

            LIMIT 1
        ");

        $stmt->execute([

            $class_id,
            $school_id

        ]);

        $class = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$class) {

            throw new Exception(
                'Class not found.'
            );
        }

        // ==============================================
        // HOLIDAY CHECK
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT

                title,
                holiday_type

            FROM holidays

            WHERE school_id = ?
            AND holiday_date = ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $attendance_date

        ]);

        $holiday = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($holiday) {

            echo json_encode([

                'success' => true,

                'is_holiday' => true,

                'holiday_title' =>
                    $holiday['title'],

                'holiday_type' =>
                    $holiday['holiday_type']

            ]);

            exit;
        }

        // ==============================================
        // WEEKLY OFF CHECK
        // ==============================================

        $day_name = date(
            'l',
            strtotime($attendance_date)
        );

        $stmt = $pdo->prepare("
            SELECT id

            FROM weekly_offs

            WHERE school_id = ?
            AND day_name = ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $day_name

        ]);

        $weekly_off = $stmt->fetch();

        if ($weekly_off) {

            echo json_encode([

                'success' => true,

                'is_weekly_off' => true,

                'day_name' => $day_name

            ]);

            exit;
        }

        // ==============================================
        // FETCH STUDENTS
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT

                ss.id AS student_session_id,

                s.name,

                ss.roll_no,

                ss.section,

                ss.admission_no

            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.status = 'Active'

            ORDER BY

                CAST(ss.roll_no AS UNSIGNED) ASC,

                s.name ASC
        ");

        $stmt->execute([

            $school_id,
            $current_session_id,
            $class_id

        ]);

        $students = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // ==============================================
        // EXISTING ATTENDANCE
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT

                student_session_id,
                status,
                remarks

            FROM attendance

            WHERE school_id = ?
            AND session_id = ?
            AND attendance_date = ?
        ");

        $stmt->execute([

            $school_id,
            $current_session_id,
            $attendance_date

        ]);

        $attendance_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $attendance_map = [];

        foreach ($attendance_rows as $row) {

            $attendance_map[
                $row['student_session_id']
            ] = [

                'status'  => $row['status'],
                'remarks' => $row['remarks']

            ];
        }

        // ==============================================
        // FINAL RESPONSE
        // ==============================================

        echo json_encode([

            'success' => true,

            'class_name' =>
                $class['class_name'],

            'attendance_date' =>
                $attendance_date,

            'students' => $students,

            'attendance' => $attendance_map

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

            'message' => $e->getMessage()

        ]);

        exit;
    }
}
?>