<?php
declare(strict_types=1);

function app_base_path(): string
{
    $scriptName = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    $basePath = trim(str_replace('\\', '/', dirname(dirname($scriptName))), '/');

    if ($basePath === '' || $basePath === '.') {
        return '';
    }

    return '/' . $basePath;
}

function app_public_path(string $relativePath): string
{
    $normalizedPath = ltrim(str_replace('\\', '/', $relativePath), '/');
    $basePath = app_base_path();

    return ($basePath !== '' ? $basePath : '') . '/' . $normalizedPath;
}

function render_web_app_meta_tags(): string
{
    $faviconSvg = app_public_path('assets/icons/favicon.svg');
    $icon192 = app_public_path('assets/icons/icon-192.png');
    $icon512 = app_public_path('assets/icons/icon-512.png');
    $appleTouchIcon = app_public_path('assets/icons/apple-touch-icon.png');
    $manifest = app_public_path('manifest.webmanifest');

    return implode("\n", array(
        '<link rel="icon" type="image/svg+xml" href="' . e($faviconSvg) . '">',
        '<link rel="icon" type="image/png" sizes="192x192" href="' . e($icon192) . '">',
        '<link rel="icon" type="image/png" sizes="512x512" href="' . e($icon512) . '">',
        '<link rel="apple-touch-icon" sizes="180x180" href="' . e($appleTouchIcon) . '">',
        '<link rel="manifest" href="' . e($manifest) . '">',
        '<meta name="mobile-web-app-capable" content="yes">',
        '<meta name="apple-mobile-web-app-capable" content="yes">',
        '<meta name="apple-mobile-web-app-status-bar-style" content="default">',
        '<meta name="apple-mobile-web-app-title" content="CCW Car Care">',
        '<meta name="application-name" content="CCW Car Care">',
        '<meta name="theme-color" content="#0c2340">',
        '<meta name="format-detection" content="telephone=no">'
    ));
}

function render_web_app_bootstrap_script(): string
{
    $basePath = app_base_path();
    $scopePath = rtrim($basePath !== '' ? $basePath : '/', '/') . '/';
    $config = array(
        'basePath' => $basePath,
        'scope' => $scopePath,
        'serviceWorkerUrl' => app_public_path('service-worker.js'),
        'offlineFallbackUrl' => app_public_path('pages/login.php'),
        'labels' => array(
            'updateTitle' => translate_text('A new version is ready'),
            'updateMessage' => translate_text('Refresh to load the latest version of the app'),
            'updateApply' => translate_text('Refresh now'),
            'updateDismiss' => translate_text('Later'),
            'installTitle' => localized_text_value('ติดตั้ง CCW บนหน้าจอหลัก', 'Install CCW on your home screen'),
            'installMessage' => localized_text_value(
                'เปิดใช้งานแบบแอปได้ทันที เข้าระบบเร็วขึ้นและใช้งานสะดวกขึ้น',
                'Launch it like an app for faster access and a cleaner mobile experience'
            ),
            'installApply' => localized_text_value('ติดตั้งแอป', 'Install app'),
            'installDismiss' => translate_text('Later'),
            'installIosTitle' => localized_text_value('เพิ่ม CCW ไปยังหน้าจอหลัก', 'Add CCW to your home screen'),
            'installIosMessage' => localized_text_value(
                'เปิดเมนู Share ใน Safari แล้วเลือก Add to Home Screen',
                'Open the Share menu in Safari and choose Add to Home Screen'
            ),
            'installIosButton' => localized_text_value('เข้าใจแล้ว', 'Got it'),
            'installAndroidTitle' => localized_text_value('ติดตั้ง CCW บน Android', 'Install CCW on Android'),
            'installAndroidMessage' => localized_text_value(
                'เปิดเมนูของเบราว์เซอร์ แล้วเลือก Install app หรือ Add to Home screen',
                'Open the browser menu and choose Install app or Add to Home screen'
            ),
            'installAndroidButton' => localized_text_value('เข้าใจแล้ว', 'Got it'),
            'installInsecureTitle' => localized_text_value(
                'การติดตั้งแอปถูกจำกัดบนการเชื่อมต่อนี้',
                'Install app is limited on this connection'
            ),
            'installInsecureMessage' => localized_text_value(
                'ให้เปิดเว็บผ่าน HTTPS เพื่อใช้ปุ่มติดตั้งแบบทันที หรือใช้เมนูของเบราว์เซอร์เพื่อเพิ่มไปยังหน้าจอหลัก',
                'Open this site over HTTPS for one-tap install, or use the browser menu to add it to your home screen'
            ),
            'installInsecureButton' => localized_text_value('เข้าใจแล้ว', 'Got it'),
        ),
    );
    $scriptPath = dirname(__DIR__) . '/assets/pwa.js';
    $scriptVersion = is_file($scriptPath) ? (string) filemtime($scriptPath) : '1';
    $scriptUrl = app_public_path('assets/pwa.js') . '?v=' . rawurlencode($scriptVersion);

    return '<script>window.CCW_WEB_APP_CONFIG = ' . json_encode($config, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . ';</script>'
        . "\n"
        . '<script src="' . e($scriptUrl) . '" defer></script>';
}

function storage_upload_directory(string $subdirectory): string
{
    $normalizedSubdirectory = trim(str_replace('\\', '/', $subdirectory), '/');

    return dirname(__DIR__) . '/storage/uploads/' . $normalizedSubdirectory;
}

function storage_upload_public_prefix(string $subdirectory): string
{
    $normalizedSubdirectory = trim(str_replace('\\', '/', $subdirectory), '/');
    $basePath = app_base_path();

    return ($basePath !== '' ? $basePath : '') . '/storage/uploads/' . $normalizedSubdirectory . '/';
}

function storage_upload_absolute_path_from_public(string $publicPath, string $subdirectory): ?string
{
    $normalizedSubdirectory = trim(str_replace('\\', '/', $subdirectory), '/');
    $normalizedPublicPath = str_replace('\\', '/', trim($publicPath));

    if ($normalizedPublicPath === '' || str_contains($normalizedPublicPath, '..')) {
        return null;
    }

    $prefix = storage_upload_public_prefix($normalizedSubdirectory);
    $relativePath = '';

    if ($prefix !== '' && str_starts_with($normalizedPublicPath, $prefix)) {
        $relativePath = substr($normalizedPublicPath, strlen($prefix));
    } else {
        $fallbackPrefix = '/storage/uploads/' . $normalizedSubdirectory . '/';
        $fallbackPosition = strpos($normalizedPublicPath, $fallbackPrefix);

        if ($fallbackPosition === false) {
            return null;
        }

        $relativePath = substr($normalizedPublicPath, $fallbackPosition + strlen($fallbackPrefix));
    }

    $relativePath = ltrim(str_replace('\\', '/', (string) $relativePath), '/');
    if ($relativePath === '' || str_contains($relativePath, '..')) {
        return null;
    }

    $absolutePath = storage_upload_directory($normalizedSubdirectory) . '/' . $relativePath;

    return is_file($absolutePath) ? $absolutePath : null;
}
