<?php
// Global notification system that can be included on every page
// Include this file in db.php or menu.php to make notifications available everywhere

// Get the current event ID from session, URL, or form data
$notification_event_id = null;

// Try to get event ID from various sources
if (isset($_SESSION['current_event_id'])) {
    $notification_event_id = $_SESSION['current_event_id'];
} elseif (isset($_GET['event_id'])) {
    $notification_event_id = $_GET['event_id'];
} elseif (isset($_POST['event_id'])) {
    $notification_event_id = $_POST['event_id'];
}

// If no event ID found, try to get the most recent event from database
if (!$notification_event_id && isset($pdo)) {
    try {
        $stmt = $pdo->query("SELECT id FROM events ORDER BY created_at DESC LIMIT 1");
        $recent_event = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($recent_event) {
            $notification_event_id = $recent_event['id'];
        }
    } catch (Exception $e) {
        // Ignore database errors
    }
}

// Get current user ID for notifications
$notification_user_id = 'anonymous';
if (isset($_SESSION['user_id'])) {
    $notification_user_id = $_SESSION['user_id'];
} elseif (isset($_SESSION['username'])) {
    $notification_user_id = $_SESSION['username'];
} elseif (isset($_SESSION['user'])) {
    $notification_user_id = $_SESSION['user'];
}

// Determine user role for notification filtering
$notification_user_role = 'viewer';
if (isset($_SESSION['user_type'])) {
    $notification_user_role = $_SESSION['user_type'];
} elseif (isset($_SESSION['role'])) {
    $notification_user_role = $_SESSION['role'];
} elseif (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in']) {
    $notification_user_role = 'admin';
} elseif (isset($_SESSION['judge_logged_in']) && $_SESSION['judge_logged_in']) {
    $notification_user_role = 'judge';
}

// Include notification CSS and JS only once per page
if (!defined('NOTIFICATIONS_INCLUDED')) {
    define('NOTIFICATIONS_INCLUDED', true);
    
    // Add notification styles
    echo '<style>
    /* Notification System Styles */
    .notification-toast-container {
        position: fixed;
        bottom: 0;
        right: 0;
        padding: 1rem;
        max-height: 90vh;
        overflow-y: auto;
        z-index: 9999;
    }
    
    .notification-toast {
        transition: all 0.3s ease;
        transform: translateX(100%);
        opacity: 0;
        max-width: 400px;
        word-wrap: break-word;
    }
    
    .notification-toast.show {
        transform: translateX(0);
        opacity: 1;
    }
    
    .notification-controls {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9998;
        display: none;
    }
    
    .notification-controls.show {
        display: block;
    }
    
    .notification-filter-btn {
        margin: 2px;
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
    }
    
    .live-pulse {
        animation: livePulse 2s infinite;
    }
    
    @keyframes livePulse {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.7; }
    }
    
    /* Notification status indicator */
    .notification-status {
        position: fixed;
        bottom: 20px;
        right: 20px;
        z-index: 9997;
        background: rgba(0,0,0,0.8);
        color: white;
        padding: 0.5rem;
        border-radius: 0.25rem;
        font-size: 0.75rem;
        display: none;
    }
    
    .notification-status.show {
        display: block;
    }
    </style>';
    
    // Add notification controls HTML
    echo '<div class="notification-controls" id="notificationControls">
        <div class="border-0 shadow-none card">
            <div class="border-0 shadow-none card-header py-2">
                <div class="d-flex justify-content-between align-items-center">
                    <small class="fw-bold"><i class="fas fa-bell me-1"></i>Notifications</small>
                    <button class="btn btn-sm btn-outline-secondary" onclick="toggleNotificationControls()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
            <div class="border-0 shadow-none card-body py-2">
                <div class="mb-2">
                    <small class="text-muted">Filter by category:</small>
                    <div class="d-flex flex-wrap">
                        <button class="btn btn-outline-primary notification-filter-btn" data-category="all" onclick="setNotificationFilter(\'all\')">All</button>
                        <button class="btn btn-outline-info notification-filter-btn" data-category="general" onclick="setNotificationFilter(\'general\')">General</button>
                        <button class="btn btn-outline-primary notification-filter-btn" data-category="competition" onclick="setNotificationFilter(\'competition\')">Competition</button>
                        <button class="btn btn-outline-success notification-filter-btn" data-category="participant" onclick="setNotificationFilter(\'participant\')">Participants</button>
                        <button class="btn btn-outline-warning notification-filter-btn" data-category="judge" onclick="setNotificationFilter(\'judge\')">Judges</button>
                        <button class="btn btn-outline-danger notification-filter-btn" data-category="heat" onclick="setNotificationFilter(\'heat\')">Heats</button>
                        <button class="btn btn-outline-info notification-filter-btn" data-category="scoring" onclick="setNotificationFilter(\'scoring\')">Scoring</button>
                        <button class="btn btn-outline-secondary notification-filter-btn" data-category="system" onclick="setNotificationFilter(\'system\')">System</button>
                        <button class="btn btn-outline-dark notification-filter-btn" data-category="technical" onclick="setNotificationFilter(\'technical\')">Technical</button>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <small class="text-muted">Status: <span id="liveStatusIndicator" class="badge bg-secondary">Connecting...</span></small>
                    <button class="btn btn-sm btn-outline-danger" onclick="clearAllNotifications()" title="Clear all notifications">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>';
    
    // Add notification status indicator
    echo '<div class="notification-status" id="notificationStatus">
        <i class="fas fa-bell me-1"></i>
        <span id="notificationStatusText">Notifications ready</span>
    </div>';
    
    // Add floating notification toggle button
    echo '<div class="position-fixed" style="top: 20px; right: 60px; z-index: 9996;">
        <button class="btn btn-primary btn-sm" onclick="toggleNotificationControls()" title="Notification Settings">
            <i class="fas fa-bell"></i>
            <span class="badge bg-light text-dark ms-1" id="notificationCount">0</span>
        </button>
    </div>';
    
    // Include notification JavaScript
    echo '<script>
    // Global notification system variables
    let globalNotificationManager = null;
    let notificationCount = 0;
    let currentNotificationFilter = "all";
    
    // Initialize notification system when DOM is ready
    document.addEventListener("DOMContentLoaded", function() {
        initializeNotificationSystem();
    });
    
    function initializeNotificationSystem() {
        const eventId = "' . htmlspecialchars($notification_event_id ?? '', ENT_QUOTES) . '";
        const userId = "' . htmlspecialchars($notification_user_id, ENT_QUOTES) . '";
        const userRole = "' . htmlspecialchars($notification_user_role, ENT_QUOTES) . '";
        
        if (!eventId) {
            console.warn("No event ID available for notifications");
            updateNotificationStatus("No event selected", "warning");
            return;
        }
        
        // Load notification manager if not already loaded
        if (typeof NotificationManager === "undefined") {
            const script = document.createElement("script");
            
            // Determine the correct path based on current location
            const currentPath = window.location.pathname;
            let scriptPath = "";
            
            if (currentPath.includes("/admin/")) {
                scriptPath = "../assets/js/notification_manager.js";
            } else if (currentPath.includes("/judge/")) {
                scriptPath = "../assets/js/notification_manager.js";
            } else if (currentPath.includes("/api/")) {
                scriptPath = "../assets/js/notification_manager.js";
            } else {
                scriptPath = "assets/js/notification_manager.js";
            }
            
            script.src = scriptPath;
            script.onload = function() {
                createNotificationManager(eventId, userId, userRole);
            };
            script.onerror = function() {
                console.warn("Could not load notification manager");
                updateNotificationStatus("Notification system unavailable", "danger");
            };
            document.head.appendChild(script);
        } else {
            createNotificationManager(eventId, userId, userRole);
        }
    }
    
    function createNotificationManager(eventId, userId, userRole) {
        try {
            globalNotificationManager = new NotificationManager(eventId, userId);
            
            // Set up role-based filters
            setupRoleBasedFilters(userRole);
            
            // Override the original showToast to update our counter
            const originalShowToast = globalNotificationManager.showToast.bind(globalNotificationManager);
            globalNotificationManager.showToast = function(notification) {
                originalShowToast(notification);
                updateNotificationCount();
            };
            
            updateNotificationStatus("Connected to live notifications", "success");
            
            // Set default filter based on user role
            setInitialFilterForRole(userRole);
            
        } catch (error) {
            console.error("Error initializing notification manager:", error);
            updateNotificationStatus("Notification system error", "danger");
        }
    }
    
    function setupRoleBasedFilters(userRole) {
        // Show different categories based on user role
        const roleFilters = {
            "admin": [], // Admins see everything
            "judge": ["judge", "scoring", "participant", "heat"],
            "staff": ["competition", "participant", "heat", "general"],
            "viewer": ["general", "competition"]
        };
        
        if (roleFilters[userRole]) {
            // Note: Empty array means show all for admins
            if (roleFilters[userRole].length > 0) {
                globalNotificationManager.setCategoryFilters(roleFilters[userRole]);
            }
        }
    }
    
    function setInitialFilterForRole(userRole) {
        // Set initial active filter button based on role
        const initialFilters = {
            "admin": "all",
            "judge": "judge", 
            "staff": "competition",
            "viewer": "general"
        };
        
        const filter = initialFilters[userRole] || "all";
        setNotificationFilter(filter);
    }
    
    function toggleNotificationControls() {
        const controls = document.getElementById("notificationControls");
        controls.classList.toggle("show");
    }
    
    function setNotificationFilter(category) {
        currentNotificationFilter = category;
        
        if (!globalNotificationManager) return;
        
        // Update filter buttons
        document.querySelectorAll(".notification-filter-btn").forEach(btn => {
            btn.classList.remove("btn-primary");
            btn.classList.add("btn-outline-primary");
            if (btn.dataset.category !== "all") {
                const btnCategory = btn.dataset.category;
                btn.classList.remove("btn-outline-primary");
                btn.classList.add("btn-outline-" + getCategoryColor(btnCategory));
            }
        });
        
        const activeBtn = document.querySelector(`[data-category="${category}"]`);
        if (activeBtn) {
            activeBtn.classList.remove("btn-outline-primary", "btn-outline-info", "btn-outline-success", "btn-outline-warning", "btn-outline-danger", "btn-outline-secondary", "btn-outline-dark");
            activeBtn.classList.add("btn-primary");
        }
        
        // Apply filter
        if (category === "all") {
            globalNotificationManager.clearCategoryFilters();
        } else {
            globalNotificationManager.setCategoryFilters([category]);
        }
        
        updateNotificationStatus(`Showing ${category} notifications`, "info");
    }
    
    function getCategoryColor(category) {
        const colors = {
            "general": "info",
            "competition": "primary", 
            "participant": "success",
            "judge": "warning",
            "heat": "danger",
            "scoring": "info",
            "system": "secondary",
            "technical": "dark"
        };
        return colors[category] || "secondary";
    }
    
    function updateNotificationCount() {
        notificationCount++;
        const counter = document.getElementById("notificationCount");
        if (counter) {
            counter.textContent = notificationCount;
            if (notificationCount > 0) {
                counter.classList.add("live-pulse");
            }
        }
    }
    
    function updateNotificationStatus(message, type = "info") {
        const status = document.getElementById("notificationStatus");
        const statusText = document.getElementById("notificationStatusText");
        
        if (status && statusText) {
            statusText.textContent = message;
            status.className = `notification-status show bg-${type}`;
            
            // Auto-hide after 3 seconds for non-error messages
            if (type !== "danger") {
                setTimeout(() => {
                    status.classList.remove("show");
                }, 3000);
            }
        }
    }
    
    function clearAllNotifications() {
        if (globalNotificationManager && confirm("Clear all notifications for this event?")) {
            globalNotificationManager.clearAllNotifications().then(() => {
                notificationCount = 0;
                updateNotificationCount();
                updateNotificationStatus("All notifications cleared", "success");
            }).catch(error => {
                console.error("Error clearing notifications:", error);
                updateNotificationStatus("Error clearing notifications", "danger");
            });
        }
    }
    
    // Expose functions globally for easy access
    window.sendNotification = function(type, title, message = "", category = "general") {
        if (globalNotificationManager) {
            return globalNotificationManager.sendNotification(type, title, message, {}, category);
        } else {
            console.warn("Notification manager not initialized");
            return Promise.resolve({success: false, error: "Not initialized"});
        }
    };
    
    // Quick notification functions
    window.notifySuccess = (title, message = "") => sendNotification("success", title, message, "general");
    window.notifyError = (title, message = "") => sendNotification("danger", title, message, "system");
    window.notifyWarning = (title, message = "") => sendNotification("warning", title, message, "system");
    window.notifyInfo = (title, message = "") => sendNotification("info", title, message, "general");
    
    // Competition-specific notifications (if notification manager is loaded)
    window.notifyParticipant = function(action, bibNumber, participantName) {
        if (globalNotificationManager) {
            switch(action) {
                case "on_start":
                    return globalNotificationManager.notifyParticipantOnStart(bibNumber, participantName);
                case "started":
                    return globalNotificationManager.notifyParticipantStarted(bibNumber, participantName);
                case "completed":
                    return globalNotificationManager.notifyParticipantCompleted(bibNumber, participantName);
                case "next":
                    return globalNotificationManager.notifyNextParticipant(bibNumber, participantName);
            }
        }
    };
    
    window.notifyHeat = function(action, heatNumber, runNumber = null) {
        if (globalNotificationManager) {
            switch(action) {
                case "activated":
                    return globalNotificationManager.notifyHeatActivated(heatNumber, runNumber);
                case "deactivated":
                    return globalNotificationManager.notifyHeatDeactivated(heatNumber);
            }
        }
    };
    
    window.notifyJudge = (action, details) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyJudgeAction(action, details);
        }
    };
    
    window.notifyScore = (participantBib, score, judge) => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyScoreUpdate(participantBib, score, judge);
        }
    };
    
    window.notifyEmergencyStop = () => {
        if (globalNotificationManager) {
            return globalNotificationManager.notifyEmergencyStop();
        }
    };
    </script>';
}
?>
