<?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';

// Use POST 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.");
}

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.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

// Fetch marksheet
$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.");
} else {
    $examination = $rowmarksheet['examination_name'];
    $templateid = $rowmarksheet['template_id'];
    $academicsession = $rowmarksheet['academic_session'];
    $createdby = $rowmarksheet['added_by'];
}

// Get grade function
function getGrade($temp_marks, $total_marks)
{
    $temp = ($total_marks > 0) ? ($temp_marks / $total_marks) * 100 : 0;
    if ($temp >= 91 && $temp <= 100) return 'A 1';
    else if ($temp >= 81 && $temp <= 90) return 'A 2';
    else if ($temp >= 71 && $temp <= 80) return 'B 1';
    else if ($temp >= 61 && $temp <= 70) return 'B 2';
    else if ($temp >= 51 && $temp <= 60) return 'C 1';
    else if ($temp >= 41 && $temp <= 50) return 'C 2';
    else if ($temp >= 33 && $temp <= 40) return 'D';
    else return 'E';
}

// Fetch template info
$ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT 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.");

$templateName = $ResultTemplate['template_name'];
$cols = $ResultTemplate['cols'];

// Fetch student info
$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.");

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

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

// Prepare marks array
$array = array_fill(1, $cols, '');
for ($i = 1; $i <= 11; $i++) {
    $array[$i] = isset($postdata[$i]) ? strtoupper(trim(str_replace("'", "''", $postdata[$i]))) : '';
}

// Calculate total for main subjects
$total = 0;
for ($i = 5; $i <= 10; $i++) { // include Information Technology
    $total += is_numeric($array[$i]) ? (int)$array[$i] : 0;
}
$array[12] = $total;
$array[13] = isset($postdata['13']) ? strtoupper(trim(str_replace("'", "''", $postdata['13']))) : '';

$json_encoded_array = json_encode($array);

// Insert data and calculate analytics
try {
    $conn_rjllearning_specific->beginTransaction();

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

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

    $insertId = $conn_rjllearning_specific->lastInsertId();

    // Analytics
    $analytics = marksheet_analytics_13($array);

    $update = $conn_rjllearning_specific->prepare("UPDATE student_marksheet_data SET analytics = ? WHERE id = ?");
    $update->execute([json_encode($analytics), $insertId]);

    $conn_rjllearning_specific->commit();
    successreturn("Data inserted successfully.");

} catch (PDOException $e) {
    $conn_rjllearning_specific->rollBack();
    errorreturn("Database error: " . $e->getMessage());
}

// Analytics function
function marksheet_analytics_13($marksData)
{
    $allSubjects = [
        5 => 'English',
        6 => 'Physical Education',
        7 => $marksData[1],
        8 => $marksData[2],
        9 => $marksData[3],
        10 => $marksData[4],
        11 => 'Information Technology'
    ];

    $totalObtained = 0;
    $subjectRankings = [];

    foreach ($allSubjects as $index => $subjectName) {
        $obtained = is_numeric($marksData[$index]) ? (float)$marksData[$index] : 0;
        $totalObtained += $obtained;

        // Calculate grade per subject (max marks = 40)
        $subjectGrade = getGrade($obtained, 40);

        $subjectRankings[] = [
            'subject' => $subjectName,
            'percentage' => round(($obtained / 40) * 100, 2),
            'grade' => $subjectGrade
        ];
    }

    $totalMax = 200;
    $percentage = round(($totalObtained / $totalMax) * 100, 2);

    // Determine highest and lowest among main subjects
    $mainSubjects = array_slice($allSubjects, 0, 5, true);
    $mainSubjectMarks = [];
    foreach ($mainSubjects as $idx => $subj) {
        $mainSubjectMarks[$subj] = is_numeric($marksData[$idx]) ? (float)$marksData[$idx] : 0;
    }

    arsort($mainSubjectMarks);
    $highestSubject = key($mainSubjectMarks);
    $lowestSubject = array_key_last($mainSubjectMarks);

    usort($subjectRankings, function($a, $b) {
        return $b['percentage'] <=> $a['percentage'];
    });

    $grade = getGrade($totalObtained, $totalMax);

    return [
        'total_obtained' => $totalObtained,
        'total_max' => $totalMax,
        'percentage' => $percentage,
        'grade' => $grade,
        'highest_marks_obtained_subject' => $highestSubject,
        'lowest_marks_obtained_subject' => $lowestSubject,
        'subject_rankings' => $subjectRankings
    ];
}

?>
