<?php

require_once '../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
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;
// echo "<pre>";
// var_dump($postdata);
// echo "</pre>";
// print_r($postdata);
// die();
// // print_r($postdata['question_text_answer']);
// // print_r(json_decode($postdata['question_text_answer'], true));
// die();

// Validate required fields
$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);
//then workspace_id is iin decodede data of jwt use from there
$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 = 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 = (isset($postdata['remarks']) && !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$points = (isset($postdata['points']) && !empty($postdata['points'])) ? trim($postdata['points']) : null;
$status = 1;


// Check if test exists
// $joinQuery = "
//     SELECT a.id AS test_id, a.max_points,
//           q.id AS question_id, q.question_type, q.question_text, q.answer, q.options ,q.question_marks
//     FROM tests AS a
//     JOIN test_questions AS q ON a.id = q.test_id
//     WHERE a.id = ? 
//       AND q.id = ?
//       AND a.institution_id = ?
//       AND a.branch_id = ?
// ";

// $joinStmt = $conn_rjllearning_specific->prepare($joinQuery);
// $joinStmt->execute([$test_id, $test_questions_id, $institution_id, $branch_id]);
// $result = $joinStmt->fetch();
// if (!$result) {
//     errorreturn("test question or test does not exist.");
// }

$joinQuery = "
    SELECT 
        t.id AS test_id, 
        t.max_points,
        q.id AS test_question_id,
        q.question_bank_id,
        qb.question_type,
        qb.question_description	,
        qb.answer,
        qb.options,
        qb.question_marks 
    FROM 
        test AS t 
    JOIN 
        test_questions AS q 
        ON t.id = q.test_id 
    JOIN 
        question_bank_info AS qb 
        ON q.question_bank_id = qb.id 
    WHERE 
        t.id = ?  
        AND t.institution_id = ? 
        AND t.branch_id = ?
";
$joinStmt = $conn_rjllearning_specific->prepare($joinQuery);
$joinStmt->execute([$test_id, $institution_id, $branch_id]);
$result = $joinStmt->fetchAll(PDO::FETCH_ASSOC);


if (!$result) {
    errorreturn("Test question or test does not exist.");
}



$testQuery = "SELECT max_points, publish_date, last_date, publish_time,NOW() AS current_datetime FROM test WHERE id = ?  AND institution_id = ? AND branch_id = ?";
$testStmt = $conn_rjllearning_specific->prepare($testQuery);
$testStmt->execute([$test_id, $institution_id, $branch_id]);
$testDetails = $testStmt->fetch(PDO::FETCH_ASSOC);

if (!$testDetails) {
    errorreturn("Test details not found.");
}

$max_points = $testDetails['max_points'];
$publish_date = $testDetails['publish_date'];
$last_date = $testDetails['last_date'];
$publish_time = $testDetails['publish_time'];
$current_datetime = $testDetails['current_datetime'];

// Check if current date and time is within allowed submission window
if ($current_datetime < $publish_date) {
    errorreturn("Test is not yet published.");
} elseif ($current_datetime > $last_date) {
    errorreturn("Test submission period has ended.");
}


// Check if the question type is "mcq" and if it has options
// if ($result['question_type'] == 'mcq') {
//     $options = json_decode($result['options'], true);
//     if (empty($options)) {
//         errorreturn("MCQ question must have options.");
//     }
// }

// Function type: create_test_submission


$studentTestAttemptQuery = "
    SELECT id 
    FROM test_attempt 
    WHERE institution_id = ? 
      AND branch_id = ? 
      AND test_id = ? 
      AND student_id = ?
";
$studentTestAttemptStmt = $conn_rjllearning_specific->prepare($studentTestAttemptQuery);
$studentTestAttemptStmt->execute([$institution_id, $branch_id, $test_id, $userid]);
$student_test_attempt_id = $studentTestAttemptStmt->fetchColumn();



// Check if a student test attempt ID was found
if (!$student_test_attempt_id) {
    errorreturn("No student test attempt found for the provided parameters.");
}

if ($postdata['function_type'] == 'create_test_submission') {

    // $testExistenceQuery = "SELECT id FROM student_test_submission WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ?  AND test_id = ? AND student_id=? ";
    // $testExistenceStmt = $conn_rjllearning_specific->prepare($testExistenceQuery);
    // $testExistenceStmt->execute([$institution_id, $branch_id, $class_id, $section_id, $test_id, $userid]);
    // $existing_tests = $testExistenceStmt->fetchAll();
    // if (count($existing_tests) >= 1) {
    //     errorreturn("test with the same name already exists.");
    // }


   $testQuery = "
    SELECT 
        qbi.id AS question_bank_id, 
        qbi.question_type, 
        qbi.question_description, 
        qbi.answer, 
        qbi.options,
        tq.test_id
    FROM 
        question_bank_info qbi
    JOIN 
        test_questions tq 
        ON qbi.id = tq.question_bank_id
    WHERE 
        tq.institution_id = ? 
        AND tq.branch_id = ? 
        AND tq.test_id = ?
";
$testStmt = $conn_rjllearning_specific->prepare($testQuery);
$testStmt->execute([$institution_id, $branch_id, $test_id]);
$testQuestion = $testStmt->fetch(PDO::FETCH_ASSOC);

if (!$testQuestion) {
    errorreturn("Test question does not exist.");
}


    $correct_answer = $testQuestion['answer'];

    if (isset($postdata['question_text_answer']) && !empty($postdata['question_text_answer'])) {
        // Check if it's already decoded or still a JSON string
        $question_text_answer = is_array($postdata['question_text_answer']) ? $postdata['question_text_answer'] : json_decode($postdata['question_text_answer'], true);

        // Proceed with further processing
        if (!is_array($question_text_answer)) {
            errorreturn("Invalid JSON format for 'question_text_answer'.");
        }

        // Initialize variables
        $marks_obtained = 0;
        $insertValues = []; // Array to hold multiple insert values

        foreach ($question_text_answer as  $index => $answer) {
            $file_key = 'file_' . $answer['test_questions_id'];
            if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] == UPLOAD_ERR_OK) {
                // Handle file upload

                $question_attachment = [
                    'name' => $_FILES[$file_key]['name'],
                    'type' => $_FILES[$file_key]['type'],
                    'tmp_name' => $_FILES[$file_key]['tmp_name'],
                    'error' => $_FILES[$file_key]['error'],
                    'size' => $_FILES[$file_key]['size'],
                ];

                $response[] = [
                    'test_questions_id' => $answer['test_questions_id'],
                    'answer' => $answer['answer'],
                    'file' => $question_attachment,
                ];
            } else {
                $response[] = [
                    'test_questions_id' => $answer['test_questions_id'],
                    'answer' => $answer['answer'],
                    'file' => null,
                ];
            }

            // Print the results for debugging

        }

        foreach ($response as $rows) {
            $test_questions_id = isset($rows['test_questions_id']) ? trim($rows['test_questions_id']) : null;
            $student_selected_answer = isset($rows['answer']) ? trim($rows['answer']) : null;
            $question_attachment = isset($rows['file']) ? ($rows['file']) : null;
            // Validate if test_questions_id and student_selected_answer are not empty
            if (!$test_questions_id) {
                errorreturn("Invalid format.");
            }

          // Fetch correct answer and marks from database based on test_questions_id
$sqlAnswers = "
    SELECT 
        qbi.answer, 
        qbi.question_type, 
        qbi.options,
        tq.question_marks 
    FROM 
        test_questions tq
    JOIN 
        question_bank_info qbi 
    ON 
        tq.question_bank_id = qbi.id 
    WHERE 
        tq.test_id = ? 
        AND tq.id = ? 
        AND tq.institution_id = ? 
        AND tq.branch_id = ?
";
$stmtAnswers = $conn_rjllearning_specific->prepare($sqlAnswers);
$stmtAnswers->execute([$test_id, $test_questions_id, $institution_id, $branch_id]);
$result_answers = $stmtAnswers->fetch(PDO::FETCH_ASSOC);

if (!$result_answers) {
    errorreturn("test question with ID $test_questions_id does not exist.");
}


            // Extract correct answer and marks from result
            $correct_answer = $result_answers['answer'];
            $question_marks = $result_answers['question_marks'];
            $question_type = $result_answers['question_type'];

            // Calculate marks obtained based on student's answer
            if ($question_type === 'mcq') {
                // Check for MCQ options and correct answer
                $options = json_decode($result_answers['options'], true);
                if (empty($options)) {
                    errorreturn("MCQ question must have options.");
                }

                // Calculate marks for MCQ
                $marks_obtained = ($student_selected_answer == $correct_answer) ? $question_marks : 0;
            }
            if($question_attachment == null) {
                $question_attachment = null;
            }else{
                // Directory path for storing uploaded files
                $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/question_attachment/" . date('Y') . "/" . date('m') . "/";

                // Single file upload
                $file_name = $question_attachment['name'];
                $fileTmpName = $question_attachment["tmp_name"];
                $fileSize = $question_attachment["size"];
                $fileType = $question_attachment["type"];
                $fileError = $question_attachment["error"];
                $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                $allowedTypes = [
                    'image/jpeg', 'image/png', 'image/gif', 'image/heic',
                    'application/pdf',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'application/vnd.ms-excel',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                ];
                $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                $maxFileSize = 25 * 1024 * 1024; // Maximum file size 25 MB

                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

                $keyName = $directoryPathMain . $userid . "_" . time() . '.' . $file_extension;
                //$question_attachment_name = time() . "." . $file_extension;

                $question_attachment = json_encode(array("filepath" => $keyName, "original_name" => $file_name));
            }
            
            $insertValues[] = [
                $institution_id,
                $branch_id,
                $class_id,
                $section_id,
                $test_id,
                $test_questions_id,
                $question_attachment,
                $student_selected_answer,
                $userid,
                $student_test_attempt_id,
                $remarks,
                $marks_obtained,
                $points,
                $username,
                time(),
                date('Y-m-d'),
                $username,
                $status
            ];
        
$updateQuestionValueQuery = "
    UPDATE test_attempt 
    SET question_counter = ? 
    WHERE test_id = ? AND student_id = ? AND id = ?
";
$updateStmt = $conn_rjllearning_specific->prepare($updateQuestionValueQuery);
$updateStmt->execute([$answer['test_questions_id'], $test_id, $userid, $student_test_attempt_id]);

        }
         }
    
    
// print_r($insertValues);
// die();
    // Batch insert test submissions into database
    if (!empty($insertValues)) {
        $inserttestQuery = "INSERT INTO test_submission(institution_id,
        branch_id,
        class_id,
        section_id,
        test_id,
        test_questions_id,
        question_attachment,
        question_text_answer,
        student_id,
        student_test_attempt_id,
        remarks,marks_obtained,
        points,
        added_by,
        time_created,
        date_created,
        last_modified_by, status) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $inserttestStmt = $conn_rjllearning_specific->prepare($inserttestQuery);

        // Execute batch insertion
        foreach ($insertValues as $insertData) {
            $inserttestStmt->execute($insertData);
        }

        // Return success response
        $test_submission_id = $conn_rjllearning_specific->lastInsertId();
        successreturn(['id' => $test_submission_id, 'successmsg' => "Successfully added test submissions."]);
    } else {
        errorreturn("No valid answer format found.");
    }
}
