<?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
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 and 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 user access
$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
$stmtMarks = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id=?");
$stmtMarks->execute([$marksheet_id]);
$marksheet = $stmtMarks->fetch(PDO::FETCH_ASSOC);
if (!$marksheet) errorreturn("Marksheet does not exist.");

// Fetch template info
$template_id = $marksheet['template_id'];
$stmtTemplate = $conn_rjllearning->prepare("SELECT cols, template_name FROM template_info WHERE id=?");
$stmtTemplate->execute([$template_id]);
$template = $stmtTemplate->fetch(PDO::FETCH_ASSOC);
if (!$template) errorreturn("Marksheet Template does not exist.");
$cols = $template['cols'];

// Fetch student data
$stmtStudent = $conn_rjllearning_specific->prepare("SELECT * FROM students WHERE id=?");
$stmtStudent->execute([$student_id]);
$student = $stmtStudent->fetch(PDO::FETCH_ASSOC);
if (!$student) errorreturn("Student does not exist.");

// Initialize array
$array = [];
for ($i=1;$i<=35;$i++) $array[$i]='';

// Map POST data
$array[1] = isset($postdata[1]) ? $postdata[1] : '';
for ($i=2;$i<=33;$i++){
    $array[$i] = isset($postdata[$i]) ? $postdata[$i] : '';
}
$array[34] = isset($postdata[34]) ? $postdata[34] : '';
$array[35] = isset($postdata[35]) ? $postdata[35] : '';

// JSON encode
$json_array = json_encode($array);

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

try {
    $conn_rjllearning_specific->beginTransaction();
    
    // Insert new data
    $stmtInsert = $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 (?,?,?,?,?,?,?,?,?,?,?,?)
    ");
    $stmtInsert->execute([
        $institution_id, $marksheet_id, $student_id, $json_array,
        $student['branch_id'], $student['academic_id'], $student['class_id'], $student['section_id'],
        $username, date("Y-m-d"), date("H:i:s"), '1'
    ]);
    $insertId = $conn_rjllearning_specific->lastInsertId();
    
    // Calculate analytics
    $analytics = marksheet_analytics_28($array);
    
    // Update analytics
    $stmtUpdate = $conn_rjllearning_specific->prepare("UPDATE student_marksheet_data SET analytics=? WHERE id=?");
    $stmtUpdate->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 for Template 28
function marksheet_analytics_28($marksData){
    $subjects = [];
    $totalObtained = 0;
    $totalMax = 0;

    $subjectTypeMap = ['M'=>'Mandatory','O'=>'Optional','A'=>'Additional'];

    // Each subject is stored in 3 fields (name, type, obtained)
    $subjectPositions = range(2, 33, 3);

    foreach ($subjectPositions as $index) {
        $name = $marksData[$index] ?? '';
        if (empty($name)) continue;

        $typeAbbr = $marksData[$index+1] ?? '';
        $type = $subjectTypeMap[$typeAbbr] ?? 'Unknown';
        $marksObtained = (float)($marksData[$index+2] ?? 0);

        $subjectTotal = 20; // fixed max marks
        $subjectObtained = $marksObtained;

        if ($typeAbbr == 'M' || $typeAbbr == 'O') {
            $totalMax += $subjectTotal;
            $totalObtained += $subjectObtained;
        }

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

        $subjects[] = [
            'name' => $name,
            'type' => $type,
            'type_abbr' => $typeAbbr,
            'total' => $subjectTotal,
            'obtained' => $subjectObtained,
            'percentage' => $percentage,
            'grade' => $grade
        ];
    }

    $overallPercentage = $totalMax > 0 ? round(($totalObtained/$totalMax)*100,2) : 0;
    $overallGrade = getGrade($totalObtained, $totalMax);

    $highest = 'N/A'; $lowest = 'N/A'; $highPerc = 0; $lowPerc = 100;
    foreach ($subjects as $s) {
        if ($s['percentage'] > $highPerc) { $highPerc = $s['percentage']; $highest = $s['name']; }
        if ($s['percentage'] < $lowPerc && $s['percentage'] > 0) { $lowPerc = $s['percentage']; $lowest = $s['name']; }
    }

    return [
        'total_obtained' => (int)$totalObtained,
        'total_max' => (int)$totalMax,
        'percentage' => $overallPercentage,
        'grade' => $overallGrade,
        'highest_marks_obtained_subject' => $highest,
        'lowest_marks_obtained_subject' => $lowest,
        'subject_rankings' => $subjects
    ];
}

function getGrade($obtained,$total){
    if($total<=0) return 'N/A';
    $perc = ($obtained/$total)*100;
    if($perc>=91) return 'A 1';
    if($perc>=81) return 'A 2';
    if($perc>=71) return 'B 1';
    if($perc>=61) return 'B 2';
    if($perc>=51) return 'C 1';
    if($perc>=41) return 'C 2';
    if($perc>=33) return 'D';
    return 'E';
}
?>
