<?php
// This bootstrap file gives us access to the database, models, and config.
// It's crucial to start the session before any HTML output.
require_once dirname(__DIR__, 2) . '/core/bootstrap.php';

// --- Front-end Protection ---
// If a user is logged in and has an admin-only role, they should not be on the front-end.
// Log them out and redirect to the login page to enforce separation.
// if (isset($_SESSION['user_role'])) {
//     $admin_roles = ['super_admin', 'admin', 'league_manager', 'fixtures_manager'];
//     if (in_array($_SESSION['user_role'], $admin_roles, true)) {
//         // This user belongs in the backend. Destroy the session and redirect to login.
//         header('Location: /smart_football/app/logout.php');
//         exit();
//     }
// }

// Fetch application-wide settings
$settingModel = new Setting();
$settings = $settingModel->getAll();

$appName = $settings['app_name'] ?? 'Smart Football';
$appLogo = $settings['app_logo'] ?? URL_ROOT . '/app/assets/images/default-logo.png'; // Provide a default
$primaryColor = $settings['primary_color'] ?? '#2c3e50';
$secondaryColor = $settings['secondary_color'] ?? '#3498db';

// --- Dynamic League Branding ---
// Check if a specific league is in focus (passed from page or URL)
$header_league_id = isset($league_id) ? $league_id : filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);

if ($header_league_id) {
    $leagueModelHeader = new League();
    $headerLeague = $leagueModelHeader->getById($header_league_id);
    if ($headerLeague) {
        $appName = $headerLeague->name;
        if (!empty($headerLeague->logo)) {
            $appLogo = $headerLeague->logo;
        }
    }
}

// Fetch notifications if logged in
$unread_notifications = [];
$currentUser = null;
if (isset($_SESSION['user_id'])) {
    $notificationModel = new Notification();
    $unread_notifications = $notificationModel->getUnreadByUserId($_SESSION['user_id']);
    $userModel = new User();
    $currentUser = $userModel->getFullUserDetailsById($_SESSION['user_id']);
}

// --- Check for League Sponsor ---
$leagueSponsor = null;
if ($header_league_id) {
    $sponsorModel = new Sponsorship();
    $leagueSponsor = $sponsorModel->getActiveLeagueSponsor($header_league_id);
    
    if ($leagueSponsor && !isset($leagueSponsor->business_name) && isset($leagueSponsor->user_id)) {
        $db = new Database();
        $db->query("SELECT business_name FROM sponsor_profiles WHERE user_id = :uid");
        $db->bind(':uid', $leagueSponsor->user_id);
        $prof = $db->single();
        if ($prof) $leagueSponsor->business_name = $prof->business_name;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($pageTitle) ? htmlspecialchars($pageTitle) . ' | ' : ''; ?><?php echo htmlspecialchars($appName); ?></title>    
    <link rel="stylesheet" href="<?php echo URL_ROOT; ?>/app/assets/css/style.css">
    <!-- PWA Manifest & Theme -->
    <meta name="theme-color" content="<?php echo $primaryColor; ?>">
    <link rel="manifest" href="<?php echo URL_ROOT; ?>/app/manifest.json">
    <link rel="apple-touch-icon" href="<?php echo URL_ROOT; ?>/app/assets/images/icons/icon-192x192.png">

    <!-- Add Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="<?php echo URL_ROOT; ?>/app/assets/css/theme.css.php">
    <script>
        const SITE_URL = "<?php echo URL_ROOT; ?>";
    </script>
    <style>
        /* Modern Header & Footer Styles */
        :root {
            --primary-color: <?php echo $primaryColor; ?>;
            --secondary-color: <?php echo $secondaryColor; ?>;
            --accent-color: #e90052;
            --hero-gradient: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
            --header-height: 70px;
            --bottom-nav-height: 70px;
            --glass-bg: rgba(255, 255, 255, 0.95);
            --glass-border: 1px solid rgba(0, 0, 0, 0.05);
            --shadow-sm: 0 4px 20px rgba(0,0,0,0.05);
            
            /* Light Mode Variables */
            --bg-color: #f8f9fa;
            --text-color: #333;
            --card-bg: #ffffff;
            --border-color: #e0e0e0;
            --nav-bg: rgba(255, 255, 255, 0.98);
        }

        /* Dark Mode Variables */
        [data-theme="dark"] {
            --bg-color: #121212;
            --text-color: #e0e0e0;
            --card-bg: #1e1e1e;
            --border-color: #333;
            --glass-bg: rgba(0, 0, 0, 0.95);
            --glass-border: 1px solid rgba(255, 255, 255, 0.05);
            --nav-bg: rgba(30, 30, 30, 0.98);
            --shadow-sm: 0 4px 20px rgba(0,0,0,0.5);
            --table-stripe-bg: rgba(255, 255, 255, 0.03);
            --table-hover-bg: rgba(255, 255, 255, 0.05);
        }

        body {
            padding-top: var(--header-height);
            padding-bottom: var(--bottom-nav-height);
            background-color: var(--bg-color);
            color: var(--text-color);
            margin: 0;
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
            transition: background-color 0.3s, color 0.3s;
        }

        /* Header */
        .main-header {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: var(--header-height);
            background: var(--glass-bg);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border-bottom: var(--glass-border);
            z-index: 1000;
            display: flex;
            align-items: center;
            box-shadow: var(--shadow-sm);
            transition: all 0.3s ease;
        }
        
        /* Header for non-hero pages */
        body:not(.has-hero) .main-header {
            background: var(--primary-color);
            border-bottom: none;
            color: #fff;
        }
        
        body:not(.has-hero) .main-header .logo {
            color: #fff;
        }
        
        body:not(.has-hero) .icon-btn {
            color: #fff;
        }
        
        /* Dynamic Header for Hero Pages */
        body.has-hero .main-header {
            position: absolute;
            background: transparent;
            box-shadow: none;
            border-bottom: none;
            color: white;
        }
        
        body.has-hero .main-header .logo h1 {
            color: white;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .header-container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 12px;
            text-decoration: none;
            color: var(--primary-color);
        }

        .logo img {
            height: 55px;
            width: auto;
            filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
        }

        .logo h1 {
            font-size: 1.4rem;
            font-weight: 800;
            margin: 0;
            letter-spacing: -0.5px;
            display: none;
        }

        .header-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        /* Notification Styles */
        .notification-wrapper { position: relative; }
        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: var(--accent-color);
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 0.7rem;
            font-weight: bold;
        }
        .notification-dropdown {
            position: absolute;
            top: 100%;
            right: 0;
            width: 300px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            display: none;
            z-index: 1001;
            max-height: 400px;
            overflow-y: auto;
        }
        .notification-dropdown.show { display: block; }
        .notification-item {
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
            font-size: 0.9rem;
            cursor: pointer;
            transition: background 0.2s;
        }
        .notification-item:hover { background: var(--bg-color); }
        .notification-item.unread { font-weight: 600; border-left: 3px solid var(--accent-color); }
        .notification-empty { padding: 15px; text-align: center; color: #777; }

        .icon-btn {
            background: transparent;
            border: none;
            font-size: 1.4rem;
            color: inherit;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: background 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .icon-btn:hover {
            background: rgba(0,0,0,0.05);
        }
        
        body.has-hero .icon-btn:hover {
            background: rgba(255,255,255,0.15);
        }

        /* Adjust main container */
        main.container {
            width: 100%;
            max-width: none;
            margin: 0;
            padding: 0;
            min-height: calc(100vh - var(--header-height) - var(--bottom-nav-height));
        }

        /* Constrain content width for standard pages */
        .page-content, .dashboard-view, .container-fluid {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Remove padding top for hero pages so hero goes under header */
        body.has-hero main.container {
            padding-top: 0;
            margin-top: calc(var(--header-height) * -1); /* Pull content up */
        }
        
        /* Fix for hero sections to handle the pull up */
        body.has-hero .dashboard-hero,
        body.has-hero .match-hero,
        body.has-hero .player-hero,
        body.has-hero .matches-hero,
        body.has-hero .fantasy-hero-wrapper {
            padding-top: calc(var(--header-height) + 25px);
        }

        /* Common Component Styles for Dark Mode Compatibility */
        .dashboard-section, .match-detail-section, .player-section-card, .card-shadow, .modal-content, .league-item, .transfers-panel, .league-action-card, .receipt-container, .card, .package-card, .stat-card, .fixture-item, .search-card, .achievement-card, .match-summary-card, .gameweek-nav {
            background-color: var(--card-bg) !important;
            color: var(--text-color) !important;
            border-color: var(--border-color) !important;
        }
        
        .table-wrapper table {
            color: var(--text-color);
        }
        
        .styled-table thead tr {
            background-color: var(--bg-color) !important;
            color: var(--text-color) !important;
        }
        
        .styled-table tbody tr {
            border-bottom-color: var(--border-color) !important;
        }
        
        .styled-table tbody tr:hover {
            background-color: var(--bg-color) !important;
        }
        
        /* Dark Mode Table Striping & Elements Override */
        [data-theme="dark"] .styled-table tbody tr:nth-of-type(even) {
            background-color: var(--table-stripe-bg) !important;
        }
        [data-theme="dark"] .styled-table tbody tr:hover {
            background-color: var(--table-hover-bg) !important;
        }
        [data-theme="dark"] .score-box {
            background-color: rgba(255, 255, 255, 0.1) !important;
            color: var(--text-color) !important;
            border-color: rgba(255, 255, 255, 0.1) !important;
        }
        [data-theme="dark"] .score-box .score {
            color: var(--text-color) !important;
        }
        [data-theme="dark"] .sub-tab-link {
            background-color: rgba(255, 255, 255, 0.1) !important;
            color: var(--text-color) !important;
        }
        [data-theme="dark"] .sub-tab-link.active {
            background-color: var(--primary-color) !important;
            color: #fff !important;
        }
        [data-theme="dark"] .match-scorers,
        [data-theme="dark"] .stats-row {
            border-color: var(--border-color) !important;
        }

        /* Improved Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.6);
            backdrop-filter: blur(4px);
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .modal.show {
            display: flex;
            opacity: 1;
        }
        .modal-content {
            background-color: var(--card-bg);
            margin: auto;
            padding: 25px;
            border: 1px solid var(--border-color);
            width: 90%;
            max-width: 500px;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            transform: scale(0.9);
            transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            color: var(--text-color);
        }
        .modal.show .modal-content {
            transform: scale(1);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--border-color);
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        .modal-header h3 { margin: 0; font-size: 1.25rem; font-weight: 700; }
        .modal-close-btn { background: none; border: none; font-size: 1.5rem; cursor: pointer; color: var(--text-color); opacity: 0.7; transition: opacity 0.2s; }
        .modal-close-btn:hover { opacity: 1; }

        /* Header Search Bar */
        .header-search {
            display: flex;
            align-items: center;
            background: rgba(0, 0, 0, 0.05);
            padding: 5px 15px;
            border-radius: 20px;
            margin-left: 15px;
            margin-right: auto;
            border: 1px solid transparent;
            transition: all 0.3s ease;
        }
        .header-search input {
            background: transparent;
            border: none;
            color: inherit;
            padding: 5px;
            outline: none;
            font-size: 0.9rem;
            width: 200px;
        }
        .header-search button { background: transparent; border: none; color: inherit; cursor: pointer; padding: 5px; opacity: 0.7; }
        body:not(.has-hero) .header-search { background: rgba(255, 255, 255, 0.15); color: white; }
        body:not(.has-hero) .header-search input::placeholder { color: rgba(255, 255, 255, 0.7); }
        body.has-hero .header-search { background: rgba(255, 255, 255, 0.15); color: white; border-color: rgba(255, 255, 255, 0.2); }
        body.has-hero .header-search input::placeholder { color: rgba(255, 255, 255, 0.8); }
        [data-theme="dark"] .header-search { background: rgba(255, 255, 255, 0.05); border-color: rgba(255, 255, 255, 0.1); }
        @media (max-width: 768px) {
            .header-search {
                background: transparent !important;
                padding: 5px;
                border: none !important;
            }
            .header-search input {
                width: 0;
                padding: 0;
                opacity: 0;
                pointer-events: none;
                transition: all 0.3s ease;
            }
            .header-search.expanded {
                background: rgba(255, 255, 255, 0.15) !important;
                padding: 5px 15px;
                border: 1px solid rgba(255,255,255,0.2) !important;
                border-radius: 20px;
            }
            .header-search.expanded input { width: 160px; padding: 5px; opacity: 1; pointer-events: auto; }
        }

        /* --- Global Form Styles --- */
        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="number"],
        input[type="date"],
        input[type="datetime-local"],
        select,
        textarea {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background-color: var(--card-bg);
            color: var(--text-color);
            font-size: 1rem;
            transition: border-color 0.2s, box-shadow 0.2s;
            box-sizing: border-box; /* Ensure padding doesn't affect width */
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="password"]:focus,
        input[type="number"]:focus,
        input[type="date"]:focus,
        input[type="datetime-local"]:focus,
        select:focus,
        textarea:focus {
            border-color: var(--secondary-color);
            outline: none;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1); /* Using secondary color logic */
        }

        /* Checkboxes & Radios */
        input[type="checkbox"],
        input[type="radio"] {
            accent-color: var(--secondary-color);
            width: 18px;
            height: 18px;
            cursor: pointer;
            vertical-align: middle;
        }

        /* Form Labels */
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--text-color);
            font-size: 0.95rem;
        }

        /* New Account Dropdown Styles */
        .account-menu-wrapper {
            position: relative;
        }
        .header-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid rgba(255,255,255,0.5);
            cursor: pointer;
        }
        body:not(.has-hero) .header-avatar {
            border-color: rgba(255,255,255,0.8);
        }
        .account-dropdown {
            position: absolute;
            top: calc(100% + 15px);
            right: 0;
            width: 320px;
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
            border: 1px solid var(--border-color);
            overflow: hidden;
            z-index: 1001;
            display: none;
            opacity: 0;
            transform: translateY(10px);
            transition: opacity 0.2s ease, transform 0.2s ease;
        }
        .account-dropdown.show {
            display: block;
            opacity: 1;
            transform: translateY(0);
        }
        .account-dropdown-header {
            background: var(--hero-gradient);
            padding: 20px;
            display: flex;
            align-items: center;
            gap: 15px;
            color: white;
        }
        .dropdown-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid white;
        }
        .dropdown-user-info strong {
            display: block;
            font-size: 1.1rem;
        }
        .dropdown-user-info span {
            font-size: 0.85rem;
            opacity: 0.8;
            text-transform: capitalize;
        }
        .account-dropdown-actions {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            padding: 15px;
            border-bottom: 1px solid var(--border-color);
        }
        .dropdown-action-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 5px;
            padding: 10px;
            border-radius: 8px;
            background: var(--bg-color);
            color: var(--text-color);
            text-decoration: none;
            font-size: 0.75rem;
            border: none;
            cursor: pointer;
            position: relative; /* For notification badge */
        }
        .dropdown-action-item:hover {
            background: var(--border-color);
        }
        .dropdown-action-item i {
            font-size: 1.2rem;
        }
        .account-dropdown-menu {
            max-height: 40vh;
            overflow-y: auto;
        }
    </style>
</head>
<body class="<?php echo (in_array(basename($_SERVER['PHP_SELF']), ['index.php', 'fixture.php', 'player.php', 'matches.php', 'compare_players.php', 'fantasy_lineup.php', 'live_scorer.php', 'my_team.php', 'my_club.php', 'fantasy.php', 'fantasy_leagues.php', 'fantasy_league_view.php', 'staff_members.php', 'club_finances.php', 'teams.php', 'club_members.php', 'club_membership_packages.php', 'club_transfers.php', 'memberships.php', 'payment_history.php', 'wallet.php'])) ? 'has-hero' : ''; ?>">
    <header class="main-header">
        <div class="header-container">
            <a href="<?php echo URL_ROOT; ?>/app/index.php" class="logo">
                <img src="<?php echo htmlspecialchars($appLogo); ?>" alt="<?php echo htmlspecialchars($appName); ?> Logo">
                <h1><?php echo htmlspecialchars($appName); ?></h1>
            </a>
            
            <div class="header-center-content" style="display: flex; align-items: center; gap: 20px; position: absolute; left: 50%; transform: translateX(-50%);">
                 <?php if ($leagueSponsor): ?>
                    <div class="league-sponsor sponsor-ad" data-campaign-id="<?php echo $leagueSponsor->id; ?>" style="background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%); padding: 5px 15px; border-radius: 8px; display: flex; align-items: center; gap: 10px; color: white; cursor: pointer; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
                        <img src="<?php echo htmlspecialchars($leagueSponsor->ad_content); ?>" alt="Sponsor" style="height: 35px; width: auto; background: rgba(255,255,255,0.95); padding: 2px; border-radius: 4px; object-fit: contain;">
                        <div style="line-height: 1.1;">
                            <small style="display: block; font-size: 0.6rem; opacity: 0.9; text-transform: uppercase; letter-spacing: 0.5px;">Sponsored By</small>
                            <span style="font-weight: 700; font-size: 0.9rem;"><?php echo htmlspecialchars($leagueSponsor->business_name ?? 'Partner'); ?></span>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <div class="header-actions" style="margin-left: auto;">
                <?php if ($currentUser): ?>
                    <div class="account-menu-wrapper">
                        <button id="header-account-trigger" class="icon-btn" style="position: relative;">
                            <img src="<?php echo htmlspecialchars($currentUser->profile_picture ?? URL_ROOT . '/app/assets/images/default_avatar.png'); ?>" class="header-avatar">
                            <?php if (count($unread_notifications) > 0): ?>
                                <span class="notification-badge" style="top: -2px; right: -2px; width: 18px; height: 18px; font-size: 0.7rem; border: 2px solid #fff; display: flex; align-items: center; justify-content: center;"><?php echo count($unread_notifications); ?></span>
                            <?php endif; ?>
                        </button>
                    </div>
                <?php else: ?>
                    <a href="<?php echo URL_ROOT; ?>/app/login.php" class="btn btn-sm btn-primary" style="background: var(--accent-color); color: white; padding: 8px 16px; border-radius: 20px; text-decoration: none; font-weight: 600;">Login</a>
                <?php endif; ?>
            </div>
        </div>
    </header>
    <main class="container">
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // --- Mobile Search Expansion ---
            const searchForm = document.querySelector('.header-search');
            if (searchForm) {
                const searchInput = searchForm.querySelector('input');
                const searchBtn = searchForm.querySelector('button');

                searchBtn.addEventListener('click', function(e) {
                    if (window.innerWidth <= 768) {
                        if (!searchForm.classList.contains('expanded')) {
                            e.preventDefault();
                            searchForm.classList.add('expanded');
                            searchInput.focus();
                        }
                    }
                });

                searchInput.addEventListener('blur', function() {
                    if (window.innerWidth <= 768 && this.value.trim() === '') {
                        // Delay to allow click events (like form submit) to process if needed
                        setTimeout(() => searchForm.classList.remove('expanded'), 200);
                    }
                });
            }

            // --- PWA Service Worker Registration ---
            if ('serviceWorker' in navigator) {
                window.addEventListener('load', () => {
                    navigator.serviceWorker.register('<?php echo URL_ROOT; ?>/app/sw.js')
                    .then(registration => {
                        console.log('ServiceWorker registration successful with scope: ', registration.scope);
                    })
                    .catch(error => {
                        console.log('ServiceWorker registration failed: ', error);
                    });
                });
            }

            // --- Push Notification Logic ---
            window.subscribeToPush = async function() {
                if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
                    alert('Push notifications are not supported in this browser.');
                    return;
                }
                
                const registration = await navigator.serviceWorker.ready;
                
                // TODO: Replace with your actual VAPID Public Key generated on the server
                const publicVapidKey = '<?php echo defined("VAPID_PUBLIC_KEY") ? VAPID_PUBLIC_KEY : ""; ?>';

                if (!publicVapidKey) {
                    console.warn('VAPID Public Key not configured in code.');
                    alert('System Error: Push notifications are not configured.');
                    return;
                }

                try {
                    const subscription = await registration.pushManager.subscribe({
                        userVisibleOnly: true,
                        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
                    });
                    
                    // Send subscription to backend
                    await fetch('<?php echo URL_ROOT; ?>/app/api/save_subscription.php', {
                        method: 'POST',
                        body: JSON.stringify(subscription),
                        headers: { 'Content-Type': 'application/json' }
                    });
                    
                    alert('Successfully subscribed to notifications!');
                } catch (error) {
                    console.error('Failed to subscribe:', error);
                    alert('Failed to subscribe. You may have blocked notifications.');
                }
            };

            function urlBase64ToUint8Array(base64String) {
                const padding = '='.repeat((4 - base64String.length % 4) % 4);
                const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
                const rawData = window.atob(base64);
                const outputArray = new Uint8Array(rawData.length);
                for (let i = 0; i < rawData.length; ++i) {
                    outputArray[i] = rawData.charCodeAt(i);
                }
                return outputArray;
            }

            // --- Sponsor Ad Tracking ---
            const ads = document.querySelectorAll('.sponsor-ad');
            if (ads.length > 0 && 'IntersectionObserver' in window) {
                const observer = new IntersectionObserver((entries) => {
                    entries.forEach(entry => {
                        if (entry.isIntersecting) {
                            const ad = entry.target;
                            const campaignId = ad.dataset.campaignId;
                            if (campaignId && !ad.dataset.viewed) {
                                trackAdAction(campaignId, 'view');
                                ad.dataset.viewed = 'true';
                                observer.unobserve(ad);
                            }
                        }
                    });
                }, { threshold: 0.5 });

                ads.forEach(ad => {
                    observer.observe(ad);
                    ad.addEventListener('click', function() {
                        const campaignId = this.dataset.campaignId;
                        if (campaignId) trackAdAction(campaignId, 'click');
                        
                        // Handle Target URL or Contact Number
                        // We need to fetch these details. For now, let's assume they are data attributes if available,
                        // or we fetch them via the trackAdAction response.
                        // A simpler way is to reload the page or open a new tab if the ad element has an href.
                        // But since they are divs, we check data attributes.
                        
                        // Note: To make this work, the ad rendering logic in other files needs to output these data attributes.
                        // However, since I cannot modify all view files in this turn, I will rely on the fact that
                        // trackAdAction is async.
                        
                        // If the ad element is an anchor tag (which I updated in some views), it handles itself.
                        // If it's a div (like in matches.php), we need JS.
                        
                        // Ideally, the ad rendering should wrap in <a> tags.
                        // Since I can't change matches.php now, I will assume future updates will handle the linking structure
                        // or the user will click the link provided in the ad content if it's text-based (which it isn't).
                    });
                });
            }

            function trackAdAction(campaignId, action) {
                fetch('<?php echo URL_ROOT; ?>/app/api/track_ad.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ campaign_id: campaignId, action: action })
                })
                .then(res => res.json())
                .then(data => {
                    if (action === 'click' && data.target_url) {
                        window.open(data.target_url, '_blank');
                    } else if (action === 'click' && data.contact_number) {
                        window.location.href = 'tel:' + data.contact_number;
                    }
                })
                .catch(err => console.error('Ad tracking error:', err));
            }
        });
    </script>