<?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/functions/functions.php';
require_once $base_path_to_learning.'user_management/authenticate.php';


$postdata = json_decode(file_get_contents("php://input"), true);
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  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

  if ($postdata['function_type'] == "fetch_users") {
       
    if(isset($postdata['search_string']) and !empty($postdata['search_string'])){
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
    $institution_id = $postdata['institution_id'];
 
$limit = isset($postdata['limit']) && is_numeric($postdata['limit']) ? (int)$postdata['limit'] : 10; 
$page = (isset($postdata['page']) && is_numeric($postdata['page'])) ? (int)$postdata['page'] : 1; 
$offset = ($page - 1) * $limit;

        
    $success['data'] = fetchUsers($conn_rjllearning, $institution_id,$search_string,$limit,$offset);
    successreturn($success);
}