<?php
ini_set('display_errors', 1);

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

// Validation 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';
// DB access function
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);
// print_r($postdata);die();
checkIfNoPhpContentsReceive();

if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
!isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
!isset($postdata['test_id']) or !checkIfIssetAndNotEmpty($postdata['test_id']) or 
!isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_id']) or
!isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or 
!isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
!isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])) {
    
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is in decoded 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;

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

function getSpecificTest($conn_rjllearning_specific, $test_id, $institution_id, $branch_id, $student_id) {
    
    // Initialize the array to return
    $array_return = [];
    // Prepare an array to hold question details
    $question_array = array();
    $marks_obtained =  0;
    $total_points =  0 ;


    try {
        // Fetch quiz submissions for the specific quiz and student
        $sqlSubmissions = "SELECT * FROM test_submission WHERE test_id = ? AND student_id = ? AND institution_id = ? AND branch_id = ?";
        $stmtSubmissions = $conn_rjllearning_specific->prepare($sqlSubmissions);
        $stmtSubmissions->execute([$test_id, $student_id, $institution_id, $branch_id]);
        $resultSubmissions = $stmtSubmissions->fetchAll(PDO::FETCH_ASSOC);
        // print_r(($resultSubmissions));die();
        // Check if submissions exist for this quiz and student
        if (count($resultSubmissions) < 1) {
            errorreturn("No submissions found for this test and student.");
        }

        // Fetch quiz details
        $sqlquiz = "SELECT name, description, max_points FROM test WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmtquiz = $conn_rjllearning_specific->prepare($sqlquiz);
        $stmtquiz->execute([$test_id, $institution_id, $branch_id]);
        $resultquiz = $stmtquiz->fetch(PDO::FETCH_ASSOC);

        // Check if quiz exists
        if (!$resultquiz) {
            errorreturn("Test not found.");
        }

        // Extract quiz details
        $quiz_name = $resultquiz['name'];
        $quiz_description = $resultquiz['description'];
        $max_points = $resultquiz['max_points'];

        // Fetch student details
        $sqlStudent = "SELECT * FROM students WHERE user_id = ? AND institution_id = ? AND branch_id = ?";
        $stmtStudent = $conn_rjllearning_specific->prepare($sqlStudent);
        $stmtStudent->execute([$student_id, $institution_id, $branch_id]);
        $resultStudent = $stmtStudent->fetch(PDO::FETCH_ASSOC);

        // Check if student exists
        if (!$resultStudent) {
            errorreturn("Student not found.");
        }

        // Extract student data
        $student_data = [
            'student_id' => $resultStudent['user_id'],
            'name' => $resultStudent['name'],
            'fathername' => $resultStudent['fathername']
        ];

        // Fetch all questions for the quiz
        //$sqlQuestions = "SELECT * FROM test_questions WHERE test_id = ? AND institution_id = ? AND branch_id = ?";
        $sqlQuestions = "SELECT 
             qbi.id,
            tq.test_id,
            tq.institution_id,
            tq.branch_id,
            tq.id,
            qbi.class_id,
            qbi.section_id,
            qbi.subject_id,
            qbi.question_no,
            qbi.question_type,
            qbi.level,
            qbi.question_marks,
            qbi.topic_name,
            qbi.author,
            qbi.question_description,
            qbi.options,
            qbi.answer,
            qbi.question_attachment,
            qbi.status
        FROM 
            test_questions tq
        JOIN 
            question_bank_info qbi
        ON 
            tq.question_bank_id = qbi.id
        
        WHERE 
            tq.test_id = ? AND tq.institution_id = ?";
        $stmtQuestions = $conn_rjllearning_specific->prepare($sqlQuestions);
        $stmtQuestions->execute([$test_id, $institution_id]);
        $resultQuestions = $stmtQuestions->fetchAll();
        // print_r($resultQuestions);
        // Iterate through each question
        foreach ($resultQuestions as $tempQuestion) {
            // Initialize question attachments array
            $question_attachments = [];
           
            // Handle question attachments if present
            if ($tempQuestion['question_attachment'] != null) {
                $attachments = json_decode($tempQuestion['question_attachment'], true);

                // Process each attachment
                if (is_array($attachments)) {
                    foreach ($attachments as $attachment) {
                        $data_attachment = json_decode($attachment, true);
                        if ($data_attachment) {
                            $filePath = $data_attachment['filepath'];
                            $originalName = $data_attachment['original_name'];
                            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                            $question_attachments[] = [
                                "filepath" => $aws_attachment,
                                "original_name" => $originalName
                            ];
                        }
                    }
                } else {
                    // Handle single attachment
                    $data_attachment = json_decode($attachments, true);
                    if ($data_attachment) {
                        $filePath = $data_attachment['filepath'];
                        $originalName = $data_attachment['original_name'];
                        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                        $question_attachments[] = [
                            "filepath" => $aws_attachment,
                            "original_name" => $originalName
                        ];
                    }
                }
            }

            // Initialize answer question attachments array
            $answer_question_attachments = null;
              // Initialize marks for this question
            $question_marks_obtained = 0;
            $question_total_points = 0;
                // print_r($resultSubmissions);
            // Check if answer and attachments exist for this question
            // Determine if the question was answered and its correctness status
            $submitted_answer = 'Not Answered';
            foreach ($resultSubmissions as $answer) {
            if ($answer['test_questions_id'] == $tempQuestion['id']) {
                $submitted_answer = $answer['question_text_answer'];
                $question_marks_obtained = $answer['marks_obtained'];
                $question_total_points = $answer['points'];

                // Handle answer question attachments
                if ($answer['question_attachment'] != null && !is_array($answer['question_attachment'])) {
                    $data_attachment = json_decode($answer['question_attachment'], true);

                    // Check if JSON decoding was successful and required keys exist
                    if (isset($data_attachment['filepath']) && isset($data_attachment['original_name'])) {
                        $filePath = $data_attachment['filepath'];
                        $originalName = $data_attachment['original_name'];

                        // Assuming displayFileFromS3 handles errors internally
                        $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);

                        $answer_question_attachments = [
                            "filepath" => $aws_attachment,
                            "original_name" => $originalName
                        ];
                    }
                }
                break;
            }
        }

        // Update marks
        $marks_obtained += $question_marks_obtained;
        
        $status = ($submitted_answer == $tempQuestion['answer']) ? 'Correct' : 'Incorrect';
        // Populate question details into question array
        
         $options = !empty($tempQuestion['options']) ? json_decode($tempQuestion['options'], true) : null;
         $question_array[] = array(
                "test_questions_id" => $tempQuestion['id'],
                "test_submission_id" => $answer['id'],
                'question_no' => $tempQuestion['question_no'],
                'question_description' => $tempQuestion['question_description'],
                'options' => $options,
                'correct_answer' => $tempQuestion['answer'],
                'submitted_answer' => $submitted_answer,
                'answer_question_attachment' => $answer_question_attachments,
                'marks_obtained' => $question_marks_obtained,
                'question_attachment' => $question_attachments,
                'status' => $status
            );   
        }
      
         
        // print_r($question_array);die();
        // Calculate points and fetch additional info
        
        $remarks = isset($resultSubmissions[0]['remarks']) ? $resultSubmissions[0]['remarks'] : null;
         $points = isset($resultSubmissions[0]['points']) ? $resultSubmissions[0]['points'] : 0;
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $resultStudent['class_id']);
        $section_info = getSection($conn_rjllearning_specific, $institution_id, $resultStudent['section_id']);
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id);
        // $points_ratio = $points . '/' . $max_points;
         $points_ratio = $marks_obtained ;
        // Construct the final return array
        $array_return = [
            "institution_id" => $institution_id,
            'branch_info' => $branch_info,
            'class_info' => $class_info,
            'section_info' => $section_info,
            "students" => $student_data,
            "test_name" => $quiz_name,
            "test_description" => $quiz_description,
            "max_points" => $max_points,
            "marks_obtained" => $points_ratio,
            "points"=>$points,
            "remarks" => $remarks,
            "quiz_questions" => $question_array
        ];

    } catch (PDOException $e) {
        // Handle database errors here
        errorreturn("Database error: " . $e->getMessage());
    }
    
    

    return $array_return;
}



if ($postdata['function_type'] == "fetch_specific_submission_test") {
    $institution_id = trim($postdata['institution_id']);
    $branch_id = trim($postdata['branch_id']);
    $test_id = trim($postdata['test_id']);
    $student_id = trim($postdata['student_id']);

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $success['data'] = getSpecificTest($conn_rjllearning_specific, $test_id, $institution_id, $branch_id,$student_id);
    successreturn($success);
}
?>
