<?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';

$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.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details
$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 DB connection
$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);

// Extract form fields
$institution_id = $postdata['institution_id'];
$student_id = $postdata['student_id'];
$marksheet_id = $postdata['marksheet_id'];

// Fetch marksheet info
$stmtMarksheet = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE id = ?");
$stmtMarksheet->execute([$marksheet_id]);
$rowmarksheet = $stmtMarksheet->fetch(PDO::FETCH_ASSOC);
if (!$rowmarksheet) {
    errorreturn("Marksheet does not exist.");
}
$templateid = $rowmarksheet['template_id'];

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

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

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

// -------------------- FIX START --------------------

// Initialize array
$array = [];

// Populate from POST data
foreach ($postdata as $key => $value) {
    if (is_numeric($key)) {
        $index = (int)$key;
        if ($index >= 1 && $index <= $cols) {
            $array[$index] = trim($value);
        }
    }
}

// Ensure numeric marks (TH + PR)
for ($i = 8; $i <= 21; $i++) {
    if (!isset($postdata[$i]) || $postdata[$i] === '' || !is_numeric($postdata[$i])) {
        $array[$i] = 0;
    } else {
        $array[$i] = (int)$postdata[$i];
    }
}

// Calculate total (store in 22 if needed)
$array[22] = 0;
for ($i = 8; $i <= 21; $i++) {
    $array[22] += $array[$i];
}

// Make sure optional fields exist
for ($i = 23; $i <= 26; $i++) {
    if (!isset($array[$i])) {
        $array[$i] = '';
    }
}

// Encode without reindexing
$json_array = array_values($array);
$json_encoded_array = json_encode($array, JSON_UNESCAPED_UNICODE);

// -------------------- FIX END --------------------

try {
    // 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    // Execute the query with the provided parameters
    $insertSuccessful = $insert->execute([
        $institution_id,    
        $marksheet_id,
        $student_id,
        $json_encoded_array,
        $branch,
        $academic_id,
        $class,
        $section_id,
        $username, // Added by the current user
        date("Y-m-d"), // Date created
        date("H:i:s"), // Time created
        '1' // Default status to 1
    ]);

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