<?php
ini_set('display_errors', 1);
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';

$postdata = $_POST;

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

validateApiSignature($postdata['api_signature']);
$jwt_validate = authenticate_jwt($postdata['jwt_token']);

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["superadmin","admin","principal","teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.1');
} 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 & template
$rowmarksheet = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id=? AND institution_id=?");
$rowmarksheet->execute([$marksheet_id, $institution_id]);
$rowmarksheet = $rowmarksheet->fetch(PDO::FETCH_ASSOC);
if(!$rowmarksheet) errorreturn("Marksheet does not exist.");

$templateid = $rowmarksheet['template_id'];
$ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT cols 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
$rowstudent = $conn_rjllearning_specific->prepare("SELECT name, branch_id, class_id, academic_id, section_id FROM students WHERE id=?");
$rowstudent->execute([$student_id]);
$rowstudent = $rowstudent->fetch(PDO::FETCH_ASSOC);
if(!$rowstudent) errorreturn("Student does not exist.");

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

// Prepare marks array
$marks = [];
for($i=1;$i<=6;$i++){
    $marks[$i] = isset($postdata[$i]) ? (float)$postdata[$i] : 0;
}
$total_obtained = array_sum($marks);
$marks[7] = $total_obtained;
$marks[8] = trim($postdata[8] ?? '');

$json_data = json_encode($marks);

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_data,
        $rowstudent['branch_id'], $rowstudent['academic_id'], $rowstudent['class_id'], $rowstudent['section_id'],
        $username, date('Y-m-d'), date('H:i:s'), '1'
    ]);

    $insertId = $conn_rjllearning_specific->lastInsertId();

    // Analytics calculation
    $analytics = calculateMarksheetAnalytics_15($marks, $total_obtained);
    $conn_rjllearning_specific->prepare("UPDATE student_marksheet_data SET analytics=? WHERE id=?")
        ->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());
}

function calculateMarksheetAnalytics_15($marks, $total_obtained){
    $subjects = ['English','Mathematics','E.V.S','Punjabi','Hindi'];
    $subjectMax = [20,20,20,20,20]; // Max marks per subject
    $subjectRankings = [];

    // Calculate per subject percentages and grades
    foreach($subjects as $index => $sub){
        $percentage = round(($marks[$index+1] / $subjectMax[$index]) * 100, 2);
        $grade = getGrade($percentage);

        $subjectRankings[] = [
            'subject' => $sub,
            'percentage' => $percentage,
            'grade' => $grade
        ];
    }

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

    $highestSubject = $subjectRankings[0]['subject'];
    $lowestSubject = $subjectRankings[count($subjectRankings)-1]['subject'];

    // Total max marks dynamically
    $totalMax = array_sum($subjectMax);
    $percentage = round(($total_obtained / $totalMax) * 100, 2);
    $grade = getGrade($percentage);

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

// Grade function
function getGrade($percent){
    if($percent >= 91) return 'A1';
    elseif($percent >= 81) return 'A2';
    elseif($percent >= 71) return 'B1';
    elseif($percent >= 61) return 'B2';
    elseif($percent >= 51) return 'C1';
    elseif($percent >= 41) return 'C2';
    elseif($percent >= 33) return 'D';
    else return 'E';
}




?>
