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

//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 = 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['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 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;

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

function getSpecificQuestion($conn_rjllearning_specific,$institution_id,$question_id) {
        
    $sql = "SELECT * FROM  question_bank_info where id= ? AND institution_id =?";
    $array_params = [$question_id,$institution_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();
    
    $array_return = array();
    $questions = array();
    if(count($result) >= 1){
        
       $class_info = getClass($conn_rjllearning_specific, $institution_id, $result[0]['class_id']);
       $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $result[0]['subject_id']);
       $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $result[0]['branch_id']);
          $section_info = getSection($conn_rjllearning_specific, $institution_id, $result[0]['section_id']);
    
        if ($result[0]['question_attachment'] != null && !is_array($result[0]['question_attachment'])) {
            $data_attachment = json_decode($result[0]['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 = json_decode($result[0]['options'], true);
    $topic_name = json_decode($result[0]['topic_name'], true);
    $questions[] = array("question_no"=>$result[0]['question_no'],"question_type"=>$result[0]['question_type'],
        "level"=>$result[0]['level'],"question_marks"=>$result[0]['question_marks'],"topic_name"=>$topic_name,"author"=>$result[0]['author'],"question_description"=>$result[0]['question_description'],"options"=>$options,"answer"=>$result[0]['answer'],"question_attachment"=>$final_question_attachment);
   
   
    $array_return[] = array("bank_questions_id"=>$result[0]['id'],'branch_id' => $branch, 'class_info' => $class_info, 'section_id' => $section_info,'subject_info' => $subject_info,"questions" =>$questions );
    return $array_return;
  
}else{
    errorreturn("Question bank not found.");
}
}


if($postdata['function_type']  == "fetch_specific_question_bank") {  
   
    $institution_id = trim($postdata['institution_id']);
    $question_id = trim($postdata['bank_questions_id']);
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    } 
    
    $success['data'] = getSpecificQuestion($conn_rjllearning_specific,$institution_id,$question_id);
    successreturn($success);
}