<?php

// Set up error reporting
ini_set('display_errors', 1);

// Include necessary files
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_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'lib/task_schedule/task_scheduler_functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

// Check if JSON is valid
// $postdata = json_decode(file_get_contents("php://input"), true);
// checkIfNoPhpContentsReceive();

$postdata = $_POST;

$output = "Post Data:\n" . print_r($postdata, true);
$output .= "\nUploaded Files:\n" . print_r(json_encode($_FILES), true);

// Define the file path (same directory as the script)
$filePath = __DIR__ . "/output.txt";

// Write the output to the file (overwrite existing or create new)
file_put_contents($filePath, $output);



// Stop execution

$required_fields = ['class_id', 'section_id', 'name', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}
//  $postdata = json_decode(file_get_contents('php://input'), true); // Assuming the POST data is sent as JSON

// $required_fields = ['institution_id', 'branch_id', 'class_id', 'section_id', 'name', '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']);

// Authenticate user and get user details
$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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
// Include necessary function files
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

// Validate basic parameters
// $function_type = trim($postdata['function_type']);
$class_id = trim($postdata['class_id']);
// $subject_id = isset($postdata['subject_id']) ? trim($postdata['subject_id']) : null; // cannot be null ~~~~~~
$subject_id = trim($postdata['subject_id']);

$section_id = trim($postdata['section_id']);
$name = ucwords(trim($postdata['name']));
$date_created = date('Y-m-d');
$time_created = time();
// $status = trim($postdata['status']) ;
$status = 1;
// $max_points = $postdata['max_points'];
$description = trim($postdata['description']);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}


if (isset($postdata['publish_date']) && isset($postdata['last_date']) && strtotime($postdata['publish_date']) <= strtotime($postdata['last_date'])) {
    $publish_date = date('Y-m-d', strtotime($postdata['publish_date']));
} else {
    $publish_date = date('Y-m-d');
}

if (isset($postdata['last_date']) && isset($postdata['publish_date']) && strtotime($postdata['last_date']) >= strtotime($postdata['publish_date'])) {
    $last_date = date('Y-m-d', strtotime($postdata['last_date']));
} else {
    $last_date = date('Y-m-d');
}

$currenttime = time();

// $publish_time = isset($postdata['publish_time']) ? ($postdata['publish_time']) : false;
$publish_time = (isset($postdata['publish_time']) and !empty($postdata['publish_time'])) ? trim($postdata['publish_time']) : $currenttime;
$last_submission_time = isset($postdata['last_submission_time']) ? ($postdata['last_submission_time']) : false;

// Check if the publish_time and last_submission_time are valid timestamps
if ($publish_time === false || $last_submission_time === false) {
    errorreturn("Invalid date format for publish time or last submission time.");
}

// Ensure publish_time is before last_submission_time
$publish_datetime = $publish_date . ' ' . $publish_time;
$last_submission_datetime = $last_date . ' ' . $last_submission_time;

// Convert combined datetime strings to timestamps
$publish_timestamp = strtotime($publish_datetime);
$last_submission_timestamp = strtotime($last_submission_datetime);

// Check if the combined publish datetime is before the last submission datetime
if ($publish_timestamp >= $last_submission_timestamp) {
    errorreturn("Invalid Date Range: Publish time must be before last submission time.");
}
$today_date = date('Y-m-d');
// if ($publish_time === false || $last_submission_time === false) {
//     errorreturn("Invalid date format for publish time or last submission time.");
// }
// $last_submission_time =  isset($postdata['last_submission_time']) && isset($postdata['publish_time']) && strtotime($postdata['last_submission_time']) > strtotime($postdata['publish_time']) ? strtotime($postdata['last_submission_time']) : time();

if (isset($postdata['can_submit_after_last_date'])) {
    $can_submit_after_last_date = intval($postdata['can_submit_after_last_date']);
} else {
    $can_submit_after_last_date = 0;
}

if ($status !== null && !in_array($status, [0, 1, 2])) {
    errorreturn('Invalid status value.');
}

if (!CheckStartDate($publish_date)) {
    //eg House Name, Street Name
    errorreturn('Invalid Date Format');
}

if (!CheckStartDate($last_date)) {
    //eg House Name, Street Name
    errorreturn('Invalid Date Format');
}

if ($publish_date !== null) {
    if ($publish_date < $today_date) {
        // Publish date is less than today's date, show an error
        errorreturn("Publish date cannot be less than today's date.");
    }

    if ($last_date !== null && $publish_date > $last_date) {
        // Publish date is after termination date
        errorreturn('Publish date cannot be after termination date.');
    }
}

if ($publish_time !== null) {
    if ($publish_date !== null) {
        $publish_datetime = $publish_date . ' ' . $publish_time;
    } else {
        $publish_datetime = $publish_time;
    }

    if ($last_date !== null) {
        if ($last_submission_time !== null) {
            $termination_datetime = $last_date . ' ' . $last_submission_time;
        } else {
            $termination_datetime = $last_date . ' 23:59:59'; // Assume end of day if no time is provided
        }

        if ($publish_datetime > $termination_datetime) {
            // Publish datetime is after termination datetime
            errorreturn('Publish datetime cannot be after termination datetime.');
        }
    }
}

if (!CheckValidateTime($publish_time)) {
    errorreturn('Invalid End time');
}

if (!CheckValidateTime($last_submission_time)) {
    errorreturn('Invalid End time');
}

// if ($publish_time >= $last_submission_time) {
//     errorreturn('Invalid time Range');
// }

// $check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
// if ($check_branch_class == false) {
//     errorreturn("Access denied");
// }

// $question_type = $postdata['question_type'];
// // print_r($question_type);

// // Validate and retrieve question_type
// $question_type = isset($postdata['question_type']) ? $postdata['question_type'] : errorreturn("Missing question_type field.");

// // Check if question_type is valid
// if ($question_type !== 'mcq' && $question_type !== 'subjective') {
//     errorreturn("Invalid question_type: $question_type. Question type must be 'mcq' or 'subjective'.");
// }

// // Now, print the question_type
// print_r($question_type);



// if ($question_type !== 'mcq' && $question_type !== 'subjective') {
//         errorreturn("Invalid question_type: $question_type. Question type must be 'mcq' or 'subjective'.");
// }

$timestamp = strtotime("$publish_date $publish_time");

// validateBranchClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $support_branch_all = 0, $checkClass = 0, $support_class_all = 0, $checkSection = 1,  $support_section_all = 0);
//  print_r($finalised_question_array);die();
if ($postdata['function_type'] == 'create_assignment') {
    if (!isset($postdata['questions']) || !is_array($postdata['questions']) || empty($postdata['questions'])) {
        errorreturn("Questions are required.");
    }

    $questions = $postdata['questions'];

    // Validate each question object
    $finalised_question_array = array();
    $max_points = 0;
    // print_r($questions);die();
    foreach ($questions as  $index => $question) {
        $question_text = $question['question_text'];
        $question_marks = isset($question['question_marks']) ? floatval($question['question_marks']) : 0;
        $question_no = $question['question_no'];
        $answer = $question['answer'];

        $required_fields = ['question_text', 'question_no'];

        foreach ($required_fields as $field) {
            if (!isset($question[$field]) || !checkIfIssetAndNotEmpty($question[$field])) {
                errorreturn("All * fields are required: $field");
            }
        }
        $options = NULL;
        if (isset($question['options']) && !empty($question['options']) && is_array($question['options'])) {

            $options = (isset($question['options']) and !empty($question['options'])) ? $question['options'] : null;
        }


        // Check if options count is within the range of 2 to 4
        if ($options !=  null) {
            $optionsCount = count($options);
            if ($optionsCount < 2 || $optionsCount > 4) {
                errorreturn("MCQ questions must have between 2 and 4 options.");
            }
        }

        if (!is_numeric($question_marks) || $question_marks < 0) {
            errorreturn("Invalid question marks: $question_marks. It must be a non-negative number.");
        }

        // $max_points = $postdata['$question_marks'];
        // if (!is_numeric($max_points) || $max_points < 0) {
        //     errorreturn("Invalid max_points: $max_points. It must be a non-negative number.");
        // }
        $max_points += $question_marks;
        // $question_no = $question['question_no'] ?? null;
        if (!isset($question_no) || !is_numeric($question_no)) {
            errorreturn("Question number must be numeric.");
        }
        $answer = $question['answer'] ?? null;
        // Check if question type is provided and validate its value

        $question_type = $question['question_type'] ?? null;
        if (!isset($question_type) || !in_array($question_type, ['mcq', 'subjective'])) {
            errorreturn("Invalid or missing question type. Question type must be 'mcq' or 'subjective'.");
        }
        $options = null; // Initialize options to null for subjective questions
        if ($question_type === 'mcq') {
            // if (!isset($question['options']) || !is_array($question['options']) || empty($question['options'])) {
            //     errorreturn("Options are mandatory for MCQ questions and must be provided as a non-empty array.");
            // }
            // $options = explode(',', $question['options']);
            // print_r($options);
            // Check if the decoding was successful and the result is an array
            if (!is_array($options)) {
                errorreturn("Options must be an array.");
            }
            $options = json_decode($options,true);
            
            // Check if the provided answer is within the options
            if (!isset($answer) || !in_array($answer, $options)) {
                errorreturn("Answer must match one of the options for MCQ questions1.");
            }
        } elseif ($question_type === 'subjective') {
            // For subjective questions, ensure options are not provided
            // if (isset($question['options'])) {
            //     errorreturn("Options should not be provided for subjective questions.");
            // }
        }

        $file_key = 'questions' . $index . '[question_attachment]';

        if (isset($_FILES['questions']['name'][$index]['question_attachment']) && $_FILES['questions']['error'][$index]['question_attachment'] == UPLOAD_ERR_OK) {
            $question_attachment = [
                'name' => $_FILES['questions']['name'][$index]['question_attachment'],
                'type' => $_FILES['questions']['type'][$index]['question_attachment'],
                'tmp_name' => $_FILES['questions']['tmp_name'][$index]['question_attachment'],
                'error' => $_FILES['questions']['error'][$index]['question_attachment'],
                'size' => $_FILES['questions']['size'][$index]['question_attachment'],
            ];
        } else {
            $question_attachment = null;
        }

        // print_r($question_attachment);
        // die();

        if ($question_attachment == null) {
            $question_attachment = null;
        } else {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');

            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/question_attachment/" . $currentYear . "/" . $currentMonth . "/";

            $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($question_attachment['name'], PATHINFO_EXTENSION));
            $size = filesize($fileTmpName);
            // Check if it's a valid image
            $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 image types
            $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }
        // Add validated question details to final array
        $finalised_question_array[] = array(
            'question_type' => $question_type,
            'question_no' =>  $question_no,
            'question_attachment' => $question_attachment,
            'question_marks' => $question_marks,
            'question_text' => $question_text,
            'options' => $options,
            'answer' => $answer,
        );
    }


    // Check if assignment with the same name already exists
    $assignmentExistenceQuery = "SELECT id FROM  assignments WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND (section_id = ? or section_id = ?) AND name = ?";
    $assignmentExistenceStmt = $conn_rjllearning_specific->prepare($assignmentExistenceQuery);
    $assignmentExistenceStmt->execute([$institution_id, $branch_id, $class_id, $section_id, 'all', $name]);
    if (count($assignmentExistenceStmt->fetchAll()) >= 1) {
        errorreturn("Assignment with the same name already exists.");
    }

    try {
        // Insert into assignments table
        $insertAssignmentQuery = "INSERT INTO assignments 
        (institution_id, branch_id,academic_id, class_id, section_id, subject_id, name, description, max_points, publish_date, last_date, can_submit_after_last_date, publish_time, last_submission_time, added_by, last_modified_by, date_created, time_created, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?)";
        $insertAssignmentStmt = $conn_rjllearning_specific->prepare($insertAssignmentQuery);
        $insertAssignmentStmt->execute([
            $institution_id,
            $branch_id,
            $academic_id,
            $class_id,
            $section_id,
            $subject_id,
            $name,
            $description,
            $max_points,
            $publish_date,
            $last_date,
            $can_submit_after_last_date,
            $publish_time,
            $last_submission_time,
            $username,
            $username,
            $date_created,
            $time_created,
            $status
        ]);

        // Get the last inserted assignment ID
        $assignment_id = $conn_rjllearning_specific->lastInsertId();

        // Insert questions into the assignment_questions table
        $insertQuestionQuery = "INSERT INTO assignment_questions 
        (institution_id, branch_id, assignment_id, question_no, question_type, options, answer, question_attachment, question_marks, question_text, added_by, date_created, time_created, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insertQuestionStmt = $conn_rjllearning_specific->prepare($insertQuestionQuery);

        // Insert each question into the database
        foreach ($finalised_question_array as $rows) {
            // Serialize options array to store it as a string
            $options = json_encode($rows['options']);

            // Execute the prepared statement for each question
            $insertQuestionStmt->execute([
                $institution_id,
                $branch_id,
                $assignment_id,
                $rows['question_no'],
                $rows['question_type'],
                $options, // Use serialized options here
                $rows['answer'],
                null,
                $rows['question_marks'],
                $rows['question_text'],
                $username,
                $date_created,
                $time_created,
                $status
            ]);

            $id = $conn_rjllearning_specific->lastInsertId();

            if ($rows['question_attachment'] !=  null) {
                $image_name = "question_attachment_" . $id . "." . $file_extension; // Define the image name dynamically
                $assignment_image_path = $directoryPathMain . $image_name; // Create the full path for the logo
                awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $rows['question_attachment'], $assignment_image_path, $multiple_files_bool = false, $multiple_file_index = 0);
                $final_question_attachment_image = json_encode(array("filepath" => $assignment_image_path, "original_name" => $file_name));
                $sql_logo = "UPDATE assignment_questions SET question_attachment = ? WHERE id= ? and assignment_id = ?";
                $conn_rjllearning_specific->prepare($sql_logo)->execute(array($final_question_attachment_image, $id, $assignment_id));
            }
        }

        // Handle scheduling task based on publish time
        // Task for publish date
        if ($currenttime == strtotime($publish_time)) {
            // Task scheduled for publish date right now
            manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $publish_date, (time() + 120), 1, $process_type = 'create');
        } else {
            // Task scheduled for publish date later
            manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $publish_date, strtotime($timestamp), 1, $process_type = 'create');
        }

        // Task for last date
        // if ($currenttime == strtotime($last_date)) {
        //     // Task scheduled for last date right now
        //     manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $last_date, (time() + 120), 1, $process_type = 'create');
        // } else {
        //     // Task scheduled for last date later
        //     manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $last_date, strtotime($last_date), 1, $process_type = 'create');
        // }


        // Return success response
        successreturn(['id' => $assignment_id, 'successmsg' => "Successfully added assignment."]);
    } catch (Exception $e) {
        // Handle error and return response
        errorreturn("Failed to insert assignment and questions: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == 'alter_assignment') {
    // Check if assignment ID is provided
    if (!isset($postdata['assignment_id'])) {
        errorreturn("Assignment ID not provided.");
    }

    $assignment_id = $postdata['assignment_id'];

    // Check if assignment exists
    // $assignmentExistenceQuery = "SELECT id FROM assignments WHERE institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ? AND id = ?";
    // $assignmentExistenceStmt = $conn_rjllearning_specific->prepare($assignmentExistenceQuery);
    // $assignmentExistenceStmt->execute([$postdata['institution_id'], $postdata['branch_id'], $postdata['class_id'], $postdata['section_id'], $assignment_id]);
    // $result = $assignmentExistenceStmt->fetchAll();
    // print_r($result);diie();
    // // Check if assignment found
    // if (count($result) < 1) {
    //     errorreturn("Assignment not found.");
    // }
    // Update assignment questions
    $max_points =  0;
    $finalised_question_array =  array();
    // print_r($postdata);
    // die();
    foreach ($postdata['questions'] as $index => $question) {
        $question_text = $question['question_text'];
        $question_marks = isset($question['question_marks']) ? floatval($question['question_marks']) : 0;
        $question_no = $question['question_no'];
        //$answer = $question['answer'];
        $answer = (isset($question['answer']) and !empty($question['answer'])) ? $question['answer'] : null;
        $question_type = (isset($question['question_type']) and !empty($question['question_type'])) ? $question['question_type'] : null;
        $required_fields = ['question_text', 'question_no'];
        // Get remove_bool value
        $remove_bool = (isset($question['remove_bool']) && !empty($question['remove_bool'])) ? trim($question['remove_bool']) : 0;

        // Create dynamic key name
        // $remove_dynamic_key = "remove_bool_" . $index;
        $remove_dynamic_key = $index;

        foreach ($required_fields as $field) {
            if (!isset($question[$field]) || !checkIfIssetAndNotEmpty($question[$field])) {
                errorreturn("All * fields are required: $field");
            }
        }

        $options = null;
        if (isset($question['options']) && !empty($question['options']) && is_array($question['options'])) {
            $options = $question['options'];
        }
        
        // Check if options count is within the range of 2 to 4
        if ($options != null) {
            if (!is_array($options)) {
                errorreturn("Options must be an array.");
            }

            $optionsCount = count($options);
            if ($optionsCount < 2 || $optionsCount > 4) {
                errorreturn("MCQ questions must have between 2 and 4 options.");
            }
        
            // Check if the provided answer is within the options
            if (!isset($answer) || !in_array($answer, $options)) {
                errorreturn("Answer must match one of the options for MCQ questions.a");
            }
        }

        if (!is_numeric($question_marks) || $question_marks < 0) {
            errorreturn("Invalid question marks: $question_marks. It must be a non-negative number.");
        }

        $max_points += $question_marks;
        // $question_no = $question['question_no'] ?? null;
        if (!isset($question_no) || !is_numeric($question_no)) {
            errorreturn("Question number must be numeric.");
        }


        if (!isset($question_type) || !in_array($question_type, ['mcq', 'subjective'])) {
            errorreturn("Invalid or missing question type. Question type must be 'mcq' or 'subjective'.");
        }

        
        if ($question_type === 'mcq') {

            // Ensure that options are provided and are a non-empty array
            // if (!isset($question['options']) || !is_array($question['options']) || empty($question['options'])) {
            //     errorreturn("Options are mandatory for MCQ questions and must be provided as a non-empty array.");
            // }
        $options_raw = $question['options'];
        $options = json_decode($options_raw, true);
        
        // If not a valid JSON array, assume comma-separated string
        if (!is_array($options)) {
            $options = array_map('trim', explode(',', $options_raw));
        }
        
        // Final check
        if (!is_array($options)) {
            errorreturn("Options must be an array.");
        }

            // Check if the provided answer is within the options
            if (!isset($answer) || !in_array($answer, $options)) {
                errorreturn("Answer must match one of the options for MCQ questions.");
            }

            // Additional code for handling MCQ questions can go here
        } elseif ($question_type === 'subjective') {
            // For subjective questions, ensure options are not provided
            // if (isset($question['options'])) {
            //     errorreturn("Options should not be provided for subjective questions.");
            // }
        }


        //$question_attachment = json_encode($rows['question_attachment']);
        // Check if question ID is provided
        $assignment_questions_id = (isset($question['assignment_questions_id']) and !empty($question['assignment_questions_id'])) ? $question['assignment_questions_id'] : null;
        if ($assignment_questions_id !=  null) {

            $sqlQuestions = $conn_rjllearning_specific->prepare("SELECT id,question_attachment FROM assignment_questions WHERE id = ? AND assignment_id = ? AND institution_id = ?");
            $sqlQuestions->execute([$assignment_questions_id, $assignment_id, $postdata['institution_id']]);
            $rows = $sqlQuestions->fetchAll();
            // print_r($rows);die();
            if (count($rows) >= 1) {

                $existing_attachment = $rows[0]['question_attachment'];
                if($existing_attachment !=  null){
                    $data_attachment = json_decode($existing_attachment, true);
                    $assignment_image_path = $data_attachment['filepath'];   
                }
            }
        }

        if ($assignment_questions_id === null) {

            // Serialize options array to store it as a string
            $file_key = 'questions' . $index . '[question_attachment]';

            if (isset($_FILES['questions']['name'][$index]['question_attachment']) && $_FILES['questions']['error'][$index]['question_attachment'] == UPLOAD_ERR_OK) {

                $question_attachment = [
                    'name' => $_FILES['questions']['name'][$index]['question_attachment'],
                    'type' => $_FILES['questions']['type'][$index]['question_attachment'],
                    'tmp_name' => $_FILES['questions']['tmp_name'][$index]['question_attachment'],
                    'error' => $_FILES['questions']['error'][$index]['question_attachment'],
                    'size' => $_FILES['questions']['size'][$index]['question_attachment'],
                ];
            } else {
                $question_attachment = null;
            }
            if ($question_attachment == null) {
                $question_attachment = null;
            } else {
                $currentYear = date('Y');
                $currentMonth = date('m');
                $currentDay =  date('d');

                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/question_attachment/" . $currentYear . "/" . $currentMonth . "/";

                $file_name = $question_attachment['name'];
                $fileTmpName = $question_attachment["tmp_name"];
                $fileSize = $question_attachment["size"];
                $fileType = $question_attachment["type"];
                $fileError = $question_attachment["error"];
                $question_attachment_extension = strtolower(pathinfo($question_attachment['name'], PATHINFO_EXTENSION));
                $size = filesize($fileTmpName);
                // Check if it's a valid image
                $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 image types
                $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

                checkFileValidation($fileSize, $fileType, $question_attachment_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
            }
        } else if ($assignment_questions_id !=  null) {

            $file_key = 'questions' . $index . '[question_attachment]';
            //  echo $file_key;
            if (isset($_FILES['questions']['name'][$index]['question_attachment']) && $_FILES['questions']['error'][$index]['question_attachment'] == UPLOAD_ERR_OK) {
                // echo 'here1';
                $question_attachment = [
                    'name' => $_FILES['questions']['name'][$index]['question_attachment'],
                    'type' => $_FILES['questions']['type'][$index]['question_attachment'],
                    'tmp_name' => $_FILES['questions']['tmp_name'][$index]['question_attachment'],
                    'error' => $_FILES['questions']['error'][$index]['question_attachment'],
                    'size' => $_FILES['questions']['size'][$index]['question_attachment'],
                ];
            } else {
                $question_attachment = null;
            }
            // print_r($question_attachment);
            if ($remove_bool == 1 and $question_attachment !=  null) {
                if ($existing_attachment === null) {

                    $currentYear = date('Y');
                    $currentMonth = date('m');
                    $currentDay =  date('d');

                    $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/question_attachment/" . $currentYear . "/" . $currentMonth . "/";
                } else {

                    $directoryPathMain = substr($assignment_image_path, 0, strrpos($assignment_image_path, '/') + 1);
                }
                $file_name = $question_attachment['name'];
                $fileTmpName = $question_attachment["tmp_name"];
                $fileSize = $question_attachment["size"];
                $fileType = $question_attachment["type"];
                $fileError = $question_attachment["error"];
                $attachment_file_extension = strtolower(pathinfo($question_attachment['name'], PATHINFO_EXTENSION));
                $size = filesize($fileTmpName);
                // Check if it's a valid image
                $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 image types
                $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                $maxFileSize = 2; // Maximum file size (2MB)

                checkFileValidation($fileSize, $fileType, $attachment_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
            }
        }

        $finalised_question_array[] = array(
            'question_type' => $question_type,
            'question_no' =>  $question_no,
            'question_attachment' => $question_attachment,
            'question_marks' => $question_marks,
            'question_text' => $question_text,
            'options' =>   $options,
            'answer' => $answer,
            'assignment_questions_id' => isset($assignment_questions_id) ? $assignment_questions_id : null,
            'function' => isset($question['function']) ? $question['function'] : null
        );
    }
    //  print_r($assignment_questions_id);

    // Update assignment in the database
    $updateAssignmentQuery = "UPDATE assignments SET section_id=?,subject_id=?,name = ?, description = ?, max_points = ?, publish_date = ?, last_date = ?, can_submit_after_last_date = ?, publish_time = ?, last_submission_time = ?, added_by = ?, last_modified_by = ?, date_created = ?, time_created = ?, status = ? WHERE id = ? AND institution_id = ?";
    $updateAssignmentStmt = $conn_rjllearning_specific->prepare($updateAssignmentQuery);

    // Bind parameters and execute update
    $updateAssignmentStmt->execute([
        $postdata['section_id'],
        $postdata['subject_id'],
        $postdata['name'],
        $postdata['description'],
        $max_points,
        $postdata['publish_date'],
        $postdata['last_date'],
        $postdata['can_submit_after_last_date'],
        $postdata['publish_time'],
        $postdata['last_submission_time'],
        $username,
        $username,
        $date_created,
        $time_created,
        $status,
        $assignment_id,
        $postdata['institution_id']
    ]);


    if ($currenttime == strtotime($publish_time)) {
        // scheduled right now
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $publish_date, (time() + 120), 1, $process_type = 'alter');
    } else {
        // scheduled for later
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'assignment', $assignment_id, $publish_date, strtotime($publish_time), 1, $process_type = 'alter');
    }

    // print_R($finalised_question_array);die();
    foreach ($finalised_question_array as $tempQuestions) {
        $options = json_encode($tempQuestions['options']);
        if ($tempQuestions['assignment_questions_id']  != null) {

            if (isset($tempQuestions['function']) and $tempQuestions['function'] == 'update') {
                //  echo 'answer';

                //Update existing question
                $updateQuestionQuery = "UPDATE assignment_questions SET question_no = ?, question_type = ?, options = ?, answer = ?,  question_marks = ?, question_text = ? WHERE id = ? AND assignment_id = ? AND  institution_id = ?";
                $updateQuestionStmt = $conn_rjllearning_specific->prepare($updateQuestionQuery);

                $updateQuestionStmt->execute([
                    $tempQuestions['question_no'],
                    $tempQuestions['question_type'],
                    $options,
                    $tempQuestions['answer'],
                    $tempQuestions['question_marks'],
                    $tempQuestions['question_text'],
                    $tempQuestions['assignment_questions_id'],
                    $assignment_id,
                    $institution_id
                ]);

                if ($remove_dynamic_key == $index) {
                    if ($remove_bool == 1 && $existing_attachment != null) {
                        $sql_image = $conn_rjllearning_specific->prepare("SELECT question_attachment FROM  assignment_questions   where id = ? and institution_id = ?");
                        $sql_image->execute(array($assignment_questions_id, $institution_id));
                        $result_image = $sql_image->fetchAll();

                        if (count($result_image) == 1) {

                            $existing_attachment = $result_image[0]['question_attachment'];
                            if($existing_attachment !=  null){
                                $data_attachment = json_decode($existing_attachment, true);
                                $assignment_path = $data_attachment['filepath'];   
                            }
                            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $assignment_path, null, null);
                            $sql = "UPDATE assignment_questions SET question_attachment = ? WHERE id = ? and institution_id= ?";
                            $conn_rjllearning_specific->prepare($sql)->execute(array(null, $tempQuestions['assignment_questions_id'], $institution_id));
                        }
                    }
                }

                if ($tempQuestions['question_attachment'] !=  null) {
                    $image_name = "question_attachment_" . $tempQuestions['assignment_questions_id'] . "." . $attachment_file_extension; // Define the image name dynamically
                    $assignment_image_path = $directoryPathMain . $image_name; // Create the full path for the logo
                    awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $tempQuestions['question_attachment'], $assignment_image_path, $multiple_files_bool = false, $multiple_file_index = 0);
                    $final_question_attachment_image = json_encode(array("filepath" => $assignment_image_path, "original_name" => $file_name));
                    $sql_logo = "UPDATE assignment_questions SET question_attachment = ? WHERE id= ? and assignment_id = ?";
                    $conn_rjllearning_specific->prepare($sql_logo)->execute(array($final_question_attachment_image, $tempQuestions['assignment_questions_id'], $assignment_id));
                }
            } else if (isset($tempQuestions['function']) and $tempQuestions['function'] == 'delete') {
                // echo 'delete';die();
                $sql = "DELETE FROM assignment_questions WHERE id=? and assignment_id = ?  and institution_id =?  ";
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute(array($tempQuestions['assignment_questions_id'], $assignment_id, $institution_id));
                $act_group = $stmt->rowCount();

                if ($act_group >= 1) {
                    //  return "Delete Ledger Addresses  Successfully";
                } else {
                    errorreturn("Unable to delete assignment questions because of the presence of ....");
                }
            }
        } else if ($tempQuestions['assignment_questions_id']  == null) {
        
            
            //   if ($data['function'] != "delete") {
            // Insert new question if it doesn't exist
            $insertQuestionQuery = "INSERT INTO assignment_questions (institution_id, branch_id, assignment_id, question_no, question_type, options, answer, question_attachment, question_marks, question_text, added_by, date_created, time_created, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $insertQuestionStmt = $conn_rjllearning_specific->prepare($insertQuestionQuery);
            // Execute the prepared statement
            $insertQuestionStmt->execute([
                $institution_id,
                $branch_id,
                $assignment_id,
                $tempQuestions['question_no'],
                $tempQuestions['question_type'],
                $options, // Use serialized options here
                $tempQuestions['answer'],
                null,
                $tempQuestions['question_marks'],
                $tempQuestions['question_text'],
                $username,
                $date_created,
                $time_created,
                $status
            ]);

            $id = $conn_rjllearning_specific->lastInsertId();
            
            if ($tempQuestions['question_attachment'] !=  null) {
                $image_name = "question_attachment_" . $id . "." . $question_attachment_extension; // Define the image name dynamically
                $assignment_image_path = $directoryPathMain . $image_name; // Create the full path for the logo
                awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $tempQuestions['question_attachment'], $assignment_image_path, $multiple_files_bool = false, $multiple_file_index = 0);
                $final_question_attachment_image = json_encode(array("filepath" => $assignment_image_path, "original_name" => $file_name));
                $sql_logo = "UPDATE assignment_questions SET question_attachment = ? WHERE id= ? and assignment_id = ?";
                $conn_rjllearning_specific->prepare($sql_logo)->execute(array($final_question_attachment_image, $id, $assignment_id));
            }
            //}
        }
    }

    // Check if any rows were affected
    if ($updateAssignmentStmt->rowCount() > 0) {
        successreturn("Assignment updated successfully.");
    } else {
        errorreturn("No changes made to the assignment.");
    }
}
