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

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

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

checkIfNoPhpContentsReceive();

// Check required fields
if (

    !isset($postdata['assignment_id']) || !checkIfIssetAndNotEmpty($postdata['assignment_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$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;
$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,
    $institution_id,
    $branch_id,
    $assignment_id,
    $check_academic_confirmation,
    $assignment_questions_id,
    $class_id,
    $section_id,
    $subject_id,
    $userid,
    $from_date,
    $to_date
) {
  
    $questions_data = array();
    $total_obtained_marks = 0;
    try {
        $sql_assignment = "SELECT * FROM assignments WHERE id = ? AND institution_id = ? and academic_id=?";
        $array_params_assignment = [$assignment_id, $institution_id,$check_academic_confirmation];

        $stmt_assignment = $conn_rjllearning_specific->prepare($sql_assignment);
        $stmt_assignment->execute($array_params_assignment);
        $assignment = $stmt_assignment->fetch(PDO::FETCH_ASSOC);

        $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $assignment['subject_id']);

        // Prepare and execute SQL query to fetch assignment submissions
        $sql = "SELECT * FROM assignment_submission WHERE assignment_id = ? AND institution_id = ? and academic_id=? AND student_id=?";
        $array_params = [$assignment_id, $institution_id,$check_academic_confirmation,$userid];
       
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
        $submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Prepare and execute SQL query to fetch assignment questions
        $sql_questions = "SELECT * FROM assignment_questions WHERE assignment_id = ? AND institution_id = ?";
        $array_params_questions = [$assignment_id, $institution_id];

        $stmt_questions = $conn_rjllearning_specific->prepare($sql_questions);
        $stmt_questions->execute($array_params_questions);
        $all_questions = $stmt_questions->fetchAll(PDO::FETCH_ASSOC);

        // Group questions by assignment_questions_id
        $questions_by_id = [];
        foreach ($all_questions as $question) {
            $final_array_attachment = null;

            if (isset($question['question_attachment']) && $question['question_attachment'] !== null && !is_array($question['question_attachment'])) {
                $data_attachment = json_decode($question['question_attachment'], true);
                $filePath = $data_attachment['filepath'];
                $originalName = $data_attachment['original_name'];
                $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                $final_array_attachment = array("filepath" => $aws_attachment, "original_name" => $originalName);
            }

            $questions_by_id[$question['id']][] = [
                "assignment_questions_id" => $question['id'],
                "institution_id" => $question['institution_id'],
                "branch_id" => $question['branch_id'],
                "question_no" => $question['question_no'],
                "question_type" => $question['question_type'],
                "question_text" => $question['question_text'],
                "options" => isset($question['options']) ? json_decode($question['options'], true) : [],
                "answer" => $question['answer'],
                "attachment" => $final_array_attachment,
                "question_marks" => (int)$question['question_marks'],
                "attempted" => false, // Initially, mark as unattempted
                "marks_obtained" => 0 // Initialize marks_obtained
            ];
        }

        // Initialize response array
        $response = [
            "common_option" => [
                "test_id" => $assignment['id'],
                "test_name" => $assignment['name'], // Fetch the assignment name
                "total_marks" => $assignment['max_points'],
                "subject" => $subject_info,
                "total_obtained_marks" => 0 // Initialize this to 0
            ],
            "questions" => [] // Initialize the questions array
        ];

        // Initialize the assignment_checked variable
        $assignment_status = "not_attempted"; // Default status;
        $total_obtained_marks = 0; // Ensure this is defined
        $total_marks = 0; // Initialize total marks

        // Loop through the submissions and match them with the questions
        foreach ($submissions as $submission) {
            // Handle attachment
            $final_array_attachment = null;
            if (isset($submission['question_attachment']) && !empty($submission['question_attachment'])) {
                $data_attachment = json_decode($submission['question_attachment'], true);
                if (json_last_error() === JSON_ERROR_NONE) { // Check if JSON decode was successful
                    $filePath = $data_attachment['filepath'];
                    $originalName = $data_attachment['original_name'];
                    $aws_attachment = displayFileFromS3(
                        $GLOBALS['s3_learning_bucket'],
                        $GLOBALS['learning_bucketName'],
                        $filePath
                    );
                    $final_array_attachment = [
                        "filepath" => $aws_attachment,
                        "original_name" => $originalName
                    ];
                }
            }

            // Update total max points and obtained marks
            if (isset($submission['marks_obtained'])) {
                $total_marks += (int)$submission['marks_obtained'];
                $total_obtained_marks = $total_marks + $submission['points'];
                if ($submission['status'] == 1) {
                    $assignment_status = "not checked'"; // If marks are obtained, it's attempted
                }
                
                if (isset($submission['status']) && $submission['status'] == 2) {
                    $assignment_status = "checked"; // If marked as checked, update status
                }
            }

            // Group questions for response
            foreach ($questions_by_id as $question_id => &$questions) {
                foreach ($questions as &$question) {
                    if ($question_id == $submission['assignment_questions_id']) {
                        $question['question_text_answer'] = isset($submission['question_text_answer']) ? $submission['question_text_answer'] : null;
                        $question['question_attachment'] = $final_array_attachment;
                        $question['attempted'] = true; // Mark as attempted
                        $question['marks_obtained'] = isset($submission['marks_obtained']) ? (int)$submission['marks_obtained'] : 0; // Set marks obtained
                        $response['questions'][] = $question;
                    }
                }
            }
        }

        // Loop through all questions and add unattempted ones
        foreach ($questions_by_id as $questions) {
            foreach ($questions as $question) {
                // Only add unattempted questions that are not already added
                if (!$question['attempted']) {
                    $question['attempted'] = false; // Ensure it's marked as unattempted
                    $question['marks_obtained'] = 0; // Ensure marks_obtained is 0 for unattempted questions
                    $response['questions'][] = $question;
                }
            }
        }

        // Set obtained marks and assignment status in response
        $response['common_option']['total_obtained_marks'] = $total_obtained_marks;
        $response['common_option']['assignment_status'] = $assignment_status ;

    } catch (Exception $e) {
        errorreturn("An error occurred: " . $e->getMessage());
    }

    // Format final response
    $response['status'] = 1;

    return $response;
}






// Main logic to fetch specific assignment submissions
if ($postdata['function_type'] == "fetch_specific_students_api_assignment_submission") {
 
    $assignment_id = trim($postdata['assignment_id']);

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


    $subject_id = isset($postdata['subject_id']) ? trim($postdata['subject_id']) : 'all';
    $assignment_questions_id = isset($postdata['assignment_questions_id']) ? trim($postdata['assignment_questions_id']) : null;
    $from_date = isset($postdata['from_date']) ? trim($postdata['from_date']) : null;
    $to_date = isset($postdata['to_date']) ? trim($postdata['to_date']) : null;
    // $limit = isset($postdata['limit']) ? $postdata['limit'] : 'all'; // Ensure 'limit' is set in $postdata
    // $page = isset($postdata['page']) && is_numeric($postdata['page']) ? (int)$postdata['page'] : 1;
 

    // Fetch assignment submissions using defined function
    $success['data'] = getSpecificAssignment($conn_rjllearning_specific, $institution_id, $branch_id, $assignment_id,$check_academic_confirmation, $assignment_questions_id, $class_id, $section_id, $subject_id,$userid, $from_date, $to_date);

    // Return success response based on 'limit' condition
    successreturn($success);
}
?>
