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

//validation 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';

//aws image store
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';


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


if (
    // !isset($postdata['search_string']) || !checkIfIssetAndNotEmpty($postdata['search_string']) || 
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);

$institution_id = (!empty($postdata['institution_id']) && $postdata['institution_id'] !== null) 
    ? $postdata['institution_id'] 
    : 'all';

$branch_id = ($institution_id === 'all')
    ? 'all'
    : ((!empty($postdata['branch_id']) && $postdata['branch_id'] !== null) ? $postdata['branch_id'] : 'all');


// $search_string = $postdata['search_string'];
$search_string = isset($postdata['search_string']) && checkIfIssetAndNotEmpty($postdata['search_string']) ? $postdata['search_string'] : 'null';

// Check if search_string is not 'null' and has at least 3 characters
if ($search_string !== 'null' && strlen($search_string) < 3) {
    $search_string = 'null';  // If the string is too short, set it to 'null'
}



// if ($postdata['search_string'] || strlen(trim($postdata['search_string'])) < 3) {
//     errorreturn('Error: Search string must be at least 3 characters long.');
// }


// if (strlen($postdata['search_string']) < 3 ) {
//     errorreturn("Search string must be at least 3 characters long.");
// }

if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}


function fetchUsersForReminders($conn_rjllearning, $workspace_id, $search_string, $institution_id, $branch_id)
{
    $query = "SELECT id, name, username, mobile FROM users 
              WHERE workspace_id = ? and can_activate = 1 and role !='student'";

    $array_params = [$workspace_id];

    if ($search_string != null) {
        $query .= " AND (name LIKE ? OR username LIKE ? OR email LIKE ? OR mobile LIKE ? OR role LIKE ? OR designation LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    // Add institution and branch conditions
    if ($institution_id !== 'all') {
        $query .= " AND institution_id = ?";
        $array_params[] = $institution_id;  
    }
    
    if ($branch_id !== 'all') {
        $query .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    $query .= "order by name, username, role LIMIT 25";

    // Prepare and execute the query
    $stmt = $conn_rjllearning->prepare($query);
    $stmt->execute($array_params);

    // Fetch results
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($users as &$user) {
        $user['name'] = $user['name'] . ' ' . $user['mobile'];
    }
    unset($user); // Break the reference
    
    return $users;
}



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

    $success['data'] = fetchUsersForReminders($conn_rjllearning, $workspace_id, $search_string, $institution_id, $branch_id);
    successreturn($success);
}