<?php

declare(strict_types=1);

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

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

allow_roles(['admin']);

requirePostRequest();

verifyCsrfToken();

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

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

/*
|--------------------------------------------------------------------------
| VALIDATE INPUTS
|--------------------------------------------------------------------------
*/

$grade_name = cleanString(
    $_POST['grade_name'] ?? ''
);

$min_percentage = (float) (
    $_POST['min_percentage'] ?? 0
);

$max_percentage = (float) (
    $_POST['max_percentage'] ?? 0
);

$grade_point = (float) (
    $_POST['grade_point'] ?? 0
);

$remarks = cleanString(
    $_POST['remarks'] ?? ''
);

/*
|--------------------------------------------------------------------------
| VALIDATIONS
|--------------------------------------------------------------------------
*/

if ($grade_name === '') {

    jsonResponse(
        false,
        'Grade name is required!'
    );
}

if (
    $min_percentage < 0 ||
    $min_percentage > 100
) {

    jsonResponse(
        false,
        'Invalid minimum percentage!'
    );
}

if (
    $max_percentage < 0 ||
    $max_percentage > 100
) {

    jsonResponse(
        false,
        'Invalid maximum percentage!'
    );
}

if ($min_percentage > $max_percentage) {

    jsonResponse(
        false,
        'Minimum percentage cannot be greater than maximum percentage!'
    );
}

/*
|--------------------------------------------------------------------------
| CHECK OVERLAP
|--------------------------------------------------------------------------
*/

$overlapStmt = $pdo->prepare("
    SELECT COUNT(*) AS total

    FROM exam_grades

    WHERE school_id = ?

    AND (
        (? BETWEEN min_percentage AND max_percentage)
        OR
        (? BETWEEN min_percentage AND max_percentage)
    )
");

$overlapStmt->execute([

    $school_id,

    $min_percentage,

    $max_percentage
]);

$overlapCount = (int) $overlapStmt->fetchColumn();

if ($overlapCount > 0) {

    jsonResponse(
        false,
        'Percentage range overlaps with existing grade!'
    );
}

try {

    /*
    |--------------------------------------------------------------------------
    | SAVE GRADE
    |--------------------------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        INSERT INTO exam_grades (

            school_id,
            grade_name,
            min_percentage,
            max_percentage,
            grade_point,
            remarks

        ) VALUES (

            ?, ?, ?, ?, ?, ?
        )
    ");

    $stmt->execute([

        $school_id,
        $grade_name,
        $min_percentage,
        $max_percentage,
        $grade_point,
        $remarks
    ]);

    /*
    |--------------------------------------------------------------------------
    | AUDIT LOG
    |--------------------------------------------------------------------------
    */

    $auditStmt = $pdo->prepare("
        INSERT INTO audit_logs (

            school_id,
            user_id,
            module,
            action,
            record_id,
            message,
            ip_address,
            user_agent

        ) VALUES (

            ?, ?, ?, ?, ?, ?, ?, ?
        )
    ");

    $auditStmt->execute([

        $school_id,
        $user_id,
        'Exams',
        'Save Grade',
        (int) $pdo->lastInsertId(),
        'Grade rule created successfully',

        $_SERVER['REMOTE_ADDR'] ?? '',

        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);

    jsonResponse(
        true,
        'Grade rule saved successfully!'
    );

} catch (Throwable $e) {

    jsonResponse(
        false,
        $e->getMessage()
    );
}