<?php
include '../includes/auth.php';
include '../includes/db.php';

// Test page for judge notification system
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Judge Notification Test</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container-fluid container-StyleScore p-4">
        <div class="row justify-content-center">
            <div class="col-md-10">
                <div class="border-0 shadow-none card">
                    <div class="border-0 shadow-none card-header bg-warning text-dark">
                        <h4 class="mb-0">
                            <i class="fas fa-gavel me-2"></i>
                            Judge Notification System Test
                        </h4>
                    </div>
                    <div class="border-0 shadow-none card-body">
                        <!-- Session Debug Info -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="border-0 shadow-none card border-info">
                                    <div class="border-0 shadow-none card-header bg-info text-white">
                                        <h6 class="mb-0">Session Information</h6>
                                    </div>
                                    <div class="border-0 shadow-none card-body">
                                        <table class="table table-sm">
                                            <tr><td><strong>User ID:</strong></td><td><?php echo htmlspecialchars($_SESSION['user_id'] ?? 'Not set'); ?></td></tr>
                                            <tr><td><strong>Judge ID:</strong></td><td><?php echo htmlspecialchars($_SESSION['judge_id'] ?? 'Not set'); ?></td></tr>
                                            <tr><td><strong>Username:</strong></td><td><?php echo htmlspecialchars($_SESSION['username'] ?? 'Not set'); ?></td></tr>
                                            <tr><td><strong>User Type:</strong></td><td><?php echo htmlspecialchars($_SESSION['user_type'] ?? 'Not set'); ?></td></tr>
                                            <tr><td><strong>Judge Logged In:</strong></td><td><?php echo isset($_SESSION['judge_logged_in']) ? ($_SESSION['judge_logged_in'] ? 'Yes' : 'No') : 'Not set'; ?></td></tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="border-0 shadow-none card border-success">
                                    <div class="border-0 shadow-none card-header bg-success text-white">
                                        <h6 class="mb-0">Notification Configuration</h6>
                                    </div>
                                    <div class="border-0 shadow-none card-body">
                                        <table class="table table-sm">
                                            <tr><td><strong>Event ID:</strong></td><td><?php echo htmlspecialchars($notification_event_id ?? 'Not detected'); ?></td></tr>
                                            <tr><td><strong>User ID:</strong></td><td><?php echo htmlspecialchars($notification_user_id ?? 'Not detected'); ?></td></tr>
                                            <tr><td><strong>User Role:</strong></td><td><?php echo htmlspecialchars($notification_user_role ?? 'Not detected'); ?></td></tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Judge Assignments Check -->
                        <div class="border-0 shadow-none card border-primary mb-4">
                            <div class="border-0 shadow-none card-header bg-primary text-white">
                                <h6 class="mb-0">Judge Assignments Analysis</h6>
                            </div>
                            <div class="border-0 shadow-none card-body">
                                <?php
                                $judge_assignments_found = false;
                                $judge_id_for_lookup = null;
                                
                                // Try to get judge ID for lookup
                                if (isset($_SESSION['judge_id'])) {
                                    $judge_id_for_lookup = $_SESSION['judge_id'];
                                } elseif (isset($_SESSION['user_id']) && (isset($_SESSION['judge_logged_in']) && $_SESSION['judge_logged_in'])) {
                                    $judge_id_for_lookup = $_SESSION['user_id'];
                                } elseif (isset($_SESSION['user_id']) && (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'judge')) {
                                    $judge_id_for_lookup = $_SESSION['user_id'];
                                }
                                
                                if ($judge_id_for_lookup) {
                                    echo "<p><strong>Looking up assignments for Judge ID:</strong> " . htmlspecialchars($judge_id_for_lookup) . "</p>";
                                    
                                    try {
                                        $stmt = $pdo->prepare("
                                            SELECT ja.*, e.name as event_name, e.date as event_date 
                                            FROM judge_assignments ja
                                            LEFT JOIN events e ON ja.event_id = e.id
                                            WHERE ja.judge_id = ? 
                                            ORDER BY ja.event_id DESC
                                        ");
                                        $stmt->execute([$judge_id_for_lookup]);
                                        $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                        
                                        if (!empty($assignments)) {
                                            $judge_assignments_found = true;
                                            echo "<div class='table-responsive'>";
                                            echo "<table class='table table-striped table-sm'>";
                                            echo "<thead><tr><th>Event ID</th><th>Event Name</th><th>Date</th><th>Heat</th><th>Status</th></tr></thead>";
                                            echo "<tbody>";
                                            foreach ($assignments as $assignment) {
                                                echo "<tr>";
                                                echo "<td><span class='badge bg-primary'>" . htmlspecialchars($assignment['event_id']) . "</span></td>";
                                                echo "<td>" . htmlspecialchars($assignment['event_name'] ?? 'Unknown') . "</td>";
                                                echo "<td>" . htmlspecialchars($assignment['event_date'] ?? 'Unknown') . "</td>";
                                                echo "<td>" . htmlspecialchars($assignment['heat_number'] ?? 'All') . "</td>";
                                                echo "<td><span class='badge bg-success'>Assigned</span></td>";
                                                echo "</tr>";
                                            }
                                            echo "</tbody></table></div>";
                                            
                                            // Show most recent event
                                            $most_recent = $assignments[0];
                                            echo "<div class='alert alert-success'>";
                                            echo "<strong>Most Recent Assignment:</strong> Event ID " . htmlspecialchars($most_recent['event_id']) . 
                                                 " (" . htmlspecialchars($most_recent['event_name'] ?? 'Unknown Event') . ")";
                                            echo "</div>";
                                        } else {
                                            echo "<div class='alert alert-warning'>";
                                            echo "<strong>No judge assignments found</strong> for Judge ID: " . htmlspecialchars($judge_id_for_lookup);
                                            echo "</div>";
                                        }
                                    } catch (Exception $e) {
                                        echo "<div class='alert alert-danger'>";
                                        echo "<strong>Database Error:</strong> " . htmlspecialchars($e->getMessage());
                                        echo "</div>";
                                    }
                                } else {
                                    echo "<div class='alert alert-warning'>";
                                    echo "<strong>No Judge ID found in session.</strong> Cannot lookup assignments.";
                                    echo "</div>";
                                }
                                ?>
                            </div>
                        </div>

                        <!-- Test Buttons -->
                        <div class="row g-3">
                            <div class="col-md-6">
                                <h6>Judge-Specific Notifications</h6>
                                <button class="btn btn-warning btn-sm mb-2 w-100" onclick="testJudgeNotifications()">
                                    <i class="fas fa-gavel me-1"></i> Test Judge Actions
                                </button>
                                <button class="btn btn-info btn-sm mb-2 w-100" onclick="testScoringNotifications()">
                                    <i class="fas fa-star me-1"></i> Test Scoring Updates
                                </button>
                                <button class="btn btn-success btn-sm mb-2 w-100" onclick="testParticipantNotifications()">
                                    <i class="fas fa-user me-1"></i> Test Participant Events
                                </button>
                                <button class="btn btn-danger btn-sm mb-2 w-100" onclick="testHeatNotifications()">
                                    <i class="fas fa-fire me-1"></i> Test Heat Events
                                </button>
                            </div>
                            <div class="col-md-6">
                                <h6>System Functions</h6>
                                <button class="btn btn-outline-success btn-sm mb-2 w-100" onclick="notifySuccess('Judge Test', 'Testing notification system')">
                                    Quick Success Test
                                </button>
                                <button class="btn btn-outline-warning btn-sm mb-2 w-100" onclick="notifyWarning('Judge Warning', 'Testing warning notification')">
                                    Quick Warning Test
                                </button>
                                <button class="btn btn-outline-info btn-sm mb-2 w-100" onclick="showSystemInfo()">
                                    <i class="fas fa-info-circle me-1"></i> Show System Info
                                </button>
                                <button class="btn btn-outline-secondary btn-sm mb-2 w-100" onclick="clearAllNotifications()">
                                    <i class="fas fa-trash me-1"></i> Clear All Notifications
                                </button>
                            </div>
                        </div>
                        
                        <!-- Event Detection Result -->
                        <div class="mt-4">
                            <?php if ($notification_event_id): ?>
                                <div class="alert alert-success">
                                    <h6><i class="fas fa-check-circle me-2"></i>Event Detection: SUCCESS</h6>
                                    <p class="mb-0">The notification system successfully detected Event ID: <strong><?php echo htmlspecialchars($notification_event_id); ?></strong></p>
                                    <?php if ($judge_assignments_found): ?>
                                        <small class="text-muted">Detected via judge assignments lookup</small>
                                    <?php else: ?>
                                        <small class="text-muted">Detected via fallback method (most recent event)</small>
                                    <?php endif; ?>
                                </div>
                            <?php else: ?>
                                <div class="alert alert-danger">
                                    <h6><i class="fas fa-exclamation-triangle me-2"></i>Event Detection: FAILED</h6>
                                    <p class="mb-0">The notification system could not detect an event ID. Notifications may not work properly.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        function testJudgeNotifications() {
            if (typeof notifyJudge === 'function') {
                const actions = ['Score Submitted', 'Score Reviewed', 'Participant Feedback', 'Heat Complete'];
                const action = actions[Math.floor(Math.random() * actions.length)];
                notifyJudge(action, `Judge action: ${action} for current assignment`);
            } else {
                testGenericNotification('warning', 'Judge Action', 'Judge has performed an action', 'judge');
            }
        }
        
        function testScoringNotifications() {
            if (typeof notifyScore === 'function') {
                const bib = Math.floor(Math.random() * 100) + 1;
                const score = (Math.random() * 10).toFixed(1);
                const judgeName = 'Judge <?php echo htmlspecialchars($notification_user_id); ?>';
                notifyScore(bib, score, judgeName);
            } else {
                testGenericNotification('info', 'Score Updated', 'New score recorded', 'scoring');
            }
        }
        
        function testParticipantNotifications() {
            if (typeof notifyParticipant === 'function') {
                const actions = ['on_start', 'started', 'completed'];
                const action = actions[Math.floor(Math.random() * actions.length)];
                const bib = Math.floor(Math.random() * 50) + 1;
                notifyParticipant(action, bib, `Test Participant ${bib}`);
            } else {
                testGenericNotification('success', 'Participant Event', 'Participant status updated', 'participant');
            }
        }
        
        function testHeatNotifications() {
            if (typeof notifyHeat === 'function') {
                const action = Math.random() > 0.5 ? 'activated' : 'deactivated';
                const heat = Math.floor(Math.random() * 5) + 1;
                notifyHeat(action, heat, action === 'activated' ? 1 : null);
            } else {
                testGenericNotification('danger', 'Heat Event', 'Heat status changed', 'heat');
            }
        }
        
        function testGenericNotification(type, title, message, category) {
            if (typeof sendNotification === 'function') {
                sendNotification(type, title, message, category);
            } else {
                alert('Notification system not loaded yet. Please wait a moment and try again.');
            }
        }
        
        function showSystemInfo() {
            const info = `
Event ID: <?php echo htmlspecialchars($notification_event_id ?? 'Not detected'); ?>
User ID: <?php echo htmlspecialchars($notification_user_id); ?>
Role: <?php echo htmlspecialchars($notification_user_role); ?>
Assignments Found: <?php echo $judge_assignments_found ? 'Yes' : 'No'; ?>
`;
            alert('System Information:\n\n' + info);
        }
        
        // Auto-test when page loads
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                if (typeof globalNotificationManager !== 'undefined' && globalNotificationManager) {
                    console.log('Judge notification system loaded successfully');
                    if (typeof sendNotification === 'function') {
                        sendNotification('success', 'Judge System Ready', 'Judge notification system is active and working', 'judge');
                    }
                } else {
                    console.warn('Judge notification system not loaded');
                }
            }, 2000);
        });
    </script>
    
    <?php
    // Render notification system
    if (function_exists('render_notification_system')) {
        render_notification_system();
    }
    ?>
</body>
</html>
