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

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


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

// assignment_questions_id


if (

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

$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

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



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



function getSpecificAssignment($conn_rjllearning_specific, $assignment_id, $institution_id,$check_academic_confirmation, $branch_id, $student_id) {
    // Initialize the array to return
    $array_return = [];

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

        // Fetch assignment details
        $sqlAssignment = "SELECT name, description, max_points FROM assignments WHERE id = ? AND institution_id = ? AND branch_id = ? and academic_id =?";
        $stmtAssignment = $conn_rjllearning_specific->prepare($sqlAssignment);
        $stmtAssignment->execute([$assignment_id, $institution_id, $branch_id,$check_academic_confirmation]);
        $resultAssignment = $stmtAssignment->fetch(PDO::FETCH_ASSOC);

        // Check if assignment exists
        if (!$resultAssignment) {
            errorreturn("Assignment not found.");
        }

        // Extract assignment details
        $assignment_name = $resultAssignment['name'];
        $assignment_description = $resultAssignment['description'];
        $max_points = $resultAssignment['max_points'];

        // Fetch student details
        $sqlStudent = "SELECT * FROM students WHERE user_id = ? AND institution_id = ? AND branch_id = ? and academic_id=?";
        $stmtStudent = $conn_rjllearning_specific->prepare($sqlStudent);
        $stmtStudent->execute([$student_id, $institution_id, $branch_id,$check_academic_confirmation]);
        $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 assignment
        $sqlQuestions = "SELECT * FROM assignment_questions WHERE assignment_id = ? AND institution_id = ? AND branch_id = ?";
        $stmtQuestions = $conn_rjllearning_specific->prepare($sqlQuestions);
        $stmtQuestions->execute([$assignment_id, $institution_id, $branch_id]);
        $resultQuestions = $stmtQuestions->fetchAll(PDO::FETCH_ASSOC);

        // Prepare an array to hold question details
        $question_array = [];

        // 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;
                // 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['assignment_questions_id'] == $tempQuestion['id'] && $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
                        ];
                    }
                }
            

            
          
                if ($answer['assignment_questions_id'] == $tempQuestion['id']) {
                    $submitted_answer = $answer['question_text_answer'];
                    //break;
                }
            

            $status = ($submitted_answer == $tempQuestion['answer']) ? 'Pending' : 'Submitted';

            // Populate question details into question array
              
         $question_array[] = [
               
                "assignment_questions_id" => $tempQuestion['id'],
                'question_no' => $tempQuestion['question_no'],
                'question_text' => $tempQuestion['question_text'],
                'options' => json_decode($tempQuestion['options'], true),
                'correct_answer' => $tempQuestion['answer'],
                'submitted_answer' => $submitted_answer,
                'answer_question_attachment' => $answer_question_attachments,
                'question_attachment' => $question_attachments,
                'status' => $status
            ];
          
        }
        }
      
        // print_r($question_array);die();
        // Calculate points and fetch additional info
        $points = isset($resultSubmissions[0]['points']) ? $resultSubmissions[0]['points'] : 0;
        $remarks = isset($resultSubmissions[0]['remarks']) ? $resultSubmissions[0]['remarks'] : null;
        $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 = $points ;
        // 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,
            "assignment_name" => $assignment_name,
            "assignment_description" => $assignment_description,
            "max_points" => $max_points,
            "points" => $points_ratio,
            "remarks" => $remarks,
            "assignment_questions" => $question_array
        ];

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

    return $array_return;
}



if ($postdata['function_type'] == "fetch_students_api_assignment_submission") {

    $assignment_id = trim($postdata['assignment_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'] = getSpecificAssignment($conn_rjllearning_specific, $assignment_id, $institution_id,$check_academic_confirmation, $branch_id,$student_id);
    successreturn($success);
}
?>
