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

$postdata = json_decode(file_get_contents("php://input"), true);
//print_r($postdata);
checkIfNoPhpContentsReceive();

if (
    !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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

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

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 getAllInstitutionClasses($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, $offset)
{
    // if (!is_array($branch_id)) {
    //     // If $branch_ids is not an array, convert it to an array
    //     $branch_ids = [$branch_id];
    // }
    $sql_count = "SELECT COUNT(*) AS total_rows FROM class_info WHERE institution_id = ? AND (branch_id LIKE ? OR branch_id = 'all')";
    $array_params = [$institution_id, '%' . $branch_id . '%'];
    // if ($search_string != null) {
    //     $sql_count .= " AND classname LIKE ? ";
    //     $array_params[] = '%' . $search_string . '%';
    // }
    if ($search_string != null) {
        // Remove dots from search string for comparison
        $clean_search = str_replace('.', '', $search_string);
        $sql_count .= " AND REPLACE(classname, '.', '') LIKE ? ";
        $array_params[] = '%' . $clean_search . '%';
    }
    
    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {
        $sql_class = "SELECT * FROM  class_info  where institution_id =?  AND (branch_id LIKE ? OR branch_id = 'all')";
        $array_params = [$institution_id, '%' . $branch_id . '%'];
        // if ($search_string != null) {
        //     $sql_class .= " AND classname LIKE ? ";
        //     $array_params[] = '%' . $search_string . '%'; // Append to $array_params
        // }
        if ($search_string != null) {
            $clean_search = str_replace('.', '', $search_string);
            $sql_class .= " AND REPLACE(classname, '.', '') LIKE ? ";
            $array_params[] = '%' . $clean_search . '%';
        }
    } else {
        $sql_class = "SELECT * FROM class_info WHERE institution_id = ? AND (branch_id LIKE ? OR branch_id = 'all')";
        // Initialize $array_params with institution_id
        $array_params = [$institution_id, '%' . $branch_id . '%'];
        // if ($search_string != null) {
        //     $sql_class .= " AND classname LIKE ? ";
        //     $array_params[] = '%' . $search_string . '%';
        // }
        if ($search_string != null) {
            $clean_search = str_replace('.', '', $search_string);
            $sql_class .= " AND REPLACE(classname, '.', '') LIKE ? ";
            $array_params[] = '%' . $clean_search . '%';
        }
        $sql_class .= " LIMIT " . $offset . " ," . $limit . " ";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_class);
    $stmt->execute($array_params);
    $result_class = $stmt->fetchAll();
    $array_return = [];
    $branches = [];
    if (count($result_class) >= 1) {

        foreach ($result_class as $rows) {

            $branch_id = $rows['branch_id'];

            $branches = []; // Initialize branches array

            if ($branch_id == 'all') {

                $branches[] = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
            } else {
                // $imploded_branchids = implode(',', $branch_id); // Convert array to comma-separated string
                // print_R($imploded_branchids);
                $sql = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($branch_id) and status = ?";
                $array_params = [$institution_id, '1']; // Add institution_id to parameters
                $stmt = $conn_rjllearning_specific->prepare($sql);
                $stmt->execute($array_params);
                $branch_rows = $stmt->fetchAll();

                foreach ($branch_rows as $branch) {
                    $branches[] = array('branch_id' => $branch['id'], 'name' => $branch['name']);
                }
            }

            $array_return[] =  array('class_id' => $rows['id'], 'branch_id' => $branches, 'class_name' => $rows['classname'], 'class_order' => $rows['class_order']);
        }
    }
    // else {
    //     errorreturn("Class does not exist in the specified branches.");
    // }
    if (count($result_class) < 50) {

        return array('total_rows' => $totalrows, 'class_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'class_info' => $array_return, 'maxreach' => 0);
    }
}


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

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

    $limit = $postdata['limit'];


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

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = getAllInstitutionClasses($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, $offset);
        successreturn($success);
    } else {

        $success['data'] = getAllInstitutionClasses($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, null);
        successreturn($success);
    }
}
