<?php

ini_set('display_errors', 1);

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

require_once $base_path_to_learning_resources . "includes/connect.php";
require_once $base_path_to_learning_resources . "lib/function.php";
require_once $base_path_to_learning_resources . "lib/validate_api_signature.php";
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';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
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';
require_once $base_path_to_learning . "user_management/functions/functions.php";
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/activity_mentor/activity_functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

$required_fields = ['api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

validateApiSignature($postdata['api_signature']);

// Authenticate and validate the JWT token
$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;

// Validate user access to a specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);



// $isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
// if (!$isBranchClassSubjectValid) {
//     errorreturn("Invalid branch_id.");
// }
function getFunction_code($conn_rjllearning, $search_string,$limit, $offset)
{
  $sql = "SELECT count(*) as total_rows FROM function_codes where  function_status = 1 ";
    $stmt = $conn_rjllearning->prepare($sql);
    $stmt->execute();
    $result_total = $stmt->fetch();
    $totalrows = $result_total['total_rows'];

    if ($limit == 'all') {
        $sql_query = "SELECT * FROM function_codes WHERE  function_status = 1 and function_label LIKE ?";
        $array_params = ['%' . $search_string . '%'];
        

        if ($search_string != null) {
            $sql_query .= " AND function_label LIKE ? ";
            $array_params[] = '%' . $search_string . '%';
        }

        // $sql_query .= "order by group_label desc, id desc";
    } else {

        $sql_query = "SELECT * FROM function_codes  WHERE  function_status = 1";
              $array_params = [];

        

        if ($search_string != null) {
            $sql_query .= " AND (function_label LIKE ? OR group_label LIKE ? OR code LIKE ?)";
            $search_term = '%' . $search_string . '%';
            $array_params[] = $search_term;
            $array_params[] = $search_term;
            $array_params[] = $search_term;
        }
   
        $sql_query .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning->prepare($sql_query);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

// var_Dump($session_rows);
// die();
    $array_return = [];

    foreach ($session_rows as $rows) {
        


        $array_return[] = array(
            'function_code_id' => $rows['id'],
             'code' => $rows['code'],
             'function_label' => $rows['function_label'],
            
              'group_label' => $rows['group_label'],
            'status' => $rows['function_status']
        );
    }
    if (count($session_rows) < 50) {

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

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

    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;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = getFunction_code($conn_rjllearning, $search_string,$limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = getFunction_code($conn_rjllearning,$search_string,$limit, null);
        successreturn($success);
    }
}
