<?php
ini_set('display_errors', 1);

// Include necessary files
require_once '../../base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

// Decode input data
$postdata = $_POST;

// Validate required fields
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['student_id']) || !checkIfIssetAndNotEmpty($postdata['student_id']) ||
    !isset($postdata['marksheet_id']) || !checkIfIssetAndNotEmpty($postdata['marksheet_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess(
    $conn_rjllearning,
    $userid,
    $role,
    $workspace_id,
    ["superadmin", "admin", "principal", "teacher"],
    null
);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

$institution_id = $postdata['institution_id'];
$student_id = $postdata['student_id'];
$marksheet_id = $postdata['marksheet_id'];

// Check if marksheet exists
$ExecuteSqlMarksheet = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id = ?");
$ExecuteSqlMarksheet->execute([$marksheet_id]);
$rowmarksheet = $ExecuteSqlMarksheet->fetch(PDO::FETCH_ASSOC);

if (!$rowmarksheet) {
    errorreturn("Marksheet does not exist.");
}

// Fetch template info
$templateid = $rowmarksheet['template_id'];
$ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT id, cols, template_name FROM template_info WHERE id = ?");
$ExecuteSqlTemplate->execute([$templateid]);
$ResultTemplate = $ExecuteSqlTemplate->fetch(PDO::FETCH_ASSOC);

if (!$ResultTemplate) {
    errorreturn("Marksheet Template does not exist.");
}

$cols = $ResultTemplate['cols'];

// Fetch student data
$ExecuteSqlStudent = $conn_rjllearning_specific->prepare("SELECT name, branch_id, class_id, academic_id, section_id FROM students WHERE id = ?");
$ExecuteSqlStudent->execute([$student_id]);
$rowstudent = $ExecuteSqlStudent->fetch(PDO::FETCH_ASSOC);

if (!$rowstudent) {
    errorreturn("Student does not exist.");
}

$branch = $rowstudent['branch_id'];
$class = $rowstudent['class_id'];
$academic_id = $rowstudent['academic_id'];
$section_id = $rowstudent['section_id'];

// Grade calculation function
function getGrade($obtained, $max)
{
    $temp = ($max > 0) ? ($obtained / $max) * 100 : 0;
    if ($temp >= 91) return 'A 1';
    if ($temp >= 81) return 'A 2';
    if ($temp >= 71) return 'B 1';
    if ($temp >= 61) return 'B 2';
    if ($temp >= 51) return 'C 1';
    if ($temp >= 41) return 'C 2';
    if ($temp >= 33) return 'D';
    return 'E';
}

// Delete old entries
$deleteExistingData = $conn_rjllearning_specific->prepare("
    DELETE FROM student_marksheet_data
    WHERE student_id = ? AND marksheet_id = ?
");
$deleteExistingData->execute([$student_id, $marksheet_id]);

// Build marksheet array
$array = [];
for ($i = 1; $i <= $cols; $i++) {
    $value = $postdata[$i] ?? '';
    if (in_array($i, [28])) {
        $array[$i] = trim($value);
    } else {
        $array[$i] = strtoupper(trim($value));
    }
}

$subject_map = [
    'English'       => ['written' => 5, 'oral' => 6],
    'Mathematics'   => ['written' => 10, 'oral' => 11],
    'Punjabi'       => ['written' => 14, 'oral' => 15],
    'EVS & GK'      => ['written' => 19, 'oral' => 20],
    'Rhymes'        => ['written' => 23, 'oral' => 24],
    'Story'         => ['written' => 25, 'oral' => 26]
];

$subject_rankings = [];
$total_obtained = 0;
$total_max = 0;

foreach ($subject_map as $subject => $index) {

    $written = ($index['written'] !== null && isset($array[$index['written']]) && is_numeric($array[$index['written']]))
        ? floatval($array[$index['written']]) : 0;

    $oral = (isset($array[$index['oral']]) && is_numeric($array[$index['oral']]))
        ? floatval($array[$index['oral']]) : 0;

    // Max limits
    if ($written > 50) $written = 50;
    if ($oral > 30) $oral = 30;

    $obtained = $written + $oral;
    $max_marks = 80;

    $percentage = ($max_marks > 0) ? round(($obtained / $max_marks) * 100, 2) : 0;
    $grade = getGrade($obtained, $max_marks);

    $subject_rankings[] = [
        "subject" => $subject,
        "written" => $written,
        "oral" => $oral,
        "obtained" => $obtained,
        "max" => $max_marks,
        "percentage" => $percentage,
        "grade" => $grade
    ];

    $total_obtained += $obtained;
    $total_max += $max_marks;
}


// ----------------------------------------------------------
// REMOVE ART & CRAFT AND CONVERSATION GRADE — DONE
// ----------------------------------------------------------

// Sort subjects by percentage (DESC)
usort($subject_rankings, function($a, $b) {
    return $b['percentage'] <=> $a['percentage'];
});

$highest_subject = $subject_rankings[0]['subject'];
$lowest_subject = $subject_rankings[count($subject_rankings) - 1]['subject'];

$overall_percentage_formatted = ($total_max > 0)
    ? number_format(($total_obtained / $total_max) * 100, 2, '.', '')
    : number_format(0, 2, '.', '');
$overall_grade = getGrade($total_obtained, $total_max);


// FINAL ANALYTICS ARRAY
$analytics = [
    "total_obtained" => $total_obtained,
    "total_max" => $total_max,
    "percentage" => $overall_percentage_formatted,
    "grade" => $overall_grade,
    "highest_marks_obtained_subject" => $highest_subject,
    "lowest_marks_obtained_subject" => $lowest_subject,
    "subject_rankings" => $subject_rankings,
     "remarks" => isset($array[28]) ? $array[28] : ""
];

$json_encoded_array = json_encode($array);
$json_encoded_analytics = json_encode($analytics);

// Insert data
try {
    $insert = $conn_rjllearning_specific->prepare("
        INSERT INTO student_marksheet_data (
            institution_id,
            marksheet_id,
            student_id,
            data,
            analytics,
            branch_id,
            academic_id,
            class_id,
            section_id,
            created_by,
            date_created,
            time_created,
            status
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $insertSuccessful = $insert->execute([
        $institution_id,
        $marksheet_id,
        $student_id,
        $json_encoded_array,
        $json_encoded_analytics,
        $branch,
        $academic_id,
        $class,
        $section_id,
        $username,
        date("Y-m-d"),
        date("H:i:s"),
        '1'
    ]);

    if ($insertSuccessful) {
        successreturn("Data inserted successfully.");
    } else {
        errorreturn("Failed to insert data into marksheet_data.");
    }
} catch (PDOException $e) {
    errorreturn("Database error: " . $e->getMessage());
}
?>
