<?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';
require_once $base_path_to_learning_resources . 'marksheet_template/template25/process.php';

// Get 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']);
$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
$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'];

// Check template existence
$ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT id FROM template_info WHERE id = ?");
$ExecuteSqlTemplate->execute([$marksheet_id]);
if (count($ExecuteSqlTemplate->fetchAll()) != 1) {
    errorreturn("Marksheet Template does not exist.");
}

// Fetch marksheet data
$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'];
}

// Grade calculation function
function getGrade($temp_marks, $total_marks) {
    if ($total_marks <= 0) return 'Invalid total marks';
    
    $percentage = ($temp_marks / $total_marks) * 100;
    
    if ($percentage >= 91) return 'A 1';
    if ($percentage >= 81) return 'A 2';
    if ($percentage >= 71) return 'B 1';
    if ($percentage >= 61) return 'B 2';
    if ($percentage >= 51) return 'C 1';
    if ($percentage >= 41) return 'C 2';
    if ($percentage >= 33) return 'D';
    return 'E';
}

// Get 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 data
$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.");
} else {
    $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 = ?
");
if (!$deleteExistingData->execute([$student_id, $marksheet_id])) {
    errorreturn("Failed to delete existing data.");
}

// Initialize necessary variables
// Initialize the array and total marks
$array = array(); // Initialize your array

// Initialize all columns with default values
for ($i = 1; $i <= 70; $i++) {
    $array[$i] = 0; // Start with 0
}

// Assign specific indices to empty strings or other default values as needed
$array[7] = ""; 
$array[14] = ""; 
$array[21] = ""; 
$array[28] = ""; 
$array[35] = ""; 
$array[42] = ""; 
$array[49] = "";
$array[56] = "";

$array[59] = ""; // Overall percentage
$array[60] = "";

for ($i = 60; $i <= 75; $i++) {
    $array[$i] = ""; // Initialize grade-related columns to empty
}

for ($i = 1; $i <= 77; $i++) {
    // Check if the index exists in $postdata and is not empty
    if (isset($postdata[$i])) {
        // Assign the value from postdata, ensuring it's properly converted
        $array[$i] = (float)$postdata[$i]; // Store as float for accurate calculations
    }

    // Group sums and grades logic (only for indices up to 49)
    if ($i <= 56 ) {
            $array[6] = (float)$array[5] + (float)$array[1] + (float)$array[2] + (float)$array[3] + (float)$array[4];
           $group_sum = $array[6]; // Assign group sum directly to the next index
            $array[7] = getGrade($group_sum, 100); // Assign grade based on group sum
            
            $array[13] = (float)$array[8] + (float)$array[9] + (float)$array[10] + (float)$array[11] + (float)$array[12];
           $group_sum = $array[13]; // Assign group sum directly to the next index
            $array[14] = getGrade($group_sum, 100);
            
             $array[20] = (float)$array[15] + (float)$array[16] + (float)$array[17] + (float)$array[18] + (float)$array[19];
           $group_sum = $array[20]; // Assign group sum directly to the next index
            $array[21] = getGrade($group_sum, 100);
            
            $array[27] = (float)$array[22] + (float)$array[23] + (float)$array[24] + (float)$array[25] + (float)$array[26];
           $group_sum = $array[27]; // Assign group sum directly to the next index
            $array[28] = getGrade($group_sum, 100);
            
            $array[34] = (float)$array[29] + (float)$array[30] + (float)$array[31] + (float)$array[32] + (float)$array[33];
           $group_sum = $array[34]; // Assign group sum directly to the next index
            $array[35] = getGrade($group_sum, 100);
            
            
            $array[41] = (float)$array[36] + (float)$array[37] + (float)$array[38] + (float)$array[39] + (float)$array[40];
           $group_sum = $array[41]; // Assign group sum directly to the next index
            $array[42] = getGrade($group_sum, 100);
            
            $array[48] = (float)$array[43] + (float)$array[44] + (float)$array[45] + (float)$array[46] + (float)$array[47];
           $group_sum = $array[48]; // Assign group sum directly to the next index
            $array[49] = getGrade($group_sum, 100);
            
            $array[55] = (float)$array[50] + (float)$array[51] + (float)$array[52] + (float)$array[53] + (float)$array[54];
           $group_sum = $array[55]; // Assign group sum directly to the next index
            $array[56] = getGrade($group_sum, 100);
    }

    // Calculate total marks from specific columns
    if ($i == 58) {
        // Calculate total marks from specific indices, avoiding overwriting
        $total_marks = (float)$array[6] + (float)$array[13]+ (float)$array[20]+(float)$array[27]+ (float)$array[34]+ (float)$array[41]+ (float)$array[48] + (float)$array[55]; // Adjust based on your specific needs
        $array[$i] = $total_marks; 
    }

    // Calculate and assign percentage
    if ($i == 59) {
        if (isset($total_marks) && $total_marks > 0) {
            $array[$i] = number_format(($total_marks / 800) * 100, 2, '.', '') . '%'; // Assuming total marks possible is 700
        } else {
            $array[$i] = "0.00%"; // Default to 0% if total marks are zero
        }
    }

    // Assign overall grade based on total marks
    if ($i == 60) {
         $array[60] = getGrade($total_marks, 800); // Assuming max is 700
    }

    // Convert input to uppercase for specific columns
    if ($i >= 61 && $i <= 75) {
        $array[$i] = isset($postdata[$i]) ? strtoupper($postdata[$i]) : '';
    }

    // Handle participation and remarks fields
    if ($i == 76 || $i == 77) {
        if (isset($postdata[$i]) && trim($postdata[$i]) != '') {
            $array[$i] = ucwords(trim($postdata[$i]));
        } else {
            $array[$i] = ''; // Default to empty if no input
        }
    }
}

// JSON encode the array
$json_encoded_array = json_encode($array);

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();
    
    // Calculate analytics
    $analytics = marksheet_analytics_02($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) {
    $conn_rjllearning_specific->rollBack();
    errorreturn("Database error: " . $e->getMessage());
}

function marksheet_analytics_02($marksData)
{
    $subjects = [
        [
            'name' => 'English',
            'sum_index' => 6,
            'grade_index' => 7,
            'components' => [1 => 5, 2 => 5, 3 => 5, 4 => 5, 5 => 80]
        ],
        [
            'name' => 'Hindi',
            'sum_index' => 13,
            'grade_index' => 14,
            'components' => [8 => 5, 9 => 5, 10 => 5, 11 => 5, 12 => 80]
        ],
        [
            'name' => 'Punjabi',
            'sum_index' => 20,
            'grade_index' => 21,
            'components' => [15 => 5, 16 => 5, 17 => 5, 18 => 5, 19 => 80]
        ],
        [
            'name' => 'Mathematics',
            'sum_index' => 27,
            'grade_index' => 28,
            'components' => [22 => 5, 23 => 5, 24 => 5, 25 => 5, 26 => 80]
        ],
        [
            'name' => 'Science',
            'sum_index' => 34,
            'grade_index' => 35,
            'components' => [29 => 5, 30 => 5, 31 => 5, 32 => 5, 33 => 80]
        ],
        [
            'name' => 'Social Science',
            'sum_index' => 41,
            'grade_index' => 42,
            'components' => [36 => 5, 37 => 5, 38 => 5, 39 => 5, 40 => 80]
        ],
        [
            'name' => 'General Knowledge',
            'sum_index' => 48,
            'grade_index' => 49,
            'components' => [43 => 5, 44 => 5, 45 => 5, 46 => 5, 47 => 80]
        ],
        [
            'name' => 'Computer Education ',
            'sum_index' => 55,
            'grade_index' => 56,
            'components' => [50 => 5, 51 => 5, 52 => 5, 53 => 5, 54 => 80]
        ]
    ];

    $totalObtained = 0;
    $totalMax = 0;
    $subjectRankings = [];

    foreach ($subjects as $subject) {
        $subjectObtained = (float)($marksData[$subject['sum_index']] ?? 0);
        $grade = $marksData[$subject['grade_index']] ?? '';
        $totalObtained += $subjectObtained;
        $subjectMax = 100;
        $totalMax += $subjectMax;

        $subjectRankings[] = [
            'subject' => $subject['name'],
            'total' => $subjectObtained,
            'percentage' => round(($subjectObtained / $subjectMax) * 100, 2),
            'grade' => $grade
        ];
    }

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

    $highestSubject = $subjectRankings[0];
    $lowestSubject = end($subjectRankings);

    // Overall calculations
    $percentage = $totalMax > 0 ? round(($totalObtained / $totalMax) * 100, 2) : 0;
    $grade = $marksData[60] ?? getGrade($totalObtained, $totalMax);

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

}

