<?php

declare(strict_types=1);

require_once dirname(__DIR__) . '/core/helpers.php';
require_once dirname(__DIR__) . '/modules/notifications/helpers.php';

function public_navigation(): array
{
    return [
        ['label' => 'Home', 'path' => 'app/public/index.php'],
        ['label' => 'Fixtures', 'path' => 'app/public/fixtures.php'],
        ['label' => 'Results', 'path' => 'app/public/results.php'],
        ['label' => 'Table', 'path' => 'app/public/table.php'],
        ['label' => 'Clubs', 'path' => 'app/public/clubs.php'],
        ['label' => 'Players', 'path' => 'app/public/players.php'],
        ['label' => 'News', 'path' => 'app/public/news.php'],
        ['label' => 'Gallery', 'path' => 'app/public/gallery.php'],
    ];
}

function public_tracking_is_supported(): bool
{
    static $supported = null;

    if ($supported !== null) {
        return $supported;
    }

    try {
        $supported = db_fetch_value("SHOW TABLES LIKE 'site_visits'", [], '') !== '';
    } catch (Throwable) {
        $supported = false;
    }

    return $supported;
}

function public_tracking_should_log_request(): bool
{
    if (PHP_SAPI === 'cli') {
        return false;
    }

    if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'GET') {
        return false;
    }

    $scriptName = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));

    if ($scriptName === '' || str_ends_with($scriptName, '/match-share-image.php')) {
        return false;
    }

    if (!empty($_SESSION['user_id'])) {
        return false;
    }

    if (public_tracking_is_internal_ip((string) ($_SERVER['REMOTE_ADDR'] ?? ''))) {
        return false;
    }

    if (public_tracking_is_bot_user_agent((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''))) {
        return false;
    }

    return public_tracking_is_supported();
}

function public_tracking_is_internal_ip(string $ipAddress): bool
{
    $ipAddress = trim($ipAddress);

    if ($ipAddress === '') {
        return false;
    }

    if (in_array($ipAddress, ['127.0.0.1', '::1'], true)) {
        return true;
    }

    if (str_starts_with($ipAddress, '10.') || str_starts_with($ipAddress, '192.168.')) {
        return true;
    }

    if (preg_match('/^172\.(1[6-9]|2[0-9]|3[0-1])\./', $ipAddress) === 1) {
        return true;
    }

    $lowerIp = strtolower($ipAddress);

    return str_starts_with($lowerIp, 'fc') || str_starts_with($lowerIp, 'fd') || str_starts_with($lowerIp, 'fe80:');
}

function public_tracking_is_bot_user_agent(string $userAgent): bool
{
    $userAgent = strtolower(trim($userAgent));

    if ($userAgent === '') {
        return false;
    }

    return preg_match('/bot|crawl|spider|slurp|preview|headless|facebookexternalhit|whatsapp|telegrambot|discordbot|curl|wget|python-requests|axios|postmanruntime/', $userAgent) === 1;
}

function public_tracking_visitor_token(): string
{
    $cookieName = 'jlfc_vid';
    $token = trim((string) ($_COOKIE[$cookieName] ?? ''));

    if ($token === '') {
        try {
            $token = bin2hex(random_bytes(16));
        } catch (Throwable) {
            $token = sha1(uniqid('jlfc', true));
        }
    }

    if (!headers_sent()) {
        setcookie($cookieName, $token, [
            'expires' => time() + (86400 * 365),
            'path' => '/',
            'domain' => '',
            'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }

    $_COOKIE[$cookieName] = $token;

    return $token;
}

function public_tracking_request_path(): string
{
    $requestUri = (string) ($_SERVER['REQUEST_URI'] ?? '/');
    $path = parse_url($requestUri, PHP_URL_PATH);

    if (!is_string($path) || $path === '') {
        return '/';
    }

    return $path;
}

function public_tracking_log_visit(): void
{
    static $logged = false;

    if ($logged || !public_tracking_should_log_request()) {
        return;
    }

    $logged = true;

    $visitorToken = public_tracking_visitor_token();
    $ipAddress = trim((string) ($_SERVER['REMOTE_ADDR'] ?? ''));
    $referrer = trim((string) ($_SERVER['HTTP_REFERER'] ?? ''));
    $userAgent = trim((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
    $path = public_tracking_request_path();

    try {
        db_query(
            'INSERT INTO site_visits (visitor_key, path, query_string, referrer, user_agent, ip_hash, visited_at)
             VALUES (:visitor_key, :path, :query_string, :referrer, :user_agent, :ip_hash, NOW())',
            [
                'visitor_key' => hash('sha256', $visitorToken),
                'path' => substr($path, 0, 190),
                'query_string' => substr((string) ($_SERVER['QUERY_STRING'] ?? ''), 0, 255),
                'referrer' => $referrer !== '' ? substr($referrer, 0, 255) : null,
                'user_agent' => $userAgent !== '' ? substr($userAgent, 0, 255) : null,
                'ip_hash' => $ipAddress !== '' ? hash('sha256', $ipAddress) : null,
            ]
        );
    } catch (Throwable) {
        return;
    }
}

public_tracking_log_visit();

function render_public_notification_prompt(): void
{
    if (!web_push_enabled()) {
        return;
    }

    $publicKey = web_push_public_key();
    if ($publicKey === '') {
        return;
    }
?>
    <section
        class="web-push-prompt"
        data-web-push-prompt
        data-public-key="<?php echo e($publicKey); ?>"
        data-subscribe-url="<?php echo e(web_push_subscribe_url()); ?>"
        data-service-worker-url="<?php echo e(web_push_service_worker_url()); ?>"
        data-service-worker-scope="<?php echo e(base_url('app/public/')); ?>"
        hidden>
        <div class="web-push-prompt-copy">
            <span class="eyebrow mb-1 d-block">Live alerts</span>
            <strong>Enable JLFC notifications</strong>
            <p class="mb-0">Get breaking news, verified match reports, and public league updates in your browser after you allow notifications.</p>
        </div>
        <div class="web-push-prompt-actions">
            <button class="btn btn-jlfc btn-sm" type="button" data-web-push-enable>Enable alerts</button>
            <button class="btn btn-outline-jlfc btn-sm" type="button" data-web-push-dismiss>Maybe later</button>
        </div>
        <div class="web-push-prompt-state text-muted small" data-web-push-state></div>
    </section>
<?php
}

function render_public_page(string $title, string $lead, callable $contentRenderer, array $meta = []): void
{
    $leagueLogoPath = league_logo_path();
    $metaDescription = (string) ($meta['description'] ?? 'JLFC public league portal for Jalingo Local Football Council.');
    $metaUrl = (string) ($meta['url'] ?? current_absolute_url());
    $metaImage = $meta['image'] ?? ($leagueLogoPath !== null ? absolute_url($leagueLogoPath) : null);
    $metaType = (string) ($meta['type'] ?? 'website');
?>
    <!doctype html>
    <html lang="en">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=0.4">
        <meta name="description" content="<?php echo e($metaDescription); ?>">
        <link rel="canonical" href="<?php echo e($metaUrl); ?>">
        <meta property="og:type" content="<?php echo e($metaType); ?>">
        <meta property="og:title" content="<?php echo e($title . ' - ' . league_short_name()); ?>">
        <meta property="og:description" content="<?php echo e($metaDescription); ?>">
        <meta property="og:url" content="<?php echo e($metaUrl); ?>">
        <meta property="og:site_name" content="<?php echo e(league_short_name()); ?>">
        <?php if ($metaImage !== null && $metaImage !== ''): ?>
            <meta property="og:image" content="<?php echo e((string) $metaImage); ?>">
            <meta property="og:image:alt" content="<?php echo e($title); ?>">
            <meta property="og:image:width" content="1200">
            <meta property="og:image:height" content="630">
            <meta name="twitter:card" content="summary_large_image">
            <meta name="twitter:image" content="<?php echo e((string) $metaImage); ?>">
        <?php else: ?>
            <meta name="twitter:card" content="summary">
        <?php endif; ?>
        <meta name="twitter:title" content="<?php echo e($title . ' - ' . league_short_name()); ?>">
        <meta name="twitter:description" content="<?php echo e($metaDescription); ?>">
        <title><?php echo e($title); ?> - <?php echo e(league_short_name()); ?></title>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@500;600;700&family=DM+Sans:wght@400;500;700&display=swap" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
        <link href="<?php echo e(asset_url('css/app.css')); ?>" rel="stylesheet">
    </head>

    <body class="public-body">
        <header class="public-hero">
            <div class="container py-4 py-lg-5">
                <nav class="navbar navbar-expand-lg navbar-dark px-0 mb-4">
                    <div class="container-fluid px-0">
                        <a class="navbar-brand fw-bold" href="<?php echo e(base_url('app/public/index.php')); ?>">
                            <?php if ($leagueLogoPath !== null): ?>
                                <img class="navbar-brand-logo" src="<?php echo e(base_url($leagueLogoPath)); ?>" alt="<?php echo e(league_short_name()); ?> logo">
                            <?php endif; ?>
                            <span><?php echo e(league_short_name()); ?></span>
                        </a>
                        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#publicNav" aria-controls="publicNav" aria-expanded="false" aria-label="Toggle navigation">
                            <span class="navbar-toggler-icon"></span>
                        </button>
                        <div class="collapse navbar-collapse" id="publicNav">
                            <ul class="navbar-nav ms-auto gap-lg-2">
                                <?php foreach (public_navigation() as $item): ?>
                                    <li class="nav-item"><a class="nav-link" href="<?php echo e(base_url($item['path'])); ?>"><?php echo e($item['label']); ?></a></li>
                                <?php endforeach; ?>
                                <li class="nav-item"><a class="nav-link" href="<?php echo e(base_url('app/public/index.php?login=1')); ?>">Admin</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>
                <div class="row g-4 align-items-end">
                    <div class="col-lg-8">
                        <span class="hero-pill mb-3 d-inline-flex">
                            <?php if ($leagueLogoPath !== null): ?>
                                <img class="hero-pill-logo" src="<?php echo e(base_url($leagueLogoPath)); ?>" alt="<?php echo e(league_short_name()); ?> logo">
                            <?php else: ?>
                                <i class="bi bi-trophy"></i>
                            <?php endif; ?>
                            <?php echo e(league_short_name()); ?>
                        </span>
                        <h1 class="display-5 fw-bold mb-3"><?php echo e($title); ?></h1>
                        <p class="lead text-white-50 mb-0"><?php echo e($lead); ?></p>
                    </div>
                    <div class="col-lg-4">
                        <div class="public-badge-card">
                            <span class="eyebrow mb-2">Organization</span>
                            <h2 class="h4 mb-2"><?php echo e(organization_name()); ?></h2>
                            <p class="mb-0 text-white-50">JLFC football management engine foundation.</p>
                        </div>
                    </div>
                </div>
            </div>
        </header>
        <main class="container py-5">
            <?php $contentRenderer(); ?>
        </main>
        <footer class="container pb-5 text-muted small">
            <?php echo e(league_short_name()); ?> &middot; <?php echo e(organization_name()); ?>
        </footer>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
        <?php render_public_notification_prompt(); ?>
        <script src="<?php echo e(asset_url('js/app.js')); ?>"></script>
    </body>

    </html>
<?php
}
