<?php

// Set up error reporting
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../../resources/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_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';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// Check if JSON is valid
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// $postdata = $_POST;
// print_r($postdata);die();
$required_fields = ['institution_id', 'branch_id', 'test_id','api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}



validateApiSignature($postdata['api_signature']);

// Authenticate user and get user details
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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 to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
// Include necessary function files
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// $quiz_submission_id = $postdata['quiz_submission_id'];
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$student_id = trim($postdata['student_id']);
$test_id = trim($postdata['test_id']);
// $quiz_questions_id = trim($postdata['quiz_questions_id']);
$remarks = (isset($postdata['remarks']) and !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$points = (isset($postdata['points']) and !empty($postdata['points'])) ? trim($postdata['points']) : null;
$marks_array = (isset($postdata['marks_array']) and !empty($postdata['marks_array'])) ? ($postdata['marks_array']) : null;;

//check quiz_id  exists or not
$quizExistenceQuery = "SELECT id,max_points FROM  test WHERE id  = ? AND institution_id = ? AND branch_id = ?";
$quizExistenceStmt = $conn_rjllearning_specific->prepare($quizExistenceQuery);
$quizExistenceStmt->execute([$test_id,$institution_id, $branch_id]);
$resultquizExistence = $quizExistenceStmt->fetchAll();
if (count($resultquizExistence) < 1) {
    errorreturn("quiz not exists.");
}
$max_points = $resultquizExistence[0]['max_points'];
$status  = 2; //checked

// $quizQuery = "SELECT id FROM  quiz_questions WHERE id  = ?  AND institution_id = ? AND branch_id = ? AND quiz_id= ?";
// $quizStmt = $conn_rjllearning_specific->prepare($quizQuery);
// $quizStmt->execute([$quiz_questions_id,$institution_id, $branch_id,$quiz_id]);

// if (count($quizStmt->fetchAll()) < 1) {
//     errorreturn("quiz questions not exists.");
// }

// Check if the given points are not greater than the quiz's max points
if ($points > $max_points) {
    errorreturn("quiz points cannot be greater than the maximum points.");
}

if ($postdata['function_type'] == 'alter_test_submission') {
        
    if (is_array($marks_array) && !empty($marks_array)) {
    foreach ($marks_array as $tempMarks) {
        // print_r($marks_array);die();
        $quiz_questions_id = $tempMarks['test_questions_id'];
        $quiz_submission_id = $tempMarks['test_submission_id'];
        $marks_obtained = isset($tempMarks['marks_obtained']) ? trim($tempMarks['marks_obtained']) : null;

        
        $updatequiz = "UPDATE test_submission SET marks_obtained = ? WHERE id = ? AND test_questions_id = ?  AND institution_id = ? AND student_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($updatequiz);
        $stmt->execute([$marks_obtained, $quiz_submission_id, $quiz_questions_id, $institution_id,$student_id]);
    }
    // successreturn("Quiz submissions updated successfully");
}

$updatequizQuery = "UPDATE test_submission SET remarks = ?, points = ?, last_modified_by = ?,status= ? WHERE test_id = ? AND institution_id = ? AND student_id = ?";
$stmt = $conn_rjllearning_specific->prepare($updatequizQuery);
$stmt->execute([$remarks, $points, $username,$status, $test_id, $institution_id,$student_id]);
successreturn("Test submission updated successfully");

}



