<?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';
require_once $base_path_to_learning . 'admin_api/modules/test/test_questions/bank_questions_functions.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;


$required_fields = ['institution_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;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
$institution_id = trim($postdata['institution_id']);

// 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';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning,$conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$class_id = trim($postdata['class_id']);
$subject_id = trim($postdata['subject_id']);
// $branch_id = trim($postdata['branch_id']);
$section_id = trim($postdata['section_id']);
$test_id = trim($postdata['test_id']);

// $status = trim($postdata['status']) ;
$status = 1;
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}
$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied");
}

if ($postdata['function_type'] == 'create_question_test') {
    if (!isset($postdata['questions']) || !is_array($postdata['questions'])) {
        errorreturn("Questions are required and must be a array.");
    }
    $questions = array();
    //  $questions = json_decode($postdata['questions'], true);
    $questions = $postdata['questions'];

    if (!isset($questions) || !is_array($questions) || empty($questions)) {
        errorreturn("Questions are required.");
    }
    $max_points = 0;
    // addQuestions($conn_rjllearning_specific, $questions,$test_id,$institution_id,$branch_id,$class_id,$section_id,$subject_id,$username);  

    // foreach ($questions as $index => $question) {
    //     $question_bank =   isQuestionInBank($conn_rjllearning_specific, $question, $institution_id, $branch_id);
    //     foreach ($questions as $index => $question) {
    //         //print_r($question_bank);
    //         if ($question_bank == true) {
    //             $questionId = getExistingQuestionId($conn_rjllearning_specific, $question, $institution_id, $branch_id);
    //         } else {
    //             $questionId = saveNewQuestionToBank($conn_rjllearning_specific, $question, $institution_id, $branch_id, $index, $class_id, $section_id, $subject_id, $username,$workspace_id);
    //         }

    //         if (!isQuestionInTest($conn_rjllearning_specific, $test_id, $questionId, $institution_id, $branch_id)) {
    //             saveQuestionToTest($conn_rjllearning_specific, $test_id, $questionId,$question['question_marks'], $institution_id, $branch_id, $username);
    //         }

    //     }

    // }
    foreach ($questions as $index => $question) {
        // Check if the question already exists in the question bank
        $question_bank = isQuestionInBank($conn_rjllearning_specific, $question, $institution_id, $branch_id);

        // If the question exists in the bank, get its ID
        if ($question_bank) {
            $questionId = getExistingQuestionId($conn_rjllearning_specific, $question, $institution_id, $branch_id);
        } else {
            // If the question doesn't exist in the bank, save it to the bank
            $questionId = saveNewQuestionToBank($conn_rjllearning_specific, $question, $institution_id, $branch_id, $index, $class_id, $section_id, $subject_id, $username, $workspace_id);
        }

        // Check if the question is already associated with the test
        if (!isQuestionInTest($conn_rjllearning_specific, $test_id, $questionId, $institution_id, $branch_id)) {
            // If the question is not associated with the test, save it to the test
            saveQuestionToTest($conn_rjllearning_specific, $test_id, $questionId, $question['question_marks'], $institution_id, $branch_id, $username);
        }
    }


    $updateTestQuery = "UPDATE test SET max_points = (
        SELECT SUM(q.question_marks) 
        FROM test_questions tq
        JOIN question_bank_info q ON tq.question_bank_id = q.id
        WHERE tq.test_id = ? AND tq.institution_id = ?) WHERE id = ? AND institution_id = ? AND branch_id = ?";

    $updateTestStmt = $conn_rjllearning_specific->prepare($updateTestQuery);
    $updateTestStmt->execute([$test_id, $institution_id, $test_id, $institution_id, $branch_id]);



    successreturn(['id' => $questionId, 'successmsg' => "Successfully added bank questions."]);
} else if ($postdata['function_type'] == 'alter_test_question') {
    // Check if test ID is provided
    if (!isset($postdata['bank_questions_id'])) {
        errorreturn("question bank ID is not provided.");
    }

    $question_bank_id = $postdata['bank_questions_id'];

    $questions = array();
    //  $questions = json_decode($postdata['questions'], true);
    $questions = $postdata['questions'];

    if (!isset($questions) || !is_array($questions) || empty($questions)) {
        errorreturn("Questions are required.");
    }
    $max_points = 0;

    foreach ($questions as $index => $question) {
        // Check if the question is in the bank
        $question_bank = isExistingQuestionInBank($conn_rjllearning_specific, $question, $institution_id, $branch_id, $question_bank_id);

        if ($question_bank == true) {
            // Get the existing question ID
            //$questionId = getExistingQuestionId($conn_rjllearning_specific, $question, $institution_id, $branch_id);

            // Update the question in the bank if necessary
            updateQuestionInBank($conn_rjllearning_specific, $question, $question_bank_id, $institution_id, $branch_id, $index, $class_id, $section_id, $subject_id, $username, $workspace_id);
        } else {
            // Save the new question to the bank
            $question_bank_id = saveNewQuestionToBank($conn_rjllearning_specific, $question, $institution_id, $branch_id, $index, $class_id, $section_id, $subject_id, $username, $workspace_id);
        }

        // Check if the question is in the test
        if (!isQuestionInTest($conn_rjllearning_specific, $test_id, $question_bank_id, $institution_id, $branch_id)) {
            // Save the question to the test

            saveQuestionToTest($conn_rjllearning_specific, $test_id, $question_bank_id, $question['question_marks'], $institution_id, $branch_id, $username);
        } else {
            // Update the question in the test if necessary
            updateQuestionInTest($conn_rjllearning_specific, $test_id, $question_bank_id, $question['question_marks'], $institution_id, $branch_id, $username);
        }
    }

    $updateTestQuery = "UPDATE test SET max_points = (
        SELECT SUM(q.question_marks) 
        FROM test_questions tq
        JOIN question_bank_info q ON tq.question_bank_id = q.id
        WHERE tq.test_id = ? AND tq.institution_id = ?) WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $updateTestStmt = $conn_rjllearning_specific->prepare($updateTestQuery);
    $updateTestStmt->execute([$test_id, $institution_id, $test_id, $institution_id, $branch_id]);



    successreturn("Test question updated successfully.");
}
