<?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 JSON input data
// $postdata = json_decode(file_get_contents("php://input"), true);

// // Check if no data was received
// checkIfNoPhpContentsReceive();

$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']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['jwt_token']) or  !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'];
// $branch_id = $postdata['branch_id'];
// $academic_id = $postdata['academic_id'];
// $class_id = $postdata['class_id'];
// $section_id = $postdata['section_id'];

//checking marksheet existence in db

// Step 1: Check if the associated template exists
// $ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT id FROM template_info WHERE id = ?");
// $ExecuteSqlTemplate->execute([$marksheet_id]); // Use marksheet_id to check the template
// $ResultTemplate = $ExecuteSqlTemplate->fetchAll();

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

// Step 2: If the template exists, fetch data from marksheet_info
$ExecuteSqlMarksheet = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id = ?");
$ExecuteSqlMarksheet->execute([$marksheet_id]);

// Fetch the result
$rowmarksheet = $ExecuteSqlMarksheet->fetch(PDO::FETCH_ASSOC);

// Check if marksheet exists
if (!$rowmarksheet) {
    errorreturn("Marksheet does not exist.");
} else {
    // If it exists, fetch the required data
    $examination = $rowmarksheet['examination_name'];
    $templateid = $rowmarksheet['template_id'];
    $academicsession = $rowmarksheet['academic_session'];
    $createdon = $rowmarksheet['time_created'];
    $createdon = $rowmarksheet['date_created']; // Ensure proper date formatting
    $createdby = $rowmarksheet['added_by'];

    // Now you can use the fetched data as needed
}

function getGrade($temp_marks, $total_marks)
{
    $temp = ($temp_marks / $total_marks) * 100;
    if ($temp >= 91 and $temp <= 100) {
        return 'A 1';
    } else if ($temp >= 81 and $temp <= 90) {
        return 'A 2';
    } else if ($temp >= 71 and $temp <= 80) {
        return 'B 1';
    } else if ($temp >= 61 and $temp <= 70) {
        return 'B 2';
    } else if ($temp >= 51 and $temp <= 60) {
        return 'C 1';
    } else if ($temp >= 41 and $temp <= 50) {
        return 'C 2';
    } else if ($temp >= 33 and $temp <= 40) {
        return 'D';
    } else if ($temp < 33) {
        return 'E';
    }
}
//fetching template data
$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.");
}

// If the template exists, extract the template name and other relevant data
$templateName = $ResultTemplate['template_name'];
$cols = $ResultTemplate['cols'];

//fetching 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]);

// Fetch the result
$rowstudent = $ExecuteSqlStudent->fetch(PDO::FETCH_ASSOC);

// Check if student exists
if (!$rowstudent) {
    errorreturn("Student does not exist.");
} else {
    // If the student exists, retrieve the desired fields
    $studentname = $rowstudent['name'];
    $branch = $rowstudent['branch_id'];
    $class = $rowstudent['class_id'];
    $academic_id = $rowstudent['academic_id'];
    $section_id = $rowstudent['section_id'];
}

//deleting any pre entries
$deleteExistingData = $conn_rjllearning_specific->prepare("
    DELETE FROM student_marksheet_data 
    WHERE student_id = ? AND marksheet_id = ?
");

// Execute the query with the student ID and marksheet ID
$deleteSuccessful = $deleteExistingData->execute([$student_id, $marksheet_id]);
if (!$deleteSuccessful) {
    errorreturn("Failed to delete existing data.");
}
// Initialize the array with a size of $cols and fill it with empty values
$array = array_fill(1, $cols, '');

// Fill the array with actual values
for ($i = 1; $i <= $cols; $i++) {
    if ($i == 3) {
        // Calculate the total for specific array indexes (starting from 1)
        // Ensure values are numeric before summing them up
        $total = (float)$array[1] + (float)$array[2];
        $array[3] = $total; // Store the total in the 4th position
    } else {
        // Store the cleaned and uppercased POST data
        $value = strtoupper(trim(str_replace("'", "''", $postdata[$i] ?? '')));
        $array[$i] = $value;
    }
}

// Serialize the array to JSON
$json_encoded_array = json_encode($array);

try {
    $conn_rjllearning_specific->beginTransaction();

    // Prepare the SQL statement
    $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();

    // Calculate analytics
    $analytics = marksheet_analytics_17($array);

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

    $conn_rjllearning_specific->commit();

    if ($updateSuccessful) {
        successreturn("Data inserted successfully.");
    } else {
        errorreturn("Failed to insert data into marksheet_data.");
    }
} catch (PDOException $e) {
    // Handle any PDO exceptions
    errorreturn("Database error: " . $e->getMessage());
}

function marksheet_analytics_17($marksData)
{
    // Subject mapping with unique keys
    $subjects = [
        1 => 'English',
        2 => 'Mathematics'
    ];

    $totalObtained = (float)($marksData[3] ?? 0);
    $totalMax = 40; 
    
    // Calculate percentage with proper rounding
    $percentage = round(($totalObtained / $totalMax) * 100, 2);
    $percentage = (float)number_format($percentage, 2, '.', ''); // Force clean decimal format

    // Calculate subject percentages
    $subjectRankings = [];
    foreach ($subjects as $index => $subjectName) {
        $obtained = (float)($marksData[$index] ?? 0);
        $subjectPercentage = round(($obtained / 20) * 100, 2);
        
        $subjectRankings[] = [
            'subject' => $subjectName,
            'percentage' => (float)number_format($subjectPercentage, 2, '.', '')
        ];
    }

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

    return [
        'total_obtained' => $totalObtained,
        'total_max' => $totalMax,
        'percentage' => $percentage,
        'grade' => getGrade($totalObtained, $totalMax),
        'highest_marks_obtained_subject' => $subjectRankings[0]['subject'],
        'lowest_marks_obtained_subject' => end($subjectRankings)['subject'],
        'subject_rankings' => $subjectRankings
    ];
}
