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

$message = '';

// Handle judge update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['judge_id'])) {
    $judge_id = intval($_POST['judge_id']);
    $is_head = isset($_POST['is_head']) ? 1 : 0;
    $name = trim($_POST['name'] ?? '');

    $stmt = $pdo->prepare("UPDATE judges SET name = ?, is_head = ? WHERE id = ?");
    if ($stmt->execute([$name, $is_head, $judge_id])) {
        $message = '<div class="alert alert-success">Judge updated successfully.</div>';
    } else {
        $message = '<div class="alert alert-danger">Failed to update judge.</div>';
    }
}

// Handle judge deletion with event assignment check
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_judge_id'])) {
    $delete_id = intval($_POST['delete_judge_id']);

    // Check if judge is assigned to any event
    $check_stmt = $pdo->prepare("SELECT COUNT(*) FROM judge_assignments WHERE judge_id = ?");
    $check_stmt->execute([$delete_id]);
    $is_assigned = $check_stmt->fetchColumn();

    if ($is_assigned > 0) {
        $message = '<div class="alert alert-warning">❌ This judge is assigned to an event and cannot be deleted.</div>';
    } else {
        // Proceed to delete
        $stmt = $pdo->prepare("DELETE FROM judges WHERE id = ?");
        if ($stmt->execute([$delete_id])) {
            $message = '<div class="alert alert-success">Judge deleted successfully.</div>';
        } else {
            $message = '<div class="alert alert-danger">Failed to delete judge.</div>';
        }
    }
}

// Load judges
$judges = $pdo->query("SELECT * FROM judges ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);

// Fetch judge assignments count
$assignments = $pdo->query("SELECT judge_id, COUNT(*) as count FROM judge_assignments GROUP BY judge_id")->fetchAll(PDO::FETCH_KEY_PAIR);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Manage Judges</title>
    <?php include_once '../includes/stylesheets.php'; ?>
<!-- style skin holder -->
    <script>
    function showAssignedEvents(judgeId) {
        fetch('get_judge_events.php?judge_id=' + judgeId)
            .then(response => response.json())
            .then(data => {
                let content = '<ul>';
                data.forEach(event => {
                    content += '<li><a href="judge_assign.php?event_id=' + event.id + '">' + event.name + ' (' + event.date + ')</a></li>';
                });
                content += '</ul>';
                document.getElementById('eventList').innerHTML = content;
                var myModal = new bootstrap.Modal(document.getElementById('eventsModal'));
                myModal.show();
            });
    }
    </script>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>
<div class="container-fluid container-StyleScore p-4">
    <h2>Manage Judges</h2>
    <?php echo $message; ?>
    <table class="table table-bordered bg-white">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Is Head Judge</th>
                <th>Assigned</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($judges as $judge): 
            $assigned_count = $assignments[$judge['id']] ?? 0;
        ?>
            <tr>
                <form method="post" class="d-flex flex-wrap align-items-center gap-2">
                    <td><?= $judge['id'] ?></td>
                    <td>
                        <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($judge['name']) ?>" required>
                    </td>
                    <td>
                        <input type="checkbox" name="is_head" <?= $judge['is_head'] ? 'checked' : '' ?>>
                    </td>
                    <td>
    <?= $assigned_count ?>
    <?php if ($assigned_count > 0): ?>
        <a href="javascript:void(0)" onclick="showAssignedEvents(<?= $judge['id'] ?>)">📋 View</a>
    <?php endif; ?>
</td>
                    <td class="text-nowrap">
                        <input type="hidden" name="judge_id" value="<?= $judge['id'] ?>">
                        <button type="submit" class="btn btn-sm btn-primary">Update</button>
                        <?php if ($assigned_count > 0): ?>
                            <button class="btn btn-sm btn-secondary" disabled title="Judge assigned to event">
                                🔒 <?= $assigned_count ?>x Assigned
                            </button>
                        <?php else: ?>
                            <form method="post" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this judge?');">
                                <input type="hidden" name="delete_judge_id" value="<?= $judge['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-danger">🗑 Delete</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </form>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<!-- Modal -->
<div class="modal fade" id="eventsModal" tabindex="-1" aria-labelledby="eventsModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="eventsModalLabel">Assigned Events</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="eventList">
      </div>
    </div>
  </div>
</div>

<?php include 'footer.php'; ?>
</body>
</html>
