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

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['delete_id'])) {
        $delete_id = intval($_POST['delete_id']);
        // Delete user directly from users table
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'judge'");
        if ($stmt->execute([$delete_id])) {
            // Redirect with success message
            header("Location: judge_add.php?msg=deleted");
            exit;
        } else {
            header("Location: judge_add.php?msg=delete_error");
            exit;
        }
    } elseif (isset($_POST['edit_id'])) {
        // Handle edit judge
        $edit_id = intval($_POST['edit_id']);
        $edit_username = $_POST['edit_username'];
        $edit_is_head = isset($_POST['edit_is_head']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE users SET username = ?, judge_id = ? WHERE id = ? AND role = 'judge'");
        if ($stmt->execute([$edit_username, $edit_is_head, $edit_id])) {
            header("Location: judge_add.php?msg=updated");
            exit;
        } else {
            header("Location: judge_add.php?msg=update_error");
            exit;
        }
    } elseif (isset($_POST['name'])) {
        // Handle add new judge
        $name = trim($_POST['name']);
        $is_head = isset($_POST['is_head']) ? 1 : 0;

        if (!empty($name)) {
            // Generate login credentials
            $username = strtolower(str_replace(' ', '_', $name));
            $password = 'judge' . rand(100, 999); // simple password for demo
            
            // Check if username already exists
            $check_stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
            $check_stmt->execute([$username]);
            
            if ($check_stmt->fetch()) {
                // Username exists, add a number
                $username = $username . rand(10, 99);
            }
            
            try {
                // Insert directly into users table
                $stmt = $pdo->prepare("INSERT INTO users (username, password, role, judge_id) VALUES (?, ?, 'judge', ?)");
                if ($stmt->execute([$username, $password, $is_head])) {
                    $user_id = $pdo->lastInsertId();
                    
                    // Redirect with success parameters
                    header("Location: judge_add.php?msg=success&name=" . urlencode($name) . "&username=" . urlencode($username) . "&password=" . urlencode($password) . "&user_id=" . $user_id . "&is_head=" . $is_head);
                    exit;
                } else {
                    header("Location: judge_add.php?msg=error");
                    exit;
                }
            } catch (Exception $e) {
                header("Location: judge_add.php?msg=db_error&error=" . urlencode($e->getMessage()));
                exit;
            }
        } else {
            header("Location: judge_add.php?msg=empty_name");
            exit;
        }
    }
}

// Handle GET messages (after redirect)
if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'success':
            $name = $_GET['name'] ?? '';
            $username = $_GET['username'] ?? '';
            $password = $_GET['password'] ?? '';
            $user_id = $_GET['user_id'] ?? '';
            $is_head = $_GET['is_head'] ?? 0;
            
            $message = "<div class='alert alert-success alert alert-dismissible fade show'>
                <h5><i class='bi bi-check-circle-fill me-2'></i>Judge Added Successfully!</h5>
                <hr>
                <strong>Name:</strong> " . htmlspecialchars($name) . "<br>
                <strong>Login Username:</strong> <code>" . htmlspecialchars($username) . "</code><br>
                <strong>Password:</strong> <code>" . htmlspecialchars($password) . "</code><br>
                <strong>User ID:</strong> <span class='badge bg-primary'>" . htmlspecialchars($user_id) . "</span><br>
                <strong>Head Judge:</strong> " . ($is_head ? '<span class="badge bg-warning">Yes</span>' : '<span class="badge bg-secondary">No</span>') . "
                <hr>
                <small class='text-muted'><i class='bi bi-info-circle me-1'></i>Please save these credentials for the judge.</small>
                <button type='button' class='btn-close' data-bs-dismiss='alert'></button>
            </div>";
            break;
            
        case 'updated':
            $message = '<div class="alert alert-success alert alert-dismissible fade show">
                <i class="bi bi-check-circle-fill me-2"></i>Judge updated successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'deleted':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="bi bi-trash me-2"></i>Judge deleted successfully.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i>Failed to add judge. Please try again.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'update_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i>Failed to update judge.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'delete_error':
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i>Failed to delete judge.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'db_error':
            $error = $_GET['error'] ?? 'Unknown error';
            $message = '<div class="alert alert-danger alert alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i>Database error: ' . htmlspecialchars($error) . '
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
            
        case 'empty_name':
            $message = '<div class="alert alert-warning alert alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i>Please enter a judge name.
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>';
            break;
    }
}

// Fetch all judges from users table with additional info INCLUDING EVENT COUNT
try {
    $judges = $pdo->query("
        SELECT u.id, u.username, u.password, u.judge_id, u.created_at,
               COUNT(ja.event_id) as event_count
        FROM users u
        LEFT JOIN judge_assignments ja ON u.id = ja.judge_id
        
        GROUP BY u.id, u.username, u.password, u.judge_id, u.created_at
        ORDER BY u.id DESC
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $judges = [];
    if (!$message) { // Only show if no other message is set
        $message = '<div class="alert alert-danger">Error fetching judges: ' . htmlspecialchars($e->getMessage()) . '</div>';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Judge Management - Style Score Admin</title>
    <?php include_once '../includes/stylesheets.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        
        .required::after {
            content: ' *';
            color: #dc3545;
        }
        
        .event-count-badge {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .event-count-badge:hover {
            transform: scale(1.1);
        }
        
        .event-item {
            border-left: 4px solid #0d6efd;
            background: #f8f9fa;
            margin-bottom: 8px;
            padding: 12px;
            border-radius: 0 8px 8px 0;
        }
        
        .event-item:hover {
            background: #e9ecef;
        }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container">
            <!-- event action menu. -->
<div class="row mb-2">
    <div class="col-12">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        //$show_public_view = false;
        include 'event_actions_menu.php'; 
        ?>
    </div>
</div>
        <div class="row justify-content-center">
            <div class="col-12">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h4 class="mb-1">
                            <i class="fas fa-users text-success me-2"></i>Judge Management
                        </h4>
                        <p class="text-muted mb-0 small">Add new judges and manage existing judge accounts</p>
                    </div>
                    <div class="d-flex gap-2">
                        <a href="judge_export.php?format=csv" class="btn btn-outline-success btn-sm">
                            <i class="fas fa-file-csv me-1"></i>Export CSV
                        </a>
                        <a href="judge_export.php?format=pdf" class="btn btn-outline-danger btn-sm">
                            <i class="fas fa-file-pdf me-1"></i>Export PDF
                        </a>
                        <a href="judge_assign.php" class="btn btn-outline-primary btn-sm">
                            <i class="fas fa-tasks me-1"></i>Assign Judges
                        </a>
                    </div>
                </div>

                <?php if ($message): ?>
                    <?php echo $message; ?>
                <?php endif; ?>

                <div class="row g-3">
                    <!-- Add New Judge -->
                    <div class="col-lg-6">
                        <div class="form-section p-3">
                            <h6 class="mb-3">
                                <i class="fas fa-user-plus text-success me-2"></i>Add New Judge
                            </h6>

                            <form method="post" id="addJudgeForm" class="needs-validation" novalidate>
                                <div class="mb-3">
                                    <label for="name" class="form-label fw-bold required">Judge Name</label>
                                    <input type="text" class="form-control form-control-sm" id="name" name="name" required 
                                           placeholder="Enter judge's full name">
                                    <div class="form-text small">
                                        <i class="fas fa-info-circle me-1"></i>This will be used to generate the login username
                                    </div>
                                    <div class="invalid-feedback">Please provide a valid judge name.</div>
                                </div>
                                
                                <div class="mb-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="is_head" id="is_head">
                                        <label class="form-check-label fw-bold" for="is_head">
                                            <i class="fas fa-star text-warning me-1"></i>
                                            Head Judge
                                        </label>
                                        <div class="form-text small">Head judges have additional administrative privileges</div>
                                    </div>
                                </div>
                                
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-success" id="submitBtn">
                                        <i class="fas fa-plus-circle me-2"></i>Add Judge
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Judge Statistics -->
                    <div class="col-lg-6">
                        <div class="form-section p-3">
                            <h6 class="mb-3">
                                <i class="fas fa-chart-bar text-success me-2"></i>Judge Statistics
                            </h6>
                            
                            <div class="row g-2">
                                <div class="col-6">
                                    <div class="text-center p-2 bg-light rounded">
                                        <div class="h4 mb-1 text-primary"><?= count($judges) ?></div>
                                        <small class="text-muted">Total Judges</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-2 bg-light rounded">
                                        <div class="h4 mb-1 text-warning">
                                            <?= count(array_filter($judges, function($j) { return $j['judge_id'] == 1; })) ?>
                                        </div>
                                        <small class="text-muted">Head Judges</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-2 bg-light rounded">
                                        <div class="h4 mb-1 text-success">
                                            <?= count(array_filter($judges, function($j) { return $j['event_count'] > 0; })) ?>
                                        </div>
                                        <small class="text-muted">Active Judges</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-2 bg-light rounded">
                                        <div class="h4 mb-1 text-info">
                                            <?= array_sum(array_column($judges, 'event_count')) ?>
                                        </div>
                                        <small class="text-muted">Total Assignments</small>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mt-3 pt-2 border-top">
                                <div class="d-flex justify-content-between align-items-center">
                                    <small class="text-muted">
                                        <i class="fas fa-clock me-1"></i>Last updated: <?= date('M d, Y H:i') ?>
                                    </small>
                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="location.reload()">
                                        <i class="fas fa-sync-alt me-1"></i>Refresh
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Judges List -->
                <div class="mt-3">
                    <div class="form-section">
                        <div class="p-3 border-bottom">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="mb-1">
                                        <i class="fas fa-list text-success me-2"></i>All Judges
                                    </h6>
                                    <p class="text-muted mb-0 small">Manage existing judge accounts and assignments</p>
                                </div>
                                <span class="badge bg-secondary"><?= count($judges) ?> Total</span>
                            </div>
                        </div>
                        
                        <div class="p-0">
                            <?php if (count($judges) > 0): ?>
                                <div class="table-responsive">
                                    <table class="table table-hover table-sm mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th class="ps-3"><i class="fas fa-hashtag me-1"></i>ID</th>
                                                <th><i class="fas fa-user me-1"></i>Username</th>
                                                <th><i class="fas fa-star me-1"></i>Head Judge</th>
                                                <th><i class="fas fa-calendar-check me-1"></i>Events</th>
                                                <th><i class="fas fa-clock me-1"></i>Created</th>
                                                <th class="pe-3"><i class="fas fa-cogs me-1"></i>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        <?php foreach ($judges as $j): ?>
                                        <tr>
                                            <td class="ps-3">
                                                <span class="badge bg-primary"><?= $j['id'] ?></span>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <i class="fas fa-user-circle text-muted me-2"></i>
                                                    <strong><?= htmlspecialchars($j['username']) ?></strong>
                                                </div>
                                            </td>
                                            <td>
                                                <?php if ($j['judge_id'] == 1): ?>
                                                    <span class="badge bg-warning">
                                                        <i class="fas fa-star me-1"></i>Yes
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">No</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($j['event_count'] > 0): ?>
                                                    <span class="badge bg-success event-count-badge" 
                                                          onclick="viewJudgeEvents(<?= $j['id'] ?>, '<?= htmlspecialchars($j['username']) ?>')"
                                                          title="Click to view assigned events">
                                                        <i class="fas fa-calendar-check me-1"></i><?= $j['event_count'] ?> Events
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-light text-dark">
                                                        <i class="fas fa-calendar-times me-1"></i>No Events
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <small class="text-muted">
                                                    <?= date('M d, Y', strtotime($j['created_at'])) ?>
                                                </small>
                                            </td>
                                            <td class="pe-3">
                                                <div class="btn-group btn-group-sm">
                                                    <button type="button" class="btn btn-outline-info" 
                                                            onclick="viewJudgeInfo(<?= $j['id'] ?>, '<?= htmlspecialchars($j['username']) ?>', '<?= htmlspecialchars($j['password']) ?>', <?= $j['judge_id'] ?>, '<?= $j['created_at'] ?>')"
                                                            title="View Judge Information">
                                                        <i class="fas fa-info-circle"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-primary" 
                                                            onclick="editJudge(<?= $j['id'] ?>, '<?= htmlspecialchars($j['username']) ?>', <?= $j['judge_id'] ?>)"
                                                            title="Edit Judge">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    
                                                    <div class="dropdown d-inline">
                                                        <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" 
                                                                data-bs-toggle="dropdown" aria-expanded="false" title="More Actions">
                                                            <i class="fas fa-ellipsis-h"></i>
                                                        </button>
                                                        <ul class="dropdown-menu">
                                                            <li><h6 class="dropdown-header">Judge Actions</h6></li>
                                                            <li><a class="dropdown-item" href="judge_assign.php?judge_id=<?= $j['id'] ?>">
                                                                <i class="fas fa-tasks me-2"></i>Assign to Events
                                                            </a></li>
                                                            <li><a class="dropdown-item" href="#" onclick="printJudgeCredentials(<?= $j['id'] ?>, '<?= htmlspecialchars($j['username']) ?>', '<?= htmlspecialchars($j['password']) ?>')">
                                                                <i class="fas fa-print me-2"></i>Print Credentials
                                                            </a></li>
                                                            <li><a class="dropdown-item" href="#" onclick="sendCredentialsEmail(<?= $j['id'] ?>)">
                                                                <i class="fas fa-envelope me-2"></i>Email Credentials
                                                            </a></li>
                                                            <li><hr class="dropdown-divider"></li>
                                                            <li><h6 class="dropdown-header">Danger Zone</h6></li>
                                                            <li>
                                                                <form method="post" class="d-inline w-100" 
                                                                      onsubmit="return confirm('Are you sure you want to delete this judge?\\n\\nThis will permanently remove:\\n- Judge account\\n- All associated scores\\n- Event assignments');">
                                                                    <input type="hidden" name="delete_id" value="<?= $j['id'] ?>">
                                                                    <button type="submit" class="dropdown-item text-danger">
                                                                        <i class="fas fa-trash me-2"></i>Delete Judge
                                                                    </button>
                                                                </form>
                                                            </li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-users fa-3x opacity-25"></i>
                                <h6 class="mt-3">No Judges Added Yet</h6>
                                <p class="small">Add your first judge using the form above.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- View Judge Info Modal -->
    <div class="modal fade" id="viewJudgeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-info text-white py-2">
                    <h6 class="modal-title">
                        <i class="fas fa-info-circle me-2"></i>Judge Information
                    </h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-3">
                    <div class="alert alert-info">
                        <h6><i class="fas fa-user-check me-2"></i>Judge Details</h6>
                        <hr>
                        <div id="judgeInfoContent">
                            <!-- Content will be populated by JavaScript -->
                        </div>
                        <hr>
                        <small class="text-muted">
                            <i class="fas fa-shield-check me-1"></i>
                            This information should be kept secure and shared only with the judge.
                        </small>
                    </div>
                    
                    <div class="d-flex gap-2 mt-3">
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="copyCredentials()">
                            <i class="fas fa-clipboard me-1"></i>Copy Credentials
                        </button>
                        <button type="button" class="btn btn-outline-success btn-sm" onclick="printCredentials()">
                            <i class="fas fa-print me-1"></i>Print Info
                        </button>
                    </div>
                </div>
                <div class="modal-footer py-2">
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- View Judge Events Modal -->
    <div class="modal fade" id="viewJudgeEventsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-success text-white py-2">
                    <h6 class="modal-title">
                        <i class="fas fa-calendar-check me-2"></i>Judge Event Assignments
                    </h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-3">
                    <div class="mb-3">
                        <h6><i class="fas fa-user-tie me-2"></i>Judge: <span id="judgeEventsName" class="text-primary"></span></h6>
                    </div>
                    
                    <div id="judgeEventsContent">
                        <div class="text-center">
                            <div class="spinner-border spinner-border-sm text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2 small">Loading events...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer py-2">
                    <a href="judge_assign.php" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-cogs me-1"></i>Manage Assignments
                    </a>
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Judge Modal -->
    <div class="modal fade" id="editJudgeModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header py-2">
                    <h6 class="modal-title">
                        <i class="fas fa-edit me-2"></i>Edit Judge
                    </h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="post" id="editJudgeForm">
                    <div class="modal-body p-3">
                        <input type="hidden" name="edit_id" id="edit_id">
                        
                        <div class="mb-3">
                            <label class="form-label fw-bold">Username</label>
                            <input type="text" class="form-control form-control-sm" name="edit_username" id="edit_username" required>
                        </div>
                        
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="edit_is_head" id="edit_is_head">
                            <label class="form-check-label fw-bold" for="edit_is_head">
                                <i class="fas fa-star text-warning me-1"></i>
                                Head Judge
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer py-2">
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary btn-sm">
                            <i class="fas fa-check me-1"></i>Update Judge
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

  
    <script>
        let currentJudgeInfo = {};
        
        function viewJudgeInfo(id, username, password, isHead, createdAt) {
            // Store current judge info
            currentJudgeInfo = {
                id: id,
                username: username,
                password: password,
                isHead: isHead,
                createdAt: createdAt
            };
            
            // Format the date
            const formattedDate = new Date(createdAt).toLocaleString();
            
            // Build the content
            const content = `
                <strong>User ID:</strong> <span class="badge bg-primary">${id}</span><br>
                <strong>Login Username:</strong> <code>${username}</code><br>
                <strong>Password:</strong> <code>${password}</code><br>
                <strong>Head Judge:</strong> ${isHead == 1 ? '<span class="badge bg-warning">Yes</span>' : '<span class="badge bg-secondary">No</span>'}<br>
                <strong>Created:</strong> ${formattedDate}
            `;
            
            document.getElementById('judgeInfoContent').innerHTML = content;
            
            const modal = new bootstrap.Modal(document.getElementById('viewJudgeModal'));
            modal.show();
        }
        
        function viewJudgeEvents(judgeId, judgeName) {
            document.getElementById('judgeEventsName').textContent = judgeName;
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('viewJudgeEventsModal'));
            modal.show();
            
            // Reset content to loading state
            document.getElementById('judgeEventsContent').innerHTML = `
                <div class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading events...</p>
                </div>
            `;
            
            // Fetch judge events via AJAX
            fetch(`get_judge_events.php?judge_id=${judgeId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayJudgeEvents(data.events);
                    } else {
                        document.getElementById('judgeEventsContent').innerHTML = `
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                Error loading events: ${data.message || 'Unknown error'}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('judgeEventsContent').innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            Failed to load events. Please try again.
                        </div>
                    `;
                });
        }
        
        function displayJudgeEvents(events) {
            const content = document.getElementById('judgeEventsContent');
            
            if (events.length === 0) {
                content.innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-calendar-times display-4 opacity-25"></i>
                        <h6 class="mt-3">No Events Assigned</h6>
                        <p>This judge is not currently assigned to any events.</p>
                        <a href="judge_assign.php" class="btn btn-outline-primary">
                            <i class="fas fa-plus-circle me-1"></i>Assign to Events
                        </a>
                    </div>
                `;
                return;
            }
            
            let html = `<h6 class="mb-3"><i class="fas fa-list-check me-2"></i>Assigned Events (${events.length}):</h6>`;
            
            events.forEach(event => {
                const eventDate = new Date(event.date).toLocaleDateString();
                const status = new Date(event.date) < new Date() ? 'completed' : 'upcoming';
                const statusBadge = status === 'completed' ? 
                    '<span class="badge bg-secondary">Completed</span>' : 
                    '<span class="badge bg-success">Upcoming</span>';
                
                html += `
                    <div class="event-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">
                                    <a href="events.php?event_id=${event.id}" class="text-decoration-none">
                                        <i class="fas fa-calendar-check me-1"></i>${event.name}
                                    </a>
                                </h6>
                                <p class="mb-1 text-muted small">
                                    <i class="fas fa-calendar me-1"></i>${eventDate}
                                    ${event.location ? `<span class="ms-2"><i class="fas fa-map-marker-alt me-1"></i>${event.location}</span>` : ''}
                                </p>
                                ${event.description ? `<p class="mb-0 text-muted small">${event.description}</p>` : ''}
                            </div>
                            <div class="ms-3">
                                ${statusBadge}
                                <div class="btn-group btn-group-sm mt-1">
                                    <a href="events.php?event_id=${event.id}" class="btn btn-outline-primary btn-sm" title="View Event">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="judge_assign.php?event_id=${event.id}" class="btn btn-outline-secondary btn-sm" title="Manage Assignments">
                                        <i class="fas fa-users"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            content.innerHTML = html;
        }
        
        function copyCredentials() {
            const text = `Judge Login Credentials
Username: ${currentJudgeInfo.username}
Password: ${currentJudgeInfo.password}
Head Judge: ${currentJudgeInfo.isHead == 1 ? 'Yes' : 'No'}
User ID: ${currentJudgeInfo.id}`;
            
            navigator.clipboard.writeText(text).then(() => {
                // Show success message
                const toast = document.createElement('div');
                toast.className = 'toast align-items-center text-white bg-success border-0 position-fixed top-0 end-0 m-3';
                toast.setAttribute('role', 'alert');
                toast.style.zIndex = '9999';
                toast.innerHTML = `
                    <div class="d-flex">
                        <div class="toast-body">
                            <i class="fas fa-check-circle me-2"></i>Credentials copied to clipboard!
                        </div>
                        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                    </div>
                `;
                document.body.appendChild(toast);
                const bsToast = new bootstrap.Toast(toast);
                bsToast.show();
                
                // Remove toast after it's hidden
                toast.addEventListener('hidden.bs.toast', () => {
                    document.body.removeChild(toast);
                });
            }).catch(() => {
                alert('Failed to copy to clipboard. Please copy manually.');
            });
        }
        
        function printCredentials() {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Judge Credentials</title>
                    <style>
                        body { font-family: 'Inter', Arial, sans-serif; padding: 20px; }
                        .header { text-align: center; margin-bottom: 30px; }
                        .info { line-height: 2; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h2>Judge Login Credentials</h2>
                    </div>
                    <div class="info">
                        <strong>User ID:</strong> ${currentJudgeInfo.id}<br>
                        <strong>Username:</strong> ${currentJudgeInfo.username}<br>
                        <strong>Password:</strong> ${currentJudgeInfo.password}<br>
                        <strong>Head Judge:</strong> ${currentJudgeInfo.isHead == 1 ? 'Yes' : 'No'}<br>
                        <strong>Created:</strong> ${new Date(currentJudgeInfo.createdAt).toLocaleString()}
                    </div>
                    <div style="margin-top: 30px; font-size: 12px; color: #666;">
                        <strong>Note:</strong> Keep these credentials secure. Share only with the designated judge.
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }

        function editJudge(id, username, isHead) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_username').value = username;
            document.getElementById('edit_is_head').checked = isHead == 1;
            
            const modal = new bootstrap.Modal(document.getElementById('editJudgeModal'));
            modal.show();
        }

        // New dropdown action functions
        function printJudgeCredentials(id, username, password) {
            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Judge Credentials</title>
                    <style>
                        body { font-family: 'Inter', Arial, sans-serif; padding: 20px; }
                        .header { text-align: center; margin-bottom: 30px; }
                        .info { line-height: 2; }
                        .credentials { background: #f8f9fa; padding: 20px; border-radius: 8px; margin: 20px 0; }
                    </style>
                </head>
                <body>
                    <div class="header">
                        <h2>Judge Login Credentials</h2>
                        <p>Style Score System</p>
                    </div>
                    <div class="credentials">
                        <h3>Login Information</h3>
                        <div class="info">
                            <strong>Judge ID:</strong> ${id}<br>
                            <strong>Username:</strong> ${username}<br>
                            <strong>Password:</strong> ${password}<br>
                            <strong>Login URL:</strong> ${window.location.origin}/judge/login.php
                        </div>
                    </div>
                    <div style="margin-top: 30px; font-size: 12px; color: #666;">
                        <strong>Note:</strong> Keep these credentials secure. Share only with the designated judge.
                        <br><strong>Generated:</strong> ${new Date().toLocaleString()}
                    </div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.print();
        }

        function sendCredentialsEmail(judgeId) {
            // This would typically make an AJAX call to send email
            if (confirm('Send login credentials to this judge via email?')) {
                // Placeholder for email functionality
                fetch('send_judge_credentials.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        judge_id: judgeId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Credentials sent successfully!');
                    } else {
                        alert('Failed to send credentials: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Failed to send credentials. Please try again.');
                });
            }
        }

        // Add form validation and submission feedback
        (function() {
            'use strict';
            window.addEventListener('load', function() {
                // Fetch all the forms we want to apply custom Bootstrap validation styles to
                var forms = document.getElementsByClassName('needs-validation');
                
                // Loop over them and prevent submission
                var validation = Array.prototype.filter.call(forms, function(form) {
                    form.addEventListener('submit', function(event) {
                        if (form.checkValidity() === false) {
                            event.preventDefault();
                            event.stopPropagation();
                        } else {
                            // Show loading state
                            const submitBtn = form.querySelector('#submitBtn');
                            if (submitBtn) {
                                submitBtn.disabled = true;
                                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Adding Judge...';
                            }
                        }
                        form.classList.add('was-validated');
                    }, false);
                });
            }, false);
        })();

        // Handle edit form submission
        document.getElementById('editJudgeForm').addEventListener('submit', function(e) {
            // Allow normal form submission to handle the redirect properly
            const modal = bootstrap.Modal.getInstance(document.getElementById('editJudgeModal'));
            if (modal) {
                modal.hide();
            }
        });

        // Clean URL after showing message (remove query parameters)
        if (window.location.search.includes('msg=')) {
            const cleanUrl = window.location.pathname;
            window.history.replaceState({}, document.title, cleanUrl);
        }
    </script>
</body>
</html>