<?php
session_start();

// Check if user is logged in as admin
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit();
}

require_once '../includes/db.php';
//require_once '../includes/functions.php';
require_once '../includes/notifications_config.php';

// Test database connection
try {
    if (!isset($pdo) || !$pdo) {
        throw new Exception('PDO connection not available');
    }
    $test_query = $pdo->query("SELECT 1");
    error_log("Database connection test: SUCCESS");
} catch (Exception $e) {
    error_log("Database connection test: FAILED - " . $e->getMessage());
}

// Get current admin user info
$admin_username = $_SESSION['username'] ?? 'admin';
$admin_full_name = $_SESSION['full_name'] ?? $admin_username;
$admin_id = $_SESSION['user_id'] ?? $_SESSION['admin_id'] ?? $_SESSION['id'] ?? null;

// If no admin ID in session, try to get it from the database
if (!$admin_id) {
    try {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ? LIMIT 1");
        $stmt->execute([$admin_username, $admin_username]);
        $admin_user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($admin_user) {
            $admin_id = $admin_user['id'];
        } else {
            // Fallback: use a default admin ID
            $admin_id = 1; // Assuming admin is user ID 1
        }
    } catch (Exception $e) {
        $admin_id = 1; // Fallback to ID 1
    }
}

// Get event list for notifications
$events = [];
try {
    $stmt = $pdo->query("SELECT id, name, date, status FROM events ORDER BY date DESC");
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $events = [];
}

// Get selected event ID
$selected_event_id = $_GET['event_id'] ?? $_POST['event_id'] ?? ($events[0]['id'] ?? null);

// Handle form submissions
$message = '';
$message_type = '';

// Debug: Log all POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("POST request received: " . print_r($_POST, true));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    error_log("Processing action: " . $action);
    
    switch ($action) {
        case 'send_notification':
            $type = $_POST['notification_type'] ?? 'info';
            $category = $_POST['category'] ?? 'general';
            $title = trim($_POST['title'] ?? '');
            $message_text = trim($_POST['message'] ?? '');
            $target_event = $_POST['target_event'] ?? $selected_event_id;
            
            // Debug: Log all POST data
            error_log("POST data received: " . print_r($_POST, true));
            
            if (empty($title)) {
                $message = 'Title is required';
                $message_type = 'danger';
            } elseif (empty($target_event)) {
                $message = 'Event selection is required';
                $message_type = 'danger';
            } else {
                // Debug: Log what we're sending
                error_log("Notification form submission - Event ID: " . $target_event . ", Title: " . $title);
                
                // Use direct database approach instead of API call
                try {
                    // Ensure notifications table exists with more robust approach
                    $table_creation_sql = "
                        CREATE TABLE IF NOT EXISTS event_notifications (
                            id INT AUTO_INCREMENT PRIMARY KEY,
                            event_id INT NOT NULL,
                            type VARCHAR(50) DEFAULT 'info',
                            category VARCHAR(50) DEFAULT 'general',
                            title VARCHAR(255) NOT NULL,
                            message TEXT,
                            user_id VARCHAR(100) DEFAULT 'system',
                            data TEXT,
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
                    ";
                    
                    $pdo->exec($table_creation_sql);
                    error_log("Notification table creation/verification: SUCCESS");
                    
                    // Create notification directly in database
                    $stmt = $pdo->prepare("
                        INSERT INTO event_notifications 
                        (event_id, type, title, message, user_id, category, created_at) 
                        VALUES (?, ?, ?, ?, ?, ?, NOW())
                    ");
                    
                    error_log("Executing INSERT with values: " . json_encode([
                        $target_event, $type, $title, $message_text, 'admin_' . $admin_username, $category
                    ]));
                    
                    $result = $stmt->execute([
                        $target_event,
                        $type,
                        $title,
                        $message_text,
                        'admin_' . $admin_username,
                        $category
                    ]);
                    
                    if ($result) {
                        $notification_id = $pdo->lastInsertId();
                        error_log("Notification created successfully with ID: " . $notification_id);
                        $message = 'Notification sent successfully! (ID: ' . $notification_id . ')';
                        $message_type = 'success';
                    } else {
                        $errorInfo = $stmt->errorInfo();
                        error_log("Database INSERT failed: " . print_r($errorInfo, true));
                        $message = 'Failed to send notification: Database INSERT failed';
                        $message_type = 'danger';
                    }
                    
                } catch (Exception $e) {
                    error_log("Notification creation error: " . $e->getMessage());
                    error_log("Exception trace: " . $e->getTraceAsString());
                    $message = 'Failed to send notification: ' . $e->getMessage();
                    $message_type = 'danger';
                }
            }
            break;
            
        case 'clear_event_notifications':
            $target_event = $_POST['target_event'] ?? $selected_event_id;
            
            // Clear notifications via API
            $api_url = '../api/notification_api.php';
            $post_data = http_build_query([
                'action' => 'clear_all',
                'event_id' => $target_event
            ]);
            
            $context = stream_context_create([
                'http' => [
                    'method' => 'POST',
                    'header' => 'Content-type: application/x-www-form-urlencoded',
                    'content' => $post_data
                ]
            ]);
            
            $result = @file_get_contents($api_url, false, $context);
            $response = json_decode($result, true);
            
            if ($response && $response['success']) {
                $message = 'All notifications cleared for selected event!';
                $message_type = 'success';
            } else {
                $message = 'Failed to clear notifications: ' . ($response['error'] ?? 'Unknown error');
                $message_type = 'danger';
            }
            break;
    }
}

// Get notification statistics
$notification_stats = [];
if ($selected_event_id) {
    try {
        // Get notification counts by category
        $stmt = $pdo->prepare("
            SELECT 
                category,
                type,
                COUNT(*) as count,
                MAX(created_at) as latest
            FROM event_notifications 
            WHERE event_id = ?
            GROUP BY category, type
            ORDER BY category, type
        ");
        $stmt->execute([$selected_event_id]);
        $notification_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get recent notifications
        $stmt = $pdo->prepare("
            SELECT *
            FROM event_notifications 
            WHERE event_id = ?
            ORDER BY created_at DESC
            LIMIT 50
        ");
        $stmt->execute([$selected_event_id]);
        $recent_notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (Exception $e) {
        $notification_stats = [];
        $recent_notifications = [];
    }
}

$page_title = 'Notification Management';
$current_page = 'notifications';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?> - StyleScore Admin</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <!-- Lucide Icons -->
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>
    
    <!-- Custom Styles -->
    <style>
        .notification-category-card {
            border-left: 4px solid;
            transition: all 0.3s ease;
        }
        
        .notification-category-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .category-general { border-left-color: #17a2b8; }
        .category-competition { border-left-color: #007bff; }
        .category-participant { border-left-color: #28a745; }
        .category-judge { border-left-color: #ffc107; }
        .category-heat { border-left-color: #dc3545; }
        .category-scoring { border-left-color: #6f42c1; }
        .category-system { border-left-color: #6c757d; }
        .category-technical { border-left-color: #343a40; }
        
        .notification-preview {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: #f8f9fa;
        }
        
        .notification-type-success { background: linear-gradient(45deg, #d4edda, #c3e6cb); }
        .notification-type-danger { background: linear-gradient(45deg, #f8d7da, #f5c6cb); }
        .notification-type-warning { background: linear-gradient(45deg, #fff3cd, #ffeaa7); }
        .notification-type-info { background: linear-gradient(45deg, #d1ecf1, #bee5eb); }
        
        .stats-card {
            transition: all 0.3s ease;
        }
        
        .stats-card:hover {
            transform: scale(1.02);
        }
        
        .recent-notification {
            border-left: 3px solid;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            background: #f8f9fa;
            border-radius: 0 4px 4px 0;
        }
        
        .notification-time {
            font-size: 0.8rem;
            color: #6c757d;
        }
        
        .live-notification-panel {
            position: sticky;
            top: 20px;
            max-height: calc(100vh - 40px);
            overflow-y: auto;
        }
        
        .send-form-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 1.5rem;
        }
        
        .template-btn {
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .template-btn:hover {
            background-color: #e9ecef;
            transform: translateY(-1px);
        }
    </style>
</head>
<body>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <!-- Alert Messages -->
        <?php if ($message): ?>
            <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : ($message_type === 'danger' ? 'exclamation-triangle' : 'info-circle'); ?> me-2"></i>
                <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <!-- Page Header -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h1 class="h3 mb-0">
                            <i class="fas fa-bell text-primary me-2"></i>
                            Notification Management
                        </h1>
                        <p class="text-muted mb-0">Send and manage system notifications</p>
                    </div>
                    <div>
                        <button type="button" class="btn btn-outline-primary" onclick="testLiveNotifications()">
                            <i class="fas fa-broadcast-tower me-1"></i>
                            Test Live System
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Event Selection -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">
                            <i class="fas fa-calendar-alt text-info me-2"></i>
                            Event Selection
                        </h5>
                        <form method="GET" class="d-flex align-items-center gap-3">
                            <select name="event_id" class="form-select" style="max-width: 300px;" onchange="this.form.submit()">
                                <option value="">Select an event...</option>
                                <?php foreach ($events as $event): ?>
                                    <option value="<?php echo $event['id']; ?>" 
                                            <?php echo $selected_event_id == $event['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($event['name']); ?> 
                                        (<?php echo htmlspecialchars($event['date']); ?>)
                                        - <?php echo ucfirst($event['status'] ?? 'active'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <?php if ($selected_event_id): ?>
                                <span class="badge bg-success">
                                    <i class="fas fa-check me-1"></i>
                                    Event Selected
                                </span>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <?php if ($selected_event_id): ?>
            <div class="row">
                <!-- Left Column: Send Notifications -->
                <div class="col-md-8">
                    <!-- Send Notification Form -->
                    <div class="send-form-container mb-4">
                        <h5 class="mb-3">
                            <i class="fas fa-paper-plane text-primary me-2"></i>
                            Send New Notification
                        </h5>
                        
                        <form id="notificationForm" onsubmit="return false;">
                            <input type="hidden" name="action" value="send_notification">
                            <input type="hidden" name="target_event" value="<?php echo $selected_event_id; ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="notification_type" class="form-label">Type</label>
                                    <select name="notification_type" id="notification_type" class="form-select" onchange="updatePreview()">
                                        <option value="info">Info</option>
                                        <option value="success">Success</option>
                                        <option value="warning">Warning</option>
                                        <option value="danger">Error/Danger</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="category" class="form-label">Category</label>
                                    <select name="category" id="category" class="form-select" onchange="updatePreview()">
                                        <option value="general">General</option>
                                        <option value="competition">Competition</option>
                                        <option value="participant">Participant</option>
                                        <option value="judge">Judge</option>
                                        <option value="heat">Heat</option>
                                        <option value="scoring">Scoring</option>
                                        <option value="system">System</option>
                                        <option value="technical">Technical</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="mt-3">
                                <label for="title" class="form-label">Title <span class="text-danger">*</span></label>
                                <input type="text" name="title" id="title" class="form-control" 
                                       placeholder="Enter notification title" required onkeyup="updatePreview()">
                            </div>
                            
                            <div class="mt-3">
                                <label for="message" class="form-label">Message</label>
                                <textarea name="message" id="message" class="form-control" rows="3" 
                                          placeholder="Enter detailed message (optional)" onkeyup="updatePreview()"></textarea>
                                <div class="form-text">You can use HTML for styling (e.g., &lt;strong&gt;, &lt;em&gt;, &lt;span class="badge bg-primary"&gt;)</div>
                            </div>
                            
                            <!-- Notification Preview -->
                            <div class="mt-4">
                                <label class="form-label">Preview:</label>
                                <div id="notificationPreview" class="notification-preview notification-type-info">
                                    <div class="d-flex align-items-start">
                                        <div class="me-3">
                                            <i id="previewIcon" class="fas fa-info-circle text-info"></i>
                                        </div>
                                        <div class="flex-grow-1">
                                            <div class="fw-bold" id="previewTitle">Sample Title</div>
                                            <div class="mt-1" id="previewMessage">Sample message content...</div>
                                            <div class="notification-time mt-2">
                                                <i class="fas fa-clock me-1"></i>
                                                Just now • Category: <span id="previewCategory">general</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-4 d-flex justify-content-between">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-1"></i>
                                    Send Notification
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="clearForm()">
                                    <i class="fas fa-eraser me-1"></i>
                                    Clear Form
                                </button>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Quick Templates -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-templates text-secondary me-2"></i>
                                Quick Templates
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('competition_start')">
                                        <div class="fw-bold text-primary">Competition Start</div>
                                        <small class="text-muted">Notify about competition beginning</small>
                                    </div>
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('heat_active')">
                                        <div class="fw-bold text-danger">Heat Activation</div>
                                        <small class="text-muted">Notify about heat becoming active</small>
                                    </div>
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('participant_ready')">
                                        <div class="fw-bold text-success">Participant Ready</div>
                                        <small class="text-muted">Call participant to start area</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('scoring_complete')">
                                        <div class="fw-bold text-info">Scoring Complete</div>
                                        <small class="text-muted">Notify about completed scoring</small>
                                    </div>
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('technical_issue')">
                                        <div class="fw-bold text-warning">Technical Issue</div>
                                        <small class="text-muted">Report technical problems</small>
                                    </div>
                                    <div class="template-btn border rounded p-3 mb-2" onclick="loadTemplate('emergency_stop')">
                                        <div class="fw-bold text-danger">Emergency Stop</div>
                                        <small class="text-muted">Emergency halt notification</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Recent Notifications -->
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-history text-secondary me-2"></i>
                                Recent Notifications
                            </h5>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="action" value="clear_event_notifications">
                                <input type="hidden" name="target_event" value="<?php echo $selected_event_id; ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger" 
                                        onclick="return confirm('Clear all notifications for this event?')">
                                    <i class="fas fa-trash me-1"></i>
                                    Clear All
                                </button>
                            </form>
                        </div>
                        <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                            <?php if (!empty($recent_notifications)): ?>
                                <?php foreach ($recent_notifications as $notification): ?>
                                    <div class="recent-notification border-<?php echo getTypeColor($notification['type']); ?>">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div class="flex-grow-1">
                                                <div class="fw-bold">
                                                    <i class="fas fa-<?php echo getTypeIcon($notification['type']); ?> text-<?php echo getTypeColor($notification['type']); ?> me-1"></i>
                                                    <?php echo htmlspecialchars($notification['title']); ?>
                                                </div>
                                                <?php if (!empty($notification['message'])): ?>
                                                    <div class="mt-1"><?php echo htmlspecialchars($notification['message']); ?></div>
                                                <?php endif; ?>
                                                <div class="notification-time mt-2">
                                                    <i class="fas fa-clock me-1"></i>
                                                    <?php echo date('M j, Y g:i A', strtotime($notification['created_at'])); ?>
                                                    • Category: <?php echo ucfirst($notification['category']); ?>
                                                    • By: <?php echo htmlspecialchars($notification['user_id']); ?>
                                                </div>
                                            </div>
                                            <span class="badge bg-<?php echo getCategoryColor($notification['category']); ?>">
                                                <?php echo ucfirst($notification['category']); ?>
                                            </span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-bell-slash fa-3x mb-3"></i>
                                    <p>No notifications found for this event.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Right Column: Statistics & Live Panel -->
                <div class="col-md-4">
                    <div class="live-notification-panel">
                        <!-- Statistics -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-chart-bar text-info me-2"></i>
                                    Notification Statistics
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if (!empty($notification_stats)): ?>
                                    <?php 
                                    $category_totals = [];
                                    foreach ($notification_stats as $stat) {
                                        $category_totals[$stat['category']] = ($category_totals[$stat['category']] ?? 0) + $stat['count'];
                                    }
                                    ?>
                                    <?php foreach ($category_totals as $category => $total): ?>
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span class="badge bg-<?php echo getCategoryColor($category); ?> me-2">
                                                <?php echo ucfirst($category); ?>
                                            </span>
                                            <span class="fw-bold"><?php echo $total; ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                    
                                    <hr>
                                    <div class="text-center">
                                        <small class="text-muted">
                                            Total: <?php echo array_sum($category_totals); ?> notifications
                                        </small>
                                    </div>
                                <?php else: ?>
                                    <div class="text-center text-muted">
                                        <i class="fas fa-chart-bar fa-2x mb-2"></i>
                                        <p class="mb-0">No statistics available</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Live Notification Test Panel -->
                        <div class="card">
                            <div class="card-header">
                                <h5 class="mb-0">
                                    <i class="fas fa-broadcast-tower text-success me-2"></i>
                                    Live System Test
                                </h5>
                            </div>
                            <div class="card-body">
                                <p class="small text-muted mb-3">
                                    Test the live notification system with sample data.
                                </p>
                                
                                <div class="d-grid gap-2">
                                    <button class="btn btn-sm btn-outline-success" onclick="testNotification('success', 'participant')">
                                        <i class="fas fa-user-check me-1"></i>
                                        Test Participant Ready
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger" onclick="testNotification('danger', 'heat')">
                                        <i class="fas fa-fire me-1"></i>
                                        Test Heat Alert
                                    </button>
                                    <button class="btn btn-sm btn-outline-info" onclick="testNotification('info', 'scoring')">
                                        <i class="fas fa-chart-line me-1"></i>
                                        Test Score Update
                                    </button>
                                    <button class="btn btn-sm btn-outline-warning" onclick="testNotification('warning', 'system')">
                                        <i class="fas fa-exclamation-triangle me-1"></i>
                                        Test System Warning
                                    </button>
                                </div>
                                
                                <hr>
                                
                                <div class="d-grid">
                                    <button class="btn btn-sm btn-primary" onclick="openLiveMonitor()">
                                        <i class="fas fa-external-link-alt me-1"></i>
                                        Open Live Monitor
                                    </button>
                                </div>
                                
                                <hr>
                                
                                <!-- Notification Settings -->
                                <div class="mb-3">
                                    <h6 class="fw-bold mb-2">
                                        <i class="fas fa-cog text-secondary me-1"></i>
                                        Settings
                                    </h6>
                                    <div class="d-grid gap-1">
                                        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#notificationSettingsModal">
                                            <i class="fas fa-sliders-h me-1"></i>
                                            Notification Settings
                                        </button>
                                        <button class="btn btn-sm btn-outline-info" onclick="exportNotifications()">
                                            <i class="fas fa-download me-1"></i>
                                            Export Data
                                        </button>
                                        <button class="btn btn-sm btn-outline-secondary" onclick="showNotificationStats()">
                                            <i class="fas fa-chart-pie me-1"></i>
                                            Detailed Stats
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="row">
                <div class="col-12">
                    <div class="text-center py-5">
                        <i class="fas fa-calendar-plus fa-4x text-muted mb-3"></i>
                        <h3 class="text-muted">No Event Selected</h3>
                        <p class="text-muted">Please select an event to manage notifications.</p>
                        <?php if (empty($events)): ?>
                            <a href="event_create.php" class="btn btn-primary">
                                <i class="fas fa-plus me-1"></i>
                                Create First Event
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Notification Settings Modal -->
    <div class="modal fade" id="notificationSettingsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-cog text-primary me-2"></i>
                        Notification System Settings
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <!-- Auto-Notifications -->
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">
                                <i class="fas fa-robot text-info me-1"></i>
                                Auto-Notifications
                            </h6>
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="autoParticipantReady" checked>
                                    <label class="form-check-label" for="autoParticipantReady">
                                        Participant Ready Alerts
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="autoScoreUpdates" checked>
                                    <label class="form-check-label" for="autoScoreUpdates">
                                        Score Update Notifications
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="autoHeatChanges">
                                    <label class="form-check-label" for="autoHeatChanges">
                                        Heat Status Changes
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="autoJudgeAlerts">
                                    <label class="form-check-label" for="autoJudgeAlerts">
                                        Judge Action Alerts
                                    </label>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Display Settings -->
                        <div class="col-md-6">
                            <h6 class="fw-bold mb-3">
                                <i class="fas fa-eye text-success me-1"></i>
                                Display Settings
                            </h6>
                            <div class="mb-3">
                                <label for="notificationDuration" class="form-label">
                                    Display Duration (seconds)
                                </label>
                                <input type="range" class="form-range" id="notificationDuration" min="3" max="30" value="10">
                                <div class="d-flex justify-content-between">
                                    <small>3s</small>
                                    <small id="durationValue">10s</small>
                                    <small>30s</small>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="maxVisibleNotifications" class="form-label">
                                    Max Visible Notifications
                                </label>
                                <select class="form-select" id="maxVisibleNotifications">
                                    <option value="3">3 notifications</option>
                                    <option value="5" selected>5 notifications</option>
                                    <option value="10">10 notifications</option>
                                    <option value="0">Unlimited</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Sound Alerts</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="soundEnabled">
                                    <label class="form-check-label" for="soundEnabled">
                                        Enable notification sounds
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filter Presets -->
                    <hr>
                    <h6 class="fw-bold mb-3">
                        <i class="fas fa-filter text-warning me-1"></i>
                        Filter Presets
                    </h6>
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card border-primary">
                                <div class="card-body text-center">
                                    <h6>Judge View</h6>
                                    <small class="text-muted">Judge, Scoring, Participant</small>
                                    <div class="mt-2">
                                        <button class="btn btn-sm btn-outline-primary" onclick="applyFilterPreset('judge')">Apply</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card border-success">
                                <div class="card-body text-center">
                                    <h6>Staff View</h6>
                                    <small class="text-muted">Competition, Participant, Heat</small>
                                    <div class="mt-2">
                                        <button class="btn btn-sm btn-outline-success" onclick="applyFilterPreset('staff')">Apply</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card border-info">
                                <div class="card-body text-center">
                                    <h6>Public View</h6>
                                    <small class="text-muted">General, Competition</small>
                                    <div class="mt-2">
                                        <button class="btn btn-sm btn-outline-info" onclick="applyFilterPreset('public')">Apply</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Advanced Settings -->
                    <hr>
                    <h6 class="fw-bold mb-3">
                        <i class="fas fa-cogs text-danger me-1"></i>
                        Advanced Settings
                    </h6>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="pollInterval" class="form-label">
                                    Polling Interval (seconds)
                                </label>
                                <select class="form-select" id="pollInterval">
                                    <option value="5">5 seconds (High frequency)</option>
                                    <option value="10" selected>10 seconds (Normal)</option>
                                    <option value="30">30 seconds (Low frequency)</option>
                                    <option value="60">1 minute (Very low)</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Database Cleanup</label>
                                <div class="d-grid">
                                    <button class="btn btn-sm btn-outline-warning" onclick="cleanupOldNotifications()">
                                        <i class="fas fa-broom me-1"></i>
                                        Clean Old Notifications (30+ days)
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" onclick="saveNotificationSettings()">
                        <i class="fas fa-save me-1"></i>
                        Save Settings
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Detailed Stats Modal -->
    <div class="modal fade" id="detailedStatsModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-chart-pie text-info me-2"></i>
                        Detailed Notification Statistics
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="detailedStatsContent">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">Loading statistics...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Include notification system -->
    <?php render_notification_system(); ?>
    
    <!-- Scripts -->
    <?php include_once '../includes/scripts.php'; ?>
    
    <script>
        // Notification management JavaScript
        let currentEventId = <?php echo json_encode($selected_event_id); ?>;
        
        // Templates
        const notificationTemplates = {
            competition_start: {
                type: 'info',
                category: 'competition',
                title: 'Competition Starting',
                message: 'The competition is about to begin. All participants please prepare.'
            },
            heat_active: {
                type: 'warning',
                category: 'heat',
                title: 'Heat #[NUMBER] Now Active',
                message: 'Heat #[NUMBER] is now active. Participants should be ready in the start area.'
            },
            participant_ready: {
                type: 'success',
                category: 'participant',
                title: 'Participant #[BIB] Ready',
                message: 'Participant #[BIB] ([NAME]) please report to the start area.'
            },
            scoring_complete: {
                type: 'info',
                category: 'scoring',
                title: 'Scoring Complete',
                message: 'All scores have been recorded and approved for this round.'
            },
            technical_issue: {
                type: 'warning',
                category: 'technical',
                title: 'Technical Issue Reported',
                message: 'A technical issue has been reported. Competition may be temporarily paused.'
            },
            emergency_stop: {
                type: 'danger',
                category: 'system',
                title: 'EMERGENCY STOP',
                message: 'Competition has been stopped due to emergency. All activities must cease immediately.'
            }
        };
        
        function loadTemplate(templateKey) {
            const template = notificationTemplates[templateKey];
            if (!template) return;
            
            document.getElementById('notification_type').value = template.type;
            document.getElementById('category').value = template.category;
            document.getElementById('title').value = template.title;
            document.getElementById('message').value = template.message;
            
            updatePreview();
        }
        
        function updatePreview() {
            const typeElement = document.getElementById('notification_type');
            const categoryElement = document.getElementById('category');
            const titleElement = document.getElementById('title');
            const messageElement = document.getElementById('message');
            
            // Check if elements exist before accessing their values
            if (!typeElement || !categoryElement || !titleElement || !messageElement) {
                console.warn('updatePreview: Some form elements not found, skipping preview update');
                return;
            }
            
            const type = typeElement.value;
            const category = categoryElement.value;
            const title = titleElement.value || 'Sample Title';
            const message = messageElement.value || 'Sample message content...';
            
            const preview = document.getElementById('notificationPreview');
            const previewIcon = document.getElementById('previewIcon');
            const previewTitle = document.getElementById('previewTitle');
            const previewMessage = document.getElementById('previewMessage');
            const previewCategory = document.getElementById('previewCategory');
            
            // Check if preview elements exist
            if (!preview || !previewIcon || !previewTitle || !previewMessage || !previewCategory) {
                console.warn('updatePreview: Preview elements not found, skipping preview update');
                return;
            }
            
            // Update classes
            preview.className = `notification-preview notification-type-${type}`;
            
            // Update icon
            const icons = {
                success: 'fas fa-check-circle text-success',
                danger: 'fas fa-exclamation-triangle text-danger',
                warning: 'fas fa-exclamation-circle text-warning',
                info: 'fas fa-info-circle text-info'
            };
            previewIcon.className = icons[type] || icons.info;
            
            // Update content
            previewTitle.textContent = title;
            previewMessage.innerHTML = message;
            previewCategory.textContent = category;
        }
        
        function clearForm() {
            const titleElement = document.getElementById('title');
            const messageElement = document.getElementById('message');
            const typeElement = document.getElementById('notification_type');
            const categoryElement = document.getElementById('category');
            
            // Only clear elements that exist
            if (titleElement) titleElement.value = '';
            if (messageElement) messageElement.value = '';
            if (typeElement) typeElement.value = 'general';
            if (categoryElement) categoryElement.value = 'information';
            
            // Update preview only if elements exist
            try {
                updatePreview();
            } catch (error) {
                console.warn('clearForm: Error updating preview:', error);
            }
        }
        
        function showAlert(message, type = 'info') {
            // Create alert element
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // Insert at top of form
            const form = document.getElementById('notificationForm');
            if (form) {
                form.parentNode.insertBefore(alertDiv, form);
                
                // Auto-remove after 5 seconds
                setTimeout(() => {
                    if (alertDiv && alertDiv.parentNode) {
                        alertDiv.parentNode.removeChild(alertDiv);
                    }
                }, 5000);
            }
        }
        
        function testNotification(type, category) {
            console.log('Testing notification:', type, category, 'Event ID:', currentEventId);
            
            if (!currentEventId) {
                showAlert('Please select an event first', 'warning');
                return;
            }

            const testMessages = {
                'success-participant': {
                    title: 'Test: Participant #42 Ready',
                    message: 'Participant #42 (John Doe) please report to the start area.'
                },
                'danger-heat': {
                    title: 'Test: Heat #3 Alert',
                    message: 'Heat #3 requires immediate attention from judges.'
                },
                'info-scoring': {
                    title: 'Test: Score Update',
                    message: 'Participant #15 scored 8.5 points from Judge #2.'
                },
                'warning-system': {
                    title: 'Test: System Warning',
                    message: 'This is a test system warning notification.'
                }
            };

            const key = `${type}-${category}`;
            const testMsg = testMessages[key] || {
                title: `Test ${type.charAt(0).toUpperCase() + type.slice(1)} Notification`,
                message: `This is a test ${category} notification.`
            };

            // Send via AJAX
            const formData = new FormData();
            formData.append('action', 'send_notification');
            formData.append('event_id', currentEventId);
            formData.append('type', type);
            formData.append('category', category);
            formData.append('title', testMsg.title);
            formData.append('message', testMsg.message);
            formData.append('user_id', '<?php echo $admin_id; ?>');

            console.log('Sending test notification via AJAX...');

            fetch('../api/notification_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Test notification response status:', response.status);
                return response.json();
            })
            .then(data => {
                console.log('Test notification response:', data);
                if (data.success) {
                    showAlert(`Test ${type} notification sent successfully!`, 'success');
                } else {
                    showAlert('Failed to send test notification: ' + (data.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error sending test notification:', error);
                showAlert('Error sending test notification: ' + error.message, 'danger');
            });
        }

        function testLiveNotifications() {
            if (!currentEventId) {
                showAlert('Please select an event first', 'warning');
                return;
            }

            const testNotification = {
                type: 'info',
                category: 'system', 
                title: 'Live Notification System Test',
                message: 'This is a comprehensive test of the live notification system. If you see this message, the system is working correctly!'
            };

            // Send via AJAX
            const formData = new FormData();
            formData.append('action', 'send_notification');
            formData.append('event_id', currentEventId);
            formData.append('type', testNotification.type);
            formData.append('category', testNotification.category);
            formData.append('title', testNotification.title);
            formData.append('message', testNotification.message);
            formData.append('user_id', '<?php echo $admin_id; ?>');

            fetch('../api/notification_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Live test notification response:', data);
                if (data.success) {
                    showAlert('Live notification test sent successfully! Check the notification display area.', 'success');
                } else {
                    showAlert('Failed to send live test notification: ' + (data.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error sending live test notification:', error);
                showAlert('Error sending live test notification: ' + error.message, 'danger');
            });
        }
        function openLiveMonitor() {
            if (!currentEventId) {
                showAlert('Please select an event first', 'warning');
                return;
            }
            
            // Open live scoreboard or dashboard in new tab
            window.open('../live_scoreboard.php?event_id=' + currentEventId, '_blank');
        }
        
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            document.body.appendChild(alertDiv);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }
        
        // Initialize preview on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, initializing notification system...');
            
            // Small delay to ensure all elements are rendered
            setTimeout(function() {
                try {
                    updatePreview();
                    initializeSettingsModal();
                    initializeFormValidation();
                    
                    if (currentEventId) {
                        console.log('Current event ID:', currentEventId);
                        
                        // Load settings for this event
                        loadNotificationSettings();
                        
                        // Initialize notification manager for real-time notifications
                        if (typeof NotificationManager !== 'undefined') {
                            const notificationManager = new NotificationManager(currentEventId, '<?php echo $admin_id; ?>');
                            notificationManager.startPolling();
                            
                            // Make it globally accessible for settings
                            window.globalNotificationManager = notificationManager;
                            
                            console.log('NotificationManager initialized and polling started');
                        } else {
                            console.warn('NotificationManager not found, notifications may not work properly');
                        }
                    }
                } catch (error) {
                    console.error('Error during initialization:', error);
                }
            }, 100);
        });
        
        function initializeFormValidation() {
            const form = document.getElementById('notificationForm');
            if (form) {
                // Remove any existing event listeners
                form.removeEventListener('submit', handleFormSubmit);
                form.addEventListener('submit', handleFormSubmit);
                
                // Also handle button click
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.removeEventListener('click', handleSubmitClick);
                    submitBtn.addEventListener('click', handleSubmitClick);
                }
                
                // Add event listeners for preview updates
                const previewFields = ['notification_type', 'category', 'title', 'message'];
                previewFields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) {
                        field.addEventListener('input', updatePreview);
                        field.addEventListener('change', updatePreview);
                    }
                });
            }
        }
        
        function handleFormSubmit(e) {
            e.preventDefault();
            sendNotificationAjax();
            return false;
        }
        
        function handleSubmitClick(e) {
            e.preventDefault();
            sendNotificationAjax();
            return false;
        }
        
        function sendNotificationAjax() {
            const form = document.getElementById('notificationForm');
            const submitBtn = form.querySelector('button[type="submit"]');
            
            // Validation
            const title = document.getElementById('title').value.trim();
            const eventId = currentEventId;
            
            console.log('AJAX validation - Title:', title, 'Event ID:', eventId);
            
            if (!title) {
                showAlert('Please enter a notification title', 'danger');
                document.getElementById('title').focus();
                return false;
            }
            
            if (!eventId) {
                showAlert('Please select an event first', 'danger');
                return false;
            }
            
            // Disable submit button to prevent multiple submissions
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Sending...';
            }
            
            // Prepare form data
            const formData = new FormData();
            formData.append('action', 'send_notification');
            formData.append('event_id', eventId);
            formData.append('type', document.getElementById('notification_type').value);
            formData.append('category', document.getElementById('category').value);
            formData.append('title', title);
            formData.append('message', document.getElementById('message').value);
            formData.append('user_id', '<?php echo $admin_id; ?>');
            
            // Debug log
            console.log('Sending notification via AJAX:');
            for (let [key, value] of formData.entries()) {
                console.log(key, value);
            }
            
            // Send via AJAX
            fetch('../api/notification_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                console.log('Response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('API response:', data);
                
                // Re-enable submit button
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i>Send Notification';
                }
                
                if (data.success) {
                    showAlert('Notification sent successfully!', 'success');
                    clearForm();
                    // Reload page after 2 seconds to show new notification in recent list
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    showAlert('Failed to send notification: ' + (data.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                
                // Re-enable submit button
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = '<i class="fas fa-paper-plane me-1"></i>Send Notification';
                }
                
                showAlert('Error sending notification: ' + error.message, 'danger');
            });
        }
        
        function initializeSettingsModal() {
            // Update duration display
            const durationSlider = document.getElementById('notificationDuration');
            const durationValue = document.getElementById('durationValue');
            
            durationSlider.addEventListener('input', function() {
                durationValue.textContent = this.value + 's';
            });
            
            // Load saved settings
            loadNotificationSettings();
        }
        
        function applyFilterPreset(preset) {
            const presets = {
                judge: ['judge', 'scoring', 'participant'],
                staff: ['competition', 'participant', 'heat'],
                public: ['general', 'competition']
            };
            
            if (presets[preset]) {
                // Apply filter and close modal
                const category = presets[preset][0]; // Use first category as primary
                setNotificationFilter(category);
                
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('notificationSettingsModal'));
                if (modal) modal.hide();
                
                showAlert(`Applied ${preset} filter preset`, 'success');
            }
        }
        
        function saveNotificationSettings() {
            if (!currentEventId) {
                showAlert('Please select an event first', 'warning');
                return;
            }
            
            const settings = {
                pollInterval: document.getElementById('pollInterval').value,
                maxVisibleNotifications: document.getElementById('maxVisibleNotifications').value,
                notificationDuration: document.getElementById('notificationDuration').value,
                soundEnabled: document.getElementById('soundEnabled').checked,
                autoDismiss: document.getElementById('autoDismiss') ? document.getElementById('autoDismiss').checked : false,
                showCategories: getSelectedCategories()
            };
            
            // Save to database via API
            const formData = new FormData();
            formData.append('action', 'save_settings');
            formData.append('event_id', currentEventId);
            Object.keys(settings).forEach(key => {
                if (Array.isArray(settings[key])) {
                    formData.append(key, JSON.stringify(settings[key]));
                } else {
                    formData.append(key, settings[key]);
                }
            });
            
            fetch('../api/notification_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Settings save response:', data);
                if (data.success) {
                    // Apply settings immediately
                    applyNotificationSettings(settings);
                    
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('notificationSettingsModal'));
                    if (modal) modal.hide();
                    
                    showAlert('Notification settings saved successfully!', 'success');
                } else {
                    showAlert('Failed to save settings: ' + (data.message || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error saving settings:', error);
                showAlert('Error saving settings: ' + error.message, 'danger');
            });
        }
        
        function getSelectedCategories() {
            const categories = [];
            const checkboxes = document.querySelectorAll('#notificationSettingsModal input[type="checkbox"][data-category]');
            checkboxes.forEach(checkbox => {
                if (checkbox.checked) {
                    categories.push(checkbox.getAttribute('data-category'));
                }
            });
            return categories;
        }
        
        function loadNotificationSettings() {
            if (!currentEventId) {
                console.warn('No event selected, using default settings');
                return;
            }
            
            // Load settings from database via API
            fetch(`../api/notification_api.php?action=get_settings&event_id=${currentEventId}`)
            .then(response => response.json())
            .then(data => {
                console.log('Settings load response:', data);
                if (data.success && data.settings) {
                    const settings = data.settings;
                    
                    // Apply saved settings to form
                    if (document.getElementById('pollInterval')) {
                        document.getElementById('pollInterval').value = settings.pollInterval || 3000;
                    }
                    if (document.getElementById('maxVisibleNotifications')) {
                        document.getElementById('maxVisibleNotifications').value = settings.maxVisibleNotifications || 5;
                    }
                    if (document.getElementById('notificationDuration')) {
                        document.getElementById('notificationDuration').value = settings.notificationDuration || 10;
                    }
                    if (document.getElementById('soundEnabled')) {
                        document.getElementById('soundEnabled').checked = settings.soundEnabled !== false;
                    }
                    if (document.getElementById('autoDismiss')) {
                        document.getElementById('autoDismiss').checked = settings.autoDismiss || false;
                    }
                    
                    // Update duration display
                    const durationValue = document.getElementById('durationValue');
                    if (durationValue) {
                        durationValue.textContent = (settings.notificationDuration || 10) + 's';
                    }
                    
                    // Apply category filters if any
                    if (settings.showCategories && Array.isArray(settings.showCategories)) {
                        settings.showCategories.forEach(category => {
                            const checkbox = document.querySelector(`input[data-category="${category}"]`);
                            if (checkbox) {
                                checkbox.checked = true;
                            }
                        });
                    }
                    
                    // Apply settings to notification system
                    applyNotificationSettings(settings);
                } else {
                    console.warn('Failed to load settings, using defaults');
                }
            })
            .catch(error => {
                console.error('Error loading settings:', error);
                // Continue with default settings
            });
        }
        
        function applyNotificationSettings(settings) {
            console.log('Applying notification settings:', settings);
            
            // Apply settings to notification system
            if (window.globalNotificationManager) {
                const manager = window.globalNotificationManager;
                
                // Update polling rate (pollingRate property)
                if (settings.pollInterval && typeof settings.pollInterval === 'number') {
                    manager.pollingRate = parseInt(settings.pollInterval);
                    console.log('Updated polling rate to:', manager.pollingRate);
                    
                    // Restart polling with new interval
                    if (manager.pollingInterval) {
                        clearInterval(manager.pollingInterval);
                        manager.pollingInterval = setInterval(() => {
                            manager.pollNotifications();
                        }, manager.pollingRate);
                    }
                }
                
                // Update max visible notifications (would need to be implemented in NotificationManager)
                if (settings.maxVisibleNotifications) {
                    manager.maxVisible = parseInt(settings.maxVisibleNotifications);
                    console.log('Updated max visible notifications to:', manager.maxVisible);
                }
                
                // Update notification duration (would need to be implemented in NotificationManager)
                if (settings.notificationDuration) {
                    manager.displayDuration = parseInt(settings.notificationDuration) * 1000;
                    console.log('Updated display duration to:', manager.displayDuration);
                }
                
                // Update sound setting (would need to be implemented in NotificationManager)
                if (typeof settings.soundEnabled === 'boolean') {
                    manager.soundEnabled = settings.soundEnabled;
                    console.log('Updated sound enabled to:', manager.soundEnabled);
                }
                
                console.log('Settings applied successfully');
            } else {
                console.warn('GlobalNotificationManager not available, settings not applied');
            }
        }
        
        function exportNotifications() {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            showAlert('Generating export... Please wait.', 'info');
            
            // Create export data
            const exportData = {
                event_id: currentEventId,
                exported_at: new Date().toISOString(),
                statistics: <?php echo json_encode($notification_stats ?? []); ?>,
                recent_notifications: <?php echo json_encode($recent_notifications ?? []); ?>
            };
            
            // Create and download file
            const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `notifications_export_event_${currentEventId}_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showAlert('Export completed successfully!', 'success');
        }
        
        function showNotificationStats() {
            const modal = new bootstrap.Modal(document.getElementById('detailedStatsModal'));
            modal.show();
            
            // Generate detailed statistics
            generateDetailedStats();
        }
        
        function generateDetailedStats() {
            const statsContent = document.getElementById('detailedStatsContent');
            
            if (!currentEventId) {
                statsContent.innerHTML = '<div class="alert alert-warning">Please select an event to view statistics.</div>';
                return;
            }
            
            // Simulate loading time
            setTimeout(() => {
                const stats = <?php echo json_encode($notification_stats ?? []); ?>;
                const recent = <?php echo json_encode($recent_notifications ?? []); ?>;
                
                let html = '<div class="row">';
                
                // Summary cards
                html += '<div class="col-md-3"><div class="card text-center"><div class="card-body">';
                html += '<h4 class="text-primary">' + (recent?.length || 0) + '</h4>';
                html += '<small>Total Notifications</small></div></div></div>';
                
                html += '<div class="col-md-3"><div class="card text-center"><div class="card-body">';
                html += '<h4 class="text-success">' + (stats?.filter(s => s.type === 'success')?.length || 0) + '</h4>';
                html += '<small>Success Notifications</small></div></div></div>';
                
                html += '<div class="col-md-3"><div class="card text-center"><div class="card-body">';
                html += '<h4 class="text-warning">' + (stats?.filter(s => s.type === 'warning')?.length || 0) + '</h4>';
                html += '<small>Warnings</small></div></div></div>';
                
                html += '<div class="col-md-3"><div class="card text-center"><div class="card-body">';
                html += '<h4 class="text-danger">' + (stats?.filter(s => s.type === 'danger')?.length || 0) + '</h4>';
                html += '<small>Errors</small></div></div></div>';
                
                html += '</div><hr>';
                
                // Category breakdown
                if (stats && stats.length > 0) {
                    html += '<h6>Notifications by Category</h6>';
                    html += '<div class="row">';
                    
                    const categoryTotals = {};
                    stats.forEach(stat => {
                        categoryTotals[stat.category] = (categoryTotals[stat.category] || 0) + parseInt(stat.count);
                    });
                    
                    Object.keys(categoryTotals).forEach(category => {
                        html += `<div class="col-md-6 mb-2">
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="badge bg-secondary">${category}</span>
                                <strong>${categoryTotals[category]}</strong>
                            </div>
                        </div>`;
                    });
                    
                    html += '</div>';
                } else {
                    html += '<div class="alert alert-info">No notification statistics available for this event.</div>';
                }
                
                statsContent.innerHTML = html;
            }, 1500);
        }
        
        function cleanupOldNotifications() {
            if (!currentEventId) {
                alert('Please select an event first');
                return;
            }
            
            if (!confirm('This will permanently delete notifications older than 30 days. Continue?')) {
                return;
            }
            
            // Make API call to cleanup old notifications
            const formData = new FormData();
            formData.append('action', 'cleanup_old');
            formData.append('event_id', currentEventId);
            formData.append('days', '30');
            
            fetch('../api/notification_api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showAlert('Old notifications cleaned up successfully!', 'success');
                    // Reload page to refresh statistics
                    setTimeout(() => location.reload(), 2000);
                } else {
                    showAlert('Failed to cleanup notifications: ' + (data.error || 'Unknown error'), 'danger');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showAlert('Error during cleanup operation', 'danger');
            });
        }
    </script>
     <?php include 'footer.php'; ?>
</body>
</html>

<?php
// Helper functions
function getTypeColor($type) {
    $colors = [
        'success' => 'success',
        'danger' => 'danger',
        'warning' => 'warning',
        'info' => 'info'
    ];
    return $colors[$type] ?? 'secondary';
}

function getTypeIcon($type) {
    $icons = [
        'success' => 'check-circle',
        'danger' => 'exclamation-triangle',
        'warning' => 'exclamation-circle',
        'info' => 'info-circle'
    ];
    return $icons[$type] ?? 'bell';
}

function getCategoryColor($category) {
    $colors = [
        'general' => 'info',
        'competition' => 'primary',
        'participant' => 'success',
        'judge' => 'warning',
        'heat' => 'danger',
        'scoring' => 'purple',
        'system' => 'secondary',
        'technical' => 'dark'
    ];
    return $colors[$category] ?? 'secondary';
}
?>
