<?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.'branch_management/functions/functions.php';
require_once $base_path_to_learning.'user_management/authenticate.php';
require_once $base_path_to_learning.'functions/common_functions.php';
require_once $base_path_to_learning_resources.'includes/specific_db_config.php';
//db access function
require_once $base_path_to_learning.'functions/db_access_function.php';

$postdata = json_decode(file_get_contents("php://input"), true);
//print_r($postdata);
checkIfNoPhpContentsReceive();
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, null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}



if ($postdata['function_type'] == "branch") {
      
      
    //  search by name,username
    if(isset($postdata['search_string']) and !empty($postdata['search_string'])){
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
 
    if(isset($postdata['all_option']) and $postdata['all_option']) {
        $all_option = 1;
    } 
    
    $institution_id = trim($postdata['institution_id']);
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific,$institution_id);
    if($check_academic_confirmation != true){
         errorreturn("Access denied. Academic session not active.");
    }
    $additionaldata = array();
    $additionaldata = ['id', 'branch_code', 'name'];
    $success['data'] = Branch($conn_rjllearning_specific, $institution_id,$search_string,$all_option,$additionaldata);
    successreturn($success);
        
}