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

// Validation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';

require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';


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

// Check required fields
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All required fields must be provided.");
}

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;

// Validate user access
$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);
require_once $base_path_to_learning . 'functions/get_branch_functions.php';

function getExtraPaidLeaves($conn_rjllearning_specific, $institution_id, $search_string, $limit, $offset)
{
    // Count total holidays for pagination
    $sql_count = "SELECT COUNT(*) as total_rows FROM extra_paid_leaves WHERE institution_id = ?";
    $array_params = [$institution_id];
    
    if ($branch_id == 'all') {
        $sql_count .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
        $sql_count .= " AND (branch_id = ?  or branch_id = 'all')";
        $array_params[] = $branch_id;
    }
    
    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $totalrows = $stmt->fetchColumn();

    // Base query
    $sql_holiday = "SELECT * FROM extra_paid_leaves WHERE institution_id = ?";
    $array_params = [$institution_id];
    
    if ($branch_id == 'all') {
        $sql_holiday .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
        $sql_holiday .= " AND (branch_id = ? OR branch_id = 'all') ";
        $array_params[] = $branch_id;
    }
    
    if (!empty($search_string)) {
        $sql_holiday .= " AND name LIKE ?";
        $array_params[] = '%' . $search_string . '%';
    }
    
    $sql_holiday .= " ORDER BY id DESC";
    if ($limit !== 'all') {
         $sql_holiday .= " LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt = $conn_rjllearning_specific->prepare($sql_holiday);
    $stmt->execute($array_params);
    $leaves_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Prepare response array
    $array_return = [];
    foreach ($leaves_rows as $row) {
        // $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        $branch_info = $row['branch_id'] == 'all' ? array('branch_id' => 'all', 'name' => ucwords('all')) 
                        : getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
        $array_return[] = [
            'holiday_id' => $row['id'],
            'branch_id' => $branch_info,
            'holiday_name' => $row['name'],
            'leave_type' => $row['leave_type'],
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date'],
            'remarks' => $row['remarks'],
            'status' => $row['status'],
        ];
    }

    return [
        'total_rows' => $totalrows,
        'extra_paid_leaves' => $array_return,
        'maxreach' => count($leaves_rows) < $limit ? 1 : 0
    ];
}



if ($postdata['function_type'] == 'fetch_extra_paid_leaves') {
    
    $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.");
    }
    

    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'] = getExtraPaidLeaves($conn_rjllearning_specific, $institution_id,$search_string ,$limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = getExtraPaidLeaves($conn_rjllearning_specific, $institution_id,$search_string,$limit, null);
        successreturn($success);
    }
    
}