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

// Validation 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 = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);die();
checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['test_id']) or !checkIfIssetAndNotEmpty($postdata['test_id']) or 
    !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 in decoded 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;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$institution_id = trim($postdata['institution_id']);

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

function getSpecificquiz($conn_rjllearning_specific, $test_id, $institution_id,$branch_id,$limit,$offset)
{

    $sql = "SELECT * FROM test WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $array_params = [$test_id, $institution_id,$branch_id];
    $sql .= " ORDER BY date_created ASC, time_created ASC";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
    //print_r($result);
    $quiz_questions = array();

    if (count($result) >= 1) {
        
            // $sql = "SELECT * FROM test_questions WHERE test_id = ? AND institution_id = ?";
        $sql ="SELECT 
             tq.id,
            tq.test_id,
            tq.institution_id,
            tq.branch_id,
            tq.question_bank_id,
            qbi.class_id,
            qbi.section_id,
            qbi.subject_id,
            qbi.question_no,
            qbi.question_type,
            qbi.level,
            qbi.question_marks,
            qbi.topic_name,
            qbi.author,
            qbi.question_description,
            qbi.options,
            qbi.answer,
            qbi.question_attachment,
            qbi.status
        FROM 
            test_questions tq
        JOIN 
            question_bank_info qbi
        ON 
            tq.question_bank_id = qbi.id
        WHERE 
            tq.test_id = ? AND tq.institution_id = ? AND branch_id =?";

        $array_params = [$test_id, $institution_id,$branch_id];
        //$sql .= " order by tq.date_created desc, tq.time_created desc ";
        $sql .= "LIMIT " . $offset . " ," . $limit . "";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
        $result_question = $stmt->fetchAll();
        // print_r($result_question);
        if (count($result_question) >= 1) {
            
            foreach ($result_question as $temp) {
                if ($temp['question_attachment'] != null && !is_array($temp['question_attachment'])) {
                    $data_attachment = json_decode($temp['question_attachment'], true);
                    $filePath = $data_attachment['filepath'];
                    $originalName = $data_attachment['original_name'];
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);
                    $final_question_attachment = ["filepath" => $aws_attachment, "original_name" => $originalName];
                } else {
                    $final_question_attachment =  null;
                }
 $options = !empty($temp['options']) ? json_decode($temp['options'], true) : null;
                $quiz_questions[] = array(
                    "test_question_id" =>$temp['id'],
                    "bank_questions_id" => $temp['question_bank_id'],
                    "test_id" => $temp['test_id'],
                    "institution_id" => $temp['institution_id'],
                    "branch_id" => $temp['branch_id'],
                    "question_no" => $temp['question_no'],
                    "question_type" => $temp['question_type'],
                    'question_description' => $temp['question_description'],
                    "options" => $options,
                    "answer" => $temp['answer'],
                    "question_attachment" => $final_question_attachment,
                    "question_marks" => $temp['question_marks']
                );
            }
        }
        
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_id']);
        $section_id = $result[0]['section_id'];
            $section_info = [];
            if ($section_id == 'all') {
                $section_info = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
            } else {
                $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id)";
                $array_params = [$institution_id];
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute($array_params);
                $section_rows = $stmt->fetchAll();

                foreach ($section_rows as $section_data) {
                    $section_info = array('section_id' => $section_data['id'], 'section_name' => $section_data['section_name']);
                }
            }
        $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $result[0]['subject_id']);
        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);

 usort($quiz_questions, function ($a, $b) {
            return $b['bank_questions_id'] - $a['bank_questions_id'];
        });
        return array(
            "test_id" => $result[0]['id'],
            'branch_id' => $branch,
            'class_info' => $class_info,
            'section_id' => $section_info,
            'subject_info' => $subject_info,
            "name" => $result[0]['name'],
            "description" => $result[0]['description'],
            "max_points" => $result[0]['max_points'],
            "publish_date" => $result[0]['publish_date'],
            "last_date" => $result[0]['last_date'],
            "publish_time" => $result[0]['publish_time'],
            "last_submission_time" => $result[0]['last_submission_time'],
            "timer" => $result[0]['timer'],
            "display_question_by" => $result[0]['display_question_by'],
            "quiz_questions" => $quiz_questions
        );
    }
}

if ($postdata['function_type'] == "fetch_specific_test") {
    
    //$branch_id = trim($postdata['branch_id']);
    $test_id = trim($postdata['test_id']);


    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    
    $limit = $postdata['limit'];
    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    
      if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
      }else{
        $offset =  null;  
      }

    $success['data'] = getSpecificquiz($conn_rjllearning_specific, $test_id, $institution_id,$branch_id,$limit,$offset);
    successreturn($success);
}
