<?php
declare(strict_types=1);

function safe_page_return(string $value, string $fallback = ''): string
{
    $value = trim($value);

    if ($value === '' || preg_match('/[\r\n]/', $value)) {
        return $fallback;
    }

    if (preg_match('#^[a-z][a-z0-9+.-]*:#i', $value) || str_starts_with($value, '//') || str_starts_with($value, '/')) {
        return $fallback;
    }

    if (str_contains($value, '..')) {
        return $fallback;
    }

    $path = parse_url($value, PHP_URL_PATH);
    if (!is_string($path)) {
        return $fallback;
    }

    $allowedPages = array(
        'audit_report.php',
        'bill_management.php',
        'bill_receipt.php',
        'booking.php',
        'cancel_bill.php',
        'data_maintenance.php',
        'dashboard.php',
        'employees.php',
        'job_details.php',
        'login.php',
        'loyalty.php',
        'manage_system.php',
        'member.php',
        'positions.php',
        'quick_receipt.php',
        'quick_service.php',
        'quick_service_settings.php',
        'queue.php',
        'report_service.php',
        'sale_report.php',
        'service_categories.php',
        'service_groups.php',
        'services.php',
        'void_report.php',
    );

    return in_array($path, $allowedPages, true) ? $value : $fallback;
}

function current_page_return(string $fallback = 'dashboard.php'): string
{
    $script = basename((string) ($_SERVER['PHP_SELF'] ?? ''));
    $query = trim((string) ($_SERVER['QUERY_STRING'] ?? ''));
    $path = $script !== '' ? $script : $fallback;

    if ($query !== '') {
        $path .= '?' . $query;
    }

    return safe_page_return($path, $fallback);
}

function app_process_path(string $script): string
{
    $normalizedScript = ltrim(str_replace('\\', '/', $script), '/');
    $scriptName = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));

    if (strpos($scriptName, '/process/') !== false) {
        return $normalizedScript;
    }

    return '../process/' . $normalizedScript;
}
