<?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';
//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 = $_POST;




// Validate required fields
$required_fields = [ 'assignment_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;


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

$assignment_id = trim($postdata['assignment_id']);
$remarks = (isset($postdata['remarks']) && !empty($postdata['remarks'])) ? trim($postdata['remarks']) : null;
$points = (isset($postdata['points']) && !empty($postdata['points'])) ? trim($postdata['points']) : null;
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

// Check if assignment exists
// $joinQuery = "
//     SELECT a.id AS assignment_id, a.max_points,
//           q.id AS question_id, q.question_type, q.question_text, q.answer, q.options ,q.question_marks
//     FROM assignments AS a
//     JOIN assignment_questions AS q ON a.id = q.assignment_id
//     WHERE a.id = ? 
//       AND q.id = ?
//       AND a.institution_id = ?
//       AND a.branch_id = ?
// ";

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

$joinQuery = "
    SELECT a.id AS assignment_id, a.max_points,
           q.id AS question_id, q.question_type, q.question_text, q.answer, q.options ,q.question_marks
    FROM assignments AS a
    JOIN assignment_questions AS q ON a.id = q.assignment_id
    WHERE a.id = ? 
      AND a.institution_id = ?
      AND a.branch_id = ?
";

$joinStmt = $conn_rjllearning_specific->prepare($joinQuery);
$joinStmt->execute([$assignment_id, $institution_id, $branch_id]);
$result = $joinStmt->fetch();

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


$assignmentQuery = "
    SELECT 
        max_points, 
        publish_date, 
        last_date, 
        can_submit_after_last_date, 
        publish_time,
        NOW() AS current_datetime
    FROM assignments
    WHERE id = ? 
      AND institution_id = ?
      AND branch_id = ?
";
$assignmentStmt = $conn_rjllearning_specific->prepare($assignmentQuery);
$assignmentStmt->execute([$assignment_id, $institution_id, $branch_id]);
$assignmentDetails = $assignmentStmt->fetch(PDO::FETCH_ASSOC);

if (!$assignmentDetails) {
    errorreturn("Assignment details not found.");
}

$max_points = $assignmentDetails['max_points'];
$publish_date = $assignmentDetails['publish_date'];
$last_date = $assignmentDetails['last_date'];
$can_submit_after_last_date = $assignmentDetails['can_submit_after_last_date'];

$publish_time = $assignmentDetails['publish_time'];
$current_datetime = $assignmentDetails['current_datetime'];

// Check if current date and time is within allowed submission window
if ($current_datetime < $publish_date) {
    errorreturn("Assignment is not yet published.");
} elseif ($current_datetime > $last_date && !$can_submit_after_last_date) {
    errorreturn("Assignment 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.");
//     }
// }

// $question_attachment = isset($question['question_attachment']) ? $question['question_attachment'] : null;


// Handle file attachments if present


// Function type: create_assignment_submission
if ($postdata['function_type'] == 'create_assignment_submission') {
    $assignmentExistenceQuery = "SELECT id FROM assignment_submission WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND assignment_id = ? AND student_id=?";
    $assignmentExistenceStmt = $conn_rjllearning_specific->prepare($assignmentExistenceQuery);
    $assignmentExistenceStmt->execute([$institution_id, $branch_id, $class_id, $section_id, $assignment_id, $userid]);
    $existing_assignments = $assignmentExistenceStmt->fetchAll();

    if (count($existing_assignments) >= 1) {
        errorreturn("Assignment with the same name already exists.");
    }

    // Fetch all questions for the assignment
    $sqlAnswers = "SELECT id, answer, question_marks, question_type, options 
                   FROM assignment_questions 
                   WHERE assignment_id = ? AND institution_id = ? AND branch_id = ?";
    $stmtAnswers = $conn_rjllearning_specific->prepare($sqlAnswers);
    $stmtAnswers->execute([$assignment_id, $institution_id, $branch_id]);
    $all_questions = $stmtAnswers->fetchAll(PDO::FETCH_ASSOC);

    // **Check if any question does not have an answer**
    $skip_auto_checking = false;
    foreach ($all_questions as $question) {
        if ($question['answer'] === null || trim($question['answer']) === '') {
            $skip_auto_checking = true; // Auto-checking should be skipped
            break;
        }
    }

    if (isset($postdata['question_text_answer']) && !empty($postdata['question_text_answer'])) {
        $question_text_answer = is_array($postdata['question_text_answer']) ? $postdata['question_text_answer'] : json_decode($postdata['question_text_answer'], true);

        if (!is_array($question_text_answer)) {
            errorreturn("Invalid JSON format for 'question_text_answer'.");
        }

        $marks_obtained = 0;
        $insertValues = [];

        foreach ($question_text_answer as $index => $answer) {
            $assignment_questions_id = trim($answer['assignment_questions_id']);
            $student_selected_answer = trim($answer['answer']);
            
            // Find the question's correct answer from the fetched list
            $questionData = array_filter($all_questions, function ($q) use ($assignment_questions_id) {
                return $q['id'] == $assignment_questions_id;
            });

            if (empty($questionData)) {
                errorreturn("Assignment question with ID $assignment_questions_id does not exist.");
            }

            $questionData = reset($questionData);
            $correct_answer = trim($questionData['answer']);
            $question_marks = $questionData['question_marks'];
            $question_type = $questionData['question_type'];

            // **Skip auto-checking if required**
            if (!$skip_auto_checking) {
                // MCQ auto-checking logic
                if ($question_type === 'mcq') {
                    $options = json_decode($questionData['options'], true);
                    if (empty($options)) {
                        errorreturn("MCQ question must have options.");
                    }
                    $marks_obtained += ($student_selected_answer == $correct_answer) ? $question_marks : 0;
                }
            }

            // File attachment handling
            $file_key = 'file_' . $assignment_questions_id;
            if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] == UPLOAD_ERR_OK) {
                $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'],
                ];

                // File upload logic
                $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/question_attachment/" . date('Y') . "/" . date('m') . "/";
                $file_name = $question_attachment['name'];
                $fileTmpName = $question_attachment["tmp_name"];
                $fileSize = $question_attachment["size"];
                $fileType = $question_attachment["type"];
                $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;

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

                $uniqueHash = bin2hex(random_bytes(8));
                $keyName = $directoryPathMain . $userid . "_" . time() . "_" . $uniqueHash . '.' . $file_extension;

                awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, ['tmp_name' => $fileTmpName], $keyName, false, 0);
                $question_attachment = json_encode(["filepath" => $keyName, "original_name" => $file_name]);
            } else {
                $question_attachment = null;
            }

            // Prepare for batch insert
            $insertValues[] = [
                $institution_id,
                $branch_id,
                $academic_id,
                $class_id,
                $section_id,
                $assignment_id,
                $assignment_questions_id,
                $question_attachment,
                $student_selected_answer,
                $userid,
                $remarks,
                ($skip_auto_checking ? null : $marks_obtained), // Store marks only if auto-checking is done
                $points,
                $username,
                time(),
                date('Y-m-d'),
                $username,
                1
            ];
        }
    }

    // **Batch Insert: Save all answers even if auto-checking is skipped**
    if (!empty($insertValues)) {
        $insertAssignmentQuery = "INSERT INTO assignment_submission (institution_id, branch_id, academic_id, class_id, section_id, assignment_id, assignment_questions_id, question_attachment, question_text_answer, student_id, remarks, marks_obtained, points, added_by, time_created, date_created, last_modified_by, status) VALUES (?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insertAssignmentStmt = $conn_rjllearning_specific->prepare($insertAssignmentQuery);

        foreach ($insertValues as $insertData) {
            $insertAssignmentStmt->execute($insertData);
        }

        $assignment_submission_id = $conn_rjllearning_specific->lastInsertId();
        successreturn(['id' => $assignment_submission_id, 'successmsg' => "Successfully added assignment submissions."]);
    }
}
 else {
        errorreturn("No valid answer format found.");
    }







function checkFileValidationFlutter($fileSize, $fileType, $file_extension, $allowed_file_size, $allowed_file_types, $allowed_file_extensions, $errormsg_for_type = null)
{

    // if (!in_array($fileType, $allowed_file_types) ) {
    //     if ($errormsg_for_type == null) {
    //         errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    //     } else {
    //         errorreturn($errormsg_for_type);
    //     }
    // }
    if (!in_array($fileType, $allowed_file_types) && $fileType != 'application/octet-stream') {
    errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    } else {
    // Handle the case where the MIME type is application/octet-stream
    if ($fileType == 'application/octet-stream') {
        if (!in_array($file_extension, $allowed_file_extensions)) {
            errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
        }
    }
    }

    if (!in_array($file_extension, $allowed_file_extensions)) {
        errorreturn("Only " . implode(", ", $allowed_file_extensions) . " are allowed to be uploaded.");
    }

    // provide max file size in MB.
    if ($fileSize > ($allowed_file_size * 1024 * 1024)) {
        errorreturn("Please upload a valid image  with a size less than $allowed_file_size MB");
}
}
