<?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 getSpecificquiz($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $subject_id, $status, $limit, $offset)
{
    $sql = "SELECT  count(*) as total_rows FROM  test  where institution_id =? ";
    $array_params = [$institution_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {

        $sql = "SELECT * FROM  test where institution_id =?";
        $array_params = [$institution_id];
        if ($branch_id == 'all') {
            $sql .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql .= " AND branch_id = ? ";
            $array_params[] = $branch_id;
        }

        if ($status == 'all') {
            $sql .= "";
        } else if ($status == '0') {
            $sql .= " AND status = ? ";
            $array_params[] = '0';
        } else if ($status !=  '1') {
            $sql .= " AND status = ? ";
            $array_params[] = '1';
        }

        if ($class_id == 'all') {
            $sql .= "";
        } else if ($class_id !=  null  && $class_id != 'all') {
            $sql .= " AND class_id = ? ";
            $array_params[] = $class_id;
        }

        if ($section_id == 'all') {
            $sql .= "";
        } else if ($section_id != 'all') {
            $sql .= " AND section_id = ? ";
            $array_params[] = $section_id;
        }

        if ($subject_id == 'all') {
            $sql .= "";
        } else if ($subject_id != 'all') {
            $sql .= " AND section_id = ? ";
            $array_params[] = $subject_id;
        }

        $sql .= " ORDER BY date_created ASC, time_created ASC";
    } else {

        $sql = "SELECT * FROM  test where institution_id =?";
        $array_params = [$institution_id];
        if ($branch_id == 'all') {
            $sql .= "";
        } else if ($branch_id !=  null  && $branch_id != 'all') {
            $sql .= " AND branch_id = ? ";
            $array_params[] = $branch_id;
        }

        if ($status == 'all') {
            $sql .= "";
        } else if ($status == '0') {
            $sql .= " AND status = ? ";
            $array_params[] = '0';
        } else if ($status !=  '1') {
            $sql .= " AND status = ? ";
            $array_params[] = '1';
        }



        if ($class_id == 'all') {
            $sql .= "";
        } else if ($class_id !=  null  && $class_id != 'all') {
            $sql .= " AND class_id = ? ";
            $array_params[] = $class_id;
        }

        if ($section_id == 'all') {
            $sql .= "";
        } else if ($section_id != 'all') {
            $sql .= " AND section_id = ? ";
            $array_params[] = $section_id;
        }

        if ($subject_id == 'all') {
            $sql .= "";
        } else if ($subject_id != 'all') {
            $sql .= " AND section_id = ? ";
            $array_params[] = $subject_id;
        }


        //  if ($mindate != 'null' and $maxdate !=  null) {
        //         $sql .= " AND publish_date >= ? and last_date <= ?";
        //         $array_params[] = $mindate;
        //          $array_params[] = $maxdate;
        // }

        $sql .= " ORDER BY date_created ASC, time_created ASC ";
        $sql .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();

    $array_return = array();
    $test_questions = array();
    foreach ($result as $rows) {
 $section_id = $rows['section_id'];
        // $section_info = [];
        if ($section_id == 'all') {

            $section_info[] = array('section_id' => $section_id, 'section_name' => ucwords($section_id));
        } else {
            // $imploded_branchids = implode(',', $branch_id); // Convert array to comma-separated string
            // print_R($imploded_branchids);
            $sql = "SELECT * FROM section_info WHERE institution_id = ? AND id IN ($section_id) ";
            $array_params = [$institution_id]; // Add institution_id to parameters
            $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']);
            }
        }
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows['class_id']);
        $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $rows['subject_id']);
        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);
       
        $array_return[] = array(
            "test_id" => $rows['id'], 'branch_id' => $branch, 'class_info' => $class_info, 'section_id' => $section_info, 'subject_info' => $subject_info, "name" => $rows['name'], "description" => $rows['description'],
            "max_points" => $rows['max_points'], "publish_date" => $rows['publish_date'], "last_date" => $rows['last_date'], "publish_time" => $rows['publish_time'], "last_submission_time" => $rows['last_submission_time'], "timer" => $rows['timer'], "display_question_by" => $rows['display_question_by'], "test_questions" => $test_questions
        );
    }

    if (count($result) < 50) {
        return array('total_rows' => $totalrows, 'test_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'test_info' => $array_return, 'maxreach' => 0);
    }
}


if ($postdata['function_type']  == "fetch_test") {

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

    if (isset($postdata['branch_id']) and !empty($postdata['branch_id']) and trim($postdata['branch_id'])) {
        $branch_id = trim($postdata['branch_id']);
    } else {
        $branch_id = 'all';
    }

    if (isset($postdata['class_id']) and !empty($postdata['class_id']) and trim($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id =  'all';
    }

    if (isset($postdata['section_id']) and !empty($postdata['section_id']) and trim($postdata['section_id'])) {
        $section_id = trim($postdata['section_id']);
    } else {
        $section_id =  'all';
    }

    if (isset($postdata['subject_id']) and !empty($postdata['subject_id']) and trim($postdata['subject_id'])) {
        $subject_id = trim($postdata['subject_id']);
    } else {
        $subject_id =   'all';
    }
    if (isset($postdata['status']) and !empty($postdata['status']) and trim($postdata['status'])) {
        $status = trim($postdata['status']);
    } else {
        $status =   'all';
    }

    $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, $institution_id, $branch_id, $class_id, $section_id, $subject_id, $status, $limit, $offset);
    successreturn($success);
}
