<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

//valdation file
require_once $base_path_to_resources . "includes/config.php"; // use require for mandatory files
require_once $base_path_to_resources . 'lib/function.php';
require_once $base_path_to_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_resources . 'lib/validate_function.php';
require_once $base_path . 'user_management/authenticate.php';

//creating dynamic db
require_once $base_path_to_resources . 'includes/specific_db_config.php';
$postdata = json_decode(file_get_contents("php://input"), true);
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']);

//authenticate jwt token
$jwttoken = $postdata['jwt_token'];

$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$created_by = $jwt_validate->data->username;
$workspace_id = $jwt_validate->data->workspace_id;
$role = $jwt_validate->data->role;
$userid = $jwt_validate->data->id;

$function_code = 'fetch_upload_categories';

$confirmed_role_user = validatePrimaryAccess($conn, $workspace_id, $role, $userid, ['superadmin', 'admin', null]);
if (!$confirmed_role_user){ 
        errorreturn('Access denied.');
}else{
        $specific_db_conn = dynamicDbConnection($confirmed_role_user);
         if ($role == null) {
            checkCompanyBranchFunctionAccess($specific_db_conn, $role, $userid, $workspace_id, null, null, null,  $function_code);
         }
}


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


if (!isset($postdata['limit']) or empty($postdata['limit']) or !in_array($postdata['limit'], ['2','5','25', '50', '100'])) {
    $limit = 25;
} else {
    $limit = intval($postdata['limit']);
}

if (!isset($postdata['page']) or empty($postdata['page']) or $postdata['page'] <= 0) {
    $page = 0;
} else {
    $page = (intval(trim($postdata['page'])) - 1) * $limit;
}

try {

    if ($postdata['function_type'] == 'fetch_upload_categories') {

        $total_rows = 0;
        $max_reached = 0;
        $category_info = [];

        $sql = "Select count(*) as total from  upload_categories where $workspace_id = ? and name LIKE ?";
        $fetch_catgory = $specific_db_conn->prepare($sql);
        $fetch_catgory->execute(array($workspace_id,'%' . $search_string . '%'));
        $result_upload_categories = $fetch_catgory->fetchAll();
         
        if (count($result_upload_categories) > 0) {
            $total_rows = $result_upload_categories[0]['total'];
        }

        $sql = "Select * from  upload_categories where $workspace_id = ? and name LIKE ?  order by name, time_created desc limit $page, $limit";
        $fetch_catgory = $specific_db_conn->prepare($sql);
        $fetch_catgory->execute(array($workspace_id,'%' . $search_string . '%'));
        $result_upload_categories = $fetch_catgory->fetchAll();
       
        if (count($result_upload_categories) > 0) {
            // print_r($result_upload_categories);
            foreach ($result_upload_categories as $element) {
                $category_info[] = array('category_id' => $element['id'],'workspace_id' => $element['workspace_id'], 'name' => $element['name']);
            }
        }

        if (count($result_upload_categories) < $limit) {
            $max_reached = 1;
        }


        successreturn(array('total_rows' => $total_rows, 'max_reached' => $max_reached, 'category_info' => $category_info));
    }
    errorreturn('Invalid request.');
} catch (Exception $e) {
    errorreturn("Error : " . $e->getMessage());
}
