<?php

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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'students_api/modules/test/student_test_attempt/student_test_attempt_function.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

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

// $postdata = json_decode(file_get_contents("php://input"), true);
// checkIfNoPhpContentsReceive();


$postdata = $_POST;



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

$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;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

require_once $base_path_to_learning . 'functions/get_branch_functions.php';

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$test_id = trim($postdata['test_id']);
$remarks = null;
$points = null;
$status = 1;

$exam_start_time = (new DateTime())->format('H:i:s');
$exit_time = (new DateTime())->format('H:i:s');



if ($postdata['function_type'] == 'test_submission') {
   
    $test = fetchTestdetails($conn_rjllearning_specific, $test_id, $institution_id, $branch_id);
    if (!$test) {
        successReturn("Test does not exist.");
    }
  
    $display_question_by = $test['display_question_by'];

    // // Check if there's an existing test attempt
    $student_test_attempt_id = checkExistingTestAttempt($conn_rjllearning_specific, $institution_id, $branch_id, $test_id, $userid);

   


    // Process the test submission
    $result = processTestSubmission(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $test_id,
        $display_question_by,
        $postdata,
        $workspace_id,
        $userid,
        $class_id,
        $section_id,
        $student_test_attempt_id,
        $remarks,
        $points,
        $username,
        $status
    );

    if ($result === true) {
    $test_submission_id = $conn_rjllearning_specific->lastInsertId();

    // Update exit time
    $updateExitTimeQuery = "
        UPDATE test_attempt 
        SET exit_time = ?, status = 2 
        WHERE id = ? 
        AND test_id = ? 
        AND institution_id = ? 
        AND student_id = ?
    ";
    $updateExitTimeStmt = $conn_rjllearning_specific->prepare($updateExitTimeQuery);
    $updateExitTimeStmt->execute([$exit_time, $student_test_attempt_id, $test_id, $institution_id, $userid]);

    successreturn(['id' => $test_submission_id, 'successmsg' => "Test submitted successfully."]);
} elseif ($result === false) {
    // If only a question is submitted and the test is not yet complete
    successreturn(['successmsg' => "Question submitted successfully."]);
} else {
    errorreturn("Failed to process test submission.");
}
} else {
    errorreturn("No valid answer format found.");
}
