<?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/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/payroll/functions.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']);

$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);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

// function getHoliday($conn_rjllearning_specific, $institution_id, $search_string, $limit, $offset)
// {
//     // Count total holidays for pagination
//     $sql_count = "SELECT COUNT(*) as total_rows FROM holiday_calendar WHERE institution_id = ?";
//     $stmt = $conn_rjllearning_specific->prepare($sql_count);
//     $stmt->execute([$institution_id]);
//     $totalrows = $stmt->fetchColumn();

//     // Base query
//     $sql_holiday = "SELECT * FROM holiday_calendar WHERE institution_id = ?";
//     $array_params = [$institution_id];

//     // Apply search filter
//     if (!empty($search_string)) {
//         $sql_holiday .= " AND holiday_name LIKE ?";
//         $array_params[] = '%' . $search_string . '%';
//     }

//     // Apply sorting
//     $sql_holiday .= " ORDER BY holiday_date DESC";

//     // Apply limit and offset if not fetching all
//     if ($limit !== 'all') {
//          $sql_holiday .= "LIMIT " . $offset . " ," . $limit . "";
//     }

//     // Execute query
//     $stmt = $conn_rjllearning_specific->prepare($sql_holiday);
//     $stmt->execute($array_params);
//     $holiday_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

//     // Prepare response array
//     $array_return = [];
//     foreach ($holiday_rows as $row) {
//         $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);
//         $array_return[] = [
//             'holiday_id' => $row['id'],
//             'branch_id' => $branch_info,
//             'holiday_name' => $row['holiday_name'],
//             'holiday_date' => $row['holiday_date'],
//             'applicable_to' => $row['applicable_to'],
//         ];
//     }

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

$institution_id = isset($postdata['institution_id']) && checkIfIssetAndNotEmpty($postdata['institution_id']) ? ($postdata['institution_id']) : 'all';
if ($institution_id == 'all') {
    $branch_id = 'all';
} else {
    $branch_id = isset($postdata['branch_id']) && checkIfIssetAndNotEmpty($postdata['branch_id']) ? ($postdata['branch_id']) : 'all';
}

if ($postdata['function_type'] == "fetch_holiday") {
    
    if (isset($postdata['from_date']) and !empty($postdata['from_date'])) {
        $from_date = trim($postdata['from_date']);
    } else {
        $from_date = date('Y-m-d');
    }
    
    if (isset($postdata['to_date']) and !empty($postdata['to_date'])) {
        $to_date = trim($postdata['to_date']);
    } else {
        $to_date = date('Y-m-d');
    }

    if ($from_date > $to_date) {
        errorreturn('Invalid Date format');
    }

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