<?php
ini_set('display_errors', 0); // Disable errors before JSON output

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
if (!isset($postdata['institution_id'],$postdata['student_id'],$postdata['marksheet_id'],$postdata['api_signature'],$postdata['jwt_token'])
    || !checkIfIssetAndNotEmpty($postdata['institution_id'])
    || !checkIfIssetAndNotEmpty($postdata['student_id'])
    || !checkIfIssetAndNotEmpty($postdata['marksheet_id'])
    || !checkIfIssetAndNotEmpty($postdata['api_signature'])
    || !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    errorreturn("All required fields are missing.");
}

// Validate API signature & JWT
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;

// Validate access
$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'];

// Fetch marksheet info
$stmt = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id=?");
$stmt->execute([$marksheet_id]);
$rowmarksheet = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$rowmarksheet) errorreturn("Marksheet not found.");

// Fetch template info
$templateid = $rowmarksheet['template_id'];
$stmt = $conn_rjllearning->prepare("SELECT cols, template_name FROM template_info WHERE id=?");
$stmt->execute([$templateid]);
$ResultTemplate = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$ResultTemplate) errorreturn("Template not found.");
$cols = $ResultTemplate['cols'];

// Fetch student info
$stmt = $conn_rjllearning_specific->prepare("SELECT name, branch_id, class_id, academic_id, section_id FROM students WHERE id=?");
$stmt->execute([$student_id]);
$rowstudent = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$rowstudent) errorreturn("Student not found.");

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

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

// Total for main subjects
$total = 0;
for($i=3;$i<=7;$i++){
    $total += is_numeric($array[$i]) ? (int)$array[$i] : 0;
}
$array[10] = $total;

// Remarks
$array[11] = isset($postdata['11']) ? strtoupper(trim($postdata['11'])) : '';

// Encode JSON
$json_data = json_encode($array);

// Insert into DB
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
    $analytics = marksheet_analytics_04($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("Marks uploaded successfully.");
} catch(PDOException $e){
    $conn_rjllearning_specific->rollBack();
    errorreturn("Database error: ".$e->getMessage());
}

// Analytics function
function marksheet_analytics_04($marksData){
    $totalObtained = $marksData[10] ?? 0;
    $totalMax = 100;
    $percentage = round($totalObtained / $totalMax * 100, 2);
    $grade = getGrade($totalObtained,$totalMax);
    return [
        'total_obtained'=>$totalObtained,
        'total_max'=>$totalMax,
        'percentage'=>$percentage,
        'grade'=>$grade
    ];
}

// Grade function
function getGrade($marks,$total){
    $p = ($marks/$total)*100;
    if($p>=91) return 'A1';
    if($p>=81) return 'A2';
    if($p>=71) return 'B1';
    if($p>=61) return 'B2';
    if($p>=51) return 'C1';
    if($p>=41) return 'C2';
    if($p>=33) return 'D';
    return 'E';
}
?>