<?php

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

// Step 1: Basic Test Create

// function   addQuestions($conn_rjllearning_specific, $questions,$test_id,$institution_id,$branch_id,$class_id,$section_id,$subject_id,$username) {
//       foreach ($questions as  $index => $question) {
        
//           if (isQuestionInBank($conn_rjllearning_specific, $question,$institution_id,$branch_id)) {
//             $questionId = getExistingQuestionId($conn_rjllearning_specific, $question,$institution_id,$branch_id);
//           } else {
//             $questionId = saveNewQuestionToBank($conn_rjllearning_specific, $question,$institution_id,$branch_id,$index,$class_id,$section_id,$subject_id,$username);
//           }
//           //saveQuestionToTest($conn_rjllearning_specific, $test_id, $questionId,$institution_id,$branch_id,$username);
//           if (!isQuestionInTest($conn_rjllearning_specific, $test_id, $questionId, $institution_id, $branch_id)) {
//                 saveQuestionToTest($conn_rjllearning_specific, $test_id, $questionId, $institution_id, $branch_id, $username);
//           }

//     }
// }

function  validateBankQuestions($conn_rjllearning_specific,$question){
    $max_points = 0;
    
    $question_text = $question['question_text'];
    $question_marks = isset($question['question_marks']) ? floatval($question['question_marks']) : 0;
    $question_no = $question['question_no'];
    $answer = (isset($question['answer']) and !empty($question['answer'])) ? (trim($question['answer'])) : null;
    $question_type = (isset($question['question_type']) and !empty($question['question_type'])) ? (trim($question['question_type'])) : null;
    $level = $question['level'] ;
    $options = (isset($question['options']) and !empty($question['options'])) ? $question['options'] : null;

    $topic_name = explode(',', $question['topic_name']);
    // $topic_name = json_encode($question['topic_name'], true);
    //  print_r ($topic_name);die();
    $required_fields = ['question_text', 'question_no','topic_name','question_type','question_marks','level','answer'];

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


    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;

    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') {
        // $options = $question['options'];
        $options = explode(',', $question['options']);
        //   $options = json_encode($question['options'], true);
        if (!is_array($options)) {
            errorreturn("Options must be an array.");
        }
        
       if ($options !=  null) {
        $optionsCount = count($options);
        if ($optionsCount < 2 || $optionsCount > 4) {
            errorreturn("MCQ questions must have between 2 and 4 options.");
        }
       }
        if (!isset($answer) || !in_array($answer, $options)) {
            errorreturn("Answer must match one of the options for MCQ questions.");
        }
    } elseif ($question_type === 'subjective') {
    }

}
// Step 2: Add Questions
function isQuestionInBank($conn_rjllearning_specific, $question, $institution_id, $branch_id)
{
    // print_r( $question['question_text']);
    $query = "SELECT id 
        FROM question_bank_info 
        WHERE institution_id = ? 
          AND branch_id = ? 
          AND ( question_description = ? OR answer = ?)";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $question['question_text'],
        $question['answer']
    ]);
    $result = $stmt->fetchAll();
    if(count($result) >= 1){
         return true;
    }else{
        return false;
    }
}


// Step 4: Get Existing Question ID
function getExistingQuestionId($conn_rjllearning_specific, $question, $institution_id, $branch_id)
{
    $query = "
        SELECT id 
        FROM question_bank_info 
        WHERE institution_id = ? 
          AND branch_id = ? 

          AND (question_description = ? OR answer = ?)";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $question['question_text'],
        $question['answer']
    ]);
    $result = $stmt->fetchAll();
    
    if(count($result) >= 1){
    return $result[0]['id'];
    }else{
        return false;
    }
}

// Step 5: Save New Question to Bank
function saveNewQuestionToBank($conn_rjllearning_specific, $question,$institution_id,$branch_id,$index,$class_id,$section_id,$subject_id,$username,$workspace_id)
{
    
    validateBankQuestions($conn_rjllearning_specific,$question);
    $max_points = 0;
   
    $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"];
        $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);
        $image_name = time() . "-" . date('d-m-Y') . "." . $file_extension;
        $question_attachment = $directoryPathMain . $image_name;
        try {
            $GLOBALS['s3_learning_bucket']->putObject([
                'Bucket' => $GLOBALS['learning_bucketName'],
                'Key' => $question_attachment,
                'SourceFile' => $fileTmpName,

            ]);
        } catch (Exception $e) {
            errorreturn($e->getMessage());
        }
        $question_attachment = json_encode(array("filepath" => $question_attachment, "original_name" => $file_name));
    }
    
    $date_created = date('Y-m-d');
    $time_created = time();
   
    $options = (isset($question['options']) and !empty($question['options'])) ?  (explode(',', $question['options'])) : null;
    $options = json_encode($options); 
       
    $topic_name = explode(',', $question['topic_name']); 
    $topic_name = json_encode($topic_name);
    $insertQuestionBankQuery = "INSERT INTO question_bank_info (institution_id, branch_id, class_id, section_id, subject_id, 
                             question_no, question_type, level, question_marks, topic_name, 
                             author, question_description, options, answer, 
                             question_attachment, date_created, time_created, status) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $insertQuestionBankStmt = $conn_rjllearning_specific->prepare($insertQuestionBankQuery);
    $insertQuestionBankStmt->execute([
                    $institution_id,
                    $branch_id,
                    $class_id,
                    $section_id,
                    $subject_id,
                    $question['question_no'],
                    $question['question_type'],
                    $question['level'],
                    $question['question_marks'],
                    $topic_name,
                    $username,
                    $question['question_text'],
                    $options,
                    $question['answer'],
                    $question_attachment,
                    $date_created,
                    $time_created,
                    1
                ]);
    return $conn_rjllearning_specific->lastInsertId();
}


// Step 6: Save Question to Test
function saveQuestionToTest($conn_rjllearning_specific, $testId, $question_bank_id,$question_marks, $institution_id, $branch_id,$username)
{
    $date_created = date('Y-m-d');
    $time_created = time();
    $insertQuestionQuery = "INSERT INTO test_questions (institution_id, branch_id, test_id, question_bank_id,question_marks,added_by, date_created, time_created, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)";
    $insertQuestionStmt = $conn_rjllearning_specific->prepare($insertQuestionQuery);
    $insertQuestionStmt->execute([$institution_id, $branch_id, $testId, $question_bank_id,$question_marks, $username, $date_created, $time_created, 1]);
}

function isQuestionInTest($conn_rjllearning_specific, $testId, $question_bank_id, $institution_id,$branch_id) {
    $query = "
        SELECT id 
        FROM test_questions 
        WHERE institution_id = ? 
          AND branch_id = ? 
          AND test_id = ? 
          AND question_bank_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([
        $institution_id,
        $branch_id,
        $testId,
        $question_bank_id
    ]);
     $result = $stmt->fetchAll();
    
    if(count($result) >= 1){
        return true;
        // errorreturn("This question already exists");
    }else{
        return false;
    }
}

function isExistingQuestionInBank($conn_rjllearning_specific, $question, $institution_id, $branch_id,$question_bank_id)
{
    // print_r( $question['question_text']);
    $query = "SELECT id 
        FROM question_bank_info 
        WHERE id= ? AND institution_id = ? 
          AND branch_id = ? ";
    $stmt = $conn_rjllearning_specific->prepare($query);
    $stmt->execute([
        $question_bank_id,
        $institution_id,
        $branch_id
    ]);
    $result = $stmt->fetchAll();
    // print_r($result);die();
    if(count($result) >= 1){
         return true;
    }else{
        return false;
    }
}


function updateQuestionInBank($conn_rjllearning_specific, $question, $question_bank_id, $institution_id, $branch_id, $index, $class_id, $section_id, $subject_id, $username,$workspace_id) {
    
    validateBankQuestions($conn_rjllearning_specific,$question);

    $sqlQuestions = $conn_rjllearning_specific->prepare("SELECT id,question_attachment FROM question_bank_info WHERE id = ? AND institution_id = ?");
    $sqlQuestions->execute([$question_bank_id, $institution_id]);
    $rows = $sqlQuestions->fetchAll();
    if (count($rows) >= 1) {
            $existing_attachment = $rows[0]['question_attachment'];
    }
    
    $max_points = 0;
   
    $remove_bool = (isset($question['remove_bool']) && !empty($question['remove_bool'])) ? trim($question['remove_bool']) : 0;
    $remove_dynamic_key = $index;
    $file_key = 'questions' . $index . '[question_attachment]';

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

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

           $existing_attachment = $result_image[0]['question_attachment'];

           awsS3UserUploadDelete($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $conn_rjllearning_specific, $institution_id, $existing_attachment, null, null);
           $sql = "UPDATE question_bank_info SET question_attachment = ? WHERE id = ? and institution_id= ?";
           $conn_rjllearning_specific->prepare($sql)->execute(array(null, $question_bank_id, $institution_id));
        }
       }
    }

    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 . "/";

        // if (!file_exists($GLOBALS['base_path_to_learning'] . $directoryPathMain)) {
        //     mkdir($GLOBALS['base_path_to_learning'] . $directoryPathMain, 0777, true);
        // }
        //  else {

        //     $directoryPathMain = substr($existing_attachment, 0, strrpos($existing_attachment, '/') + 1);
        // }
        $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);
        $image_name = time() . "-" . date('d-m-Y') . "." . $file_extension;
        $question_attachment = $directoryPathMain . $image_name;
        try {
            $GLOBALS['s3_learning_bucket']->putObject([
                'Bucket' => $GLOBALS['learning_bucketName'],
                'Key' => $question_attachment,
                'SourceFile' => $fileTmpName,

            ]);
        } catch (Exception $e) {
            errorreturn($e->getMessage());
        }
        $question_attachment = json_encode(array("filepath" => $question_attachment, "original_name" => $file_name));
        $sql_users = "UPDATE question_bank_info SET  question_attachment =? WHERE id = ? and  institution_id=?";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($question_attachment, $question_bank_id, $institution_id));
    }
    

   $options = (isset($question['options']) and !empty($question['options'])) ?  (explode(',', $question['options'])) : null;
    $options = json_encode($options); 
       
    $topic_name = explode(',', $question['topic_name']); 
    $topic_name = json_encode($topic_name);

    $updateQuestionBankQuery = "UPDATE question_bank_info SET question_no = ?, question_type = ?, level = ?, topic_name = ?, author = ?, question_description = ?, options = ?, answer = ? ,question_marks=? WHERE id = ? AND institution_id = ?";
    $updateQuestionBankStmt = $conn_rjllearning_specific->prepare($updateQuestionBankQuery);
    $updateQuestionBankStmt->execute([$question['question_no'],
    $question['question_type'],
    $question['level'],
    $topic_name,
    $username,
    $question['question_text'],
    $options,
    $question['answer'],$question['question_marks'],$question_bank_id, $institution_id]);
}

/**
 * Update question in the test.
 */
function updateQuestionInTest($conn_rjllearning_specific, $test_id, $question_bank_id, $question_marks, $institution_id, $branch_id, $username) {

    $updateTestQuestionQuery = "UPDATE test_questions SET question_marks = ? WHERE  question_bank_id = ? AND test_id = ? AND institution_id = ?";
    $updateTestQuestionStmt = $conn_rjllearning_specific->prepare($updateTestQuestionQuery);
    $updateTestQuestionStmt->execute([$question_marks,$question_bank_id,$test_id, $institution_id]);
}

