<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

include '../includes/auth_simple.php';
include '../includes/db.php';

$judge_id = $_SESSION['user_id'];
$judge_name = $_SESSION['username'] ?? 'Judge';

// Get judge's assigned events
$events_query = $pdo->prepare("
    SELECT DISTINCT 
        e.id,
        e.name,
        e.date,
        e.location,
        e.heats_total,
        sf.name as format_name,
        sf.sport as discipline,
        COUNT(DISTINCT ep.id) as total_participants,
        COUNT(DISTINCT s.id) as scores_submitted
    FROM events e
    LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
    LEFT JOIN event_participants ep ON e.id = ep.event_id
    LEFT JOIN runs r ON ep.id = r.event_participant_id
    LEFT JOIN scores s ON r.id = s.run_id AND s.judge_id = ?
    WHERE e.id IN (
        SELECT DISTINCT event_id 
        FROM judge_assignments 
        WHERE judge_id = ?
    )
    GROUP BY e.id
    ORDER BY e.date DESC
");
$events_query->execute([$judge_id, $judge_id]);
$assigned_events = $events_query->fetchAll(PDO::FETCH_ASSOC);

// Get recent scores overview
$recent_scores_query = $pdo->prepare("
    SELECT 
        s.id,
        s.score_value as total_score,
        s.created_at,
        r.run_number,
        ep.event_id,
        ep.heat_number,
        ep.bib_number,
        e.name as event_name,
        p.first_name,
        p.last_name
    FROM scores s
    JOIN runs r ON s.run_id = r.id
    JOIN event_participants ep ON r.event_participant_id = ep.id
    JOIN events e ON ep.event_id = e.id
    JOIN participants p ON ep.participant_id = p.id
    WHERE s.judge_id = ?
    ORDER BY s.created_at DESC
    LIMIT 10
");
$recent_scores_query->execute([$judge_id]);
$recent_scores = $recent_scores_query->fetchAll(PDO::FETCH_ASSOC);

// Get active heat if any
$active_heat_query = $pdo->prepare("
    SELECT 
        ehs.event_id,
        ehs.heat_number,
        ehs.heat_name,
        ehs.active_run,
        e.name as event_name
    FROM event_heat_settings ehs
    JOIN events e ON ehs.event_id = e.id
    WHERE ehs.is_active = 1
    AND e.id IN (
        SELECT DISTINCT event_id 
        FROM judge_assignments 
        WHERE judge_id = ?
    )
    LIMIT 1
");
$active_heat_query->execute([$judge_id]);
$active_heat = $active_heat_query->fetch(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Judge Dashboard - StyleScore</title>
    <?php include_once '../includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>

<div class="container-fluid p-4">
    <div class="row justify-content-center">
        <div class="col-12 col-xl-10">
            
            <!-- Header -->
            <div class="d-flex justify-content-between align-items-start flex-column flex-md-row mb-4">
                <h2 class="mb-2 mb-md-0">
                    <i class="fas fa-gavel me-2 text-primary"></i>
                    Judge Dashboard
                </h2>
                <div class="d-flex flex-column align-items-start align-items-md-end">
                    <small class="text-muted">Logged in as</small>
                    <strong><?= htmlspecialchars($judge_name) ?></strong>
                </div>
            </div>

            <!-- Active Heat Alert -->
            <?php if ($active_heat): ?>
                <div class="alert alert-success border-0 shadow-sm mb-4">
                    <div class="d-flex justify-content-between align-items-center flex-column flex-md-row gap-3">
                        <div class="text-center text-md-start w-100">
                            <h5 class="mb-2">
                                <i class="fas fa-circle fa-fade me-2"></i>
                                Active Heat Now!
                            </h5>
                            <p class="mb-0">
                                <strong><?= htmlspecialchars($active_heat['event_name']) ?></strong><br>
                                Heat <?= $active_heat['heat_number'] ?>
                                <?php if (!empty($active_heat['heat_name'])): ?>
                                    (<?= htmlspecialchars($active_heat['heat_name']) ?>)
                                <?php endif; ?>
                                - Run <?= $active_heat['active_run'] ?>
                            </p>
                        </div>
                        <a href="score.php?event_id=<?= $active_heat['event_id'] ?>&heat=<?= $active_heat['heat_number'] ?>" 
                           class="btn btn-success btn-lg w-100 w-md-auto">
                            <i class="fas fa-play me-2"></i>Start Scoring
                        </a>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Statistics Cards -->
                <div class="row g-3 mb-4">
                    <div class="col-6 col-md-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center p-3">
                                <i class="fas fa-calendar-check fa-2x text-primary mb-2"></i>
                                <h3 class="mb-1"><?= count($assigned_events) ?></h3>
                                <small class="text-muted d-block">Events</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center p-3">
                                <i class="fas fa-clipboard-check fa-2x text-success mb-2"></i>
                                <h3 class="mb-1">
                                    <?php 
                                    $total_scores = array_sum(array_column($assigned_events, 'scores_submitted'));
                                    echo $total_scores;
                                    ?>
                                </h3>
                                <small class="text-muted d-block">Scores</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center p-3">
                                <i class="fas fa-users fa-2x text-info mb-2"></i>
                                <h3 class="mb-1">
                                    <?php 
                                    $total_participants = array_sum(array_column($assigned_events, 'total_participants'));
                                    echo $total_participants;
                                    ?>
                                </h3>
                                <small class="text-muted d-block">Participants</small>
                            </div>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="card border-0 shadow-sm h-100">
                            <div class="card-body text-center p-3">
                                <i class="fas fa-fire fa-2x text-warning mb-2"></i>
                                <h3 class="mb-1">
                                    <?php 
                                    $total_heats = array_sum(array_column($assigned_events, 'heats_total'));
                                    echo $total_heats;
                                    ?>
                                </h3>
                                <small class="text-muted d-block">Heats</small>
                            </div>
                        </div>
                    </div>
                </div>

            <div class="row">
                <div class="col-12">
                <!-- Assigned Events -->
                <div class="mb-3">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-calendar-alt me-2"></i>
                                My Assigned Events
                            </h5>
                        </div>
                        <div class="card-body p-2 p-md-3">
                            <?php if (empty($assigned_events)): ?>
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-info-circle fa-3x mb-3"></i>
                                    <p>No events assigned yet.</p>
                                    <small>Contact the event administrator to be assigned to events.</small>
                                </div>
                            <?php else: ?>
                                <div class="list-group list-group-flush">
                                    <?php foreach ($assigned_events as $event): ?>
                                        <div class="list-group-item px-2 px-md-3">
                                            <div class="d-flex justify-content-between align-items-start flex-column flex-md-row gap-2">
                                                <div class="flex-grow-1 w-100">
                                                    <h6 class="mb-2">
                                                        <i class="fas fa-trophy me-2 text-warning"></i>
                                                        <?= htmlspecialchars($event['name']) ?>
                                                    </h6>
                                                    <div class="small text-muted mb-2">
                                                        <div class="mb-1">
                                                            <i class="fas fa-calendar me-1"></i>
                                                            <?= date('F j, Y', strtotime($event['date'])) ?>
                                                        </div>
                                                        <?php if ($event['location']): ?>
                                                            <div class="mb-1">
                                                                <i class="fas fa-map-marker-alt me-1"></i>
                                                                <?= htmlspecialchars($event['location']) ?>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="d-flex gap-2 flex-wrap">
                                                        <span class="badge bg-light text-dark">
                                                            <i class="fas fa-fire me-1"></i>
                                                            <?= $event['heats_total'] ?> Heats
                                                        </span>
                                                        <span class="badge bg-light text-dark">
                                                            <i class="fas fa-users me-1"></i>
                                                            <?= $event['total_participants'] ?> Participants
                                                        </span>
                                                        <?php if ($event['format_name']): ?>
                                                            <span class="badge bg-info text-white">
                                                                <?= htmlspecialchars($event['format_name']) ?>
                                                            </span>
                                                        <?php endif; ?>
                                                        <?php if ($event['scores_submitted'] > 0): ?>
                                                            <span class="badge bg-success">
                                                                <i class="fas fa-check me-1"></i>
                                                                <?= $event['scores_submitted'] ?> Scores
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="w-100 w-md-auto mt-2 mt-md-0">
                                                    <a href="score.php?event_id=<?= $event['id'] ?>" 
                                                       class="btn btn-primary btn-sm w-100">
                                                        <i class="fas fa-gavel me-1"></i>Score
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Recent Scores Overview -->
                <div class="mb-3">
                    <div class="card border-0 shadow-sm">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0">
                                <i class="fas fa-history me-2"></i>
                                My Recent Scores
                            </h5>
                        </div>
                        <div class="card-body p-2 p-md-3">
                            <?php if (empty($recent_scores)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-clipboard fa-2x mb-3"></i>
                                    <p>No scores submitted yet.</p>
                                    <small>Your recent scoring activity will appear here.</small>
                                </div>
                            <?php else: ?>
                                <div class="list-group list-group-flush" style="max-height: 500px; overflow-y: auto;">
                                    <?php foreach ($recent_scores as $score): ?>
                                        <div class="list-group-item px-2 px-md-3 py-2">
                                            <div class="d-flex justify-content-between align-items-start flex-column flex-sm-row gap-2">
                                                <div class="small flex-grow-1">
                                                    <div class="fw-bold text-dark mb-1">
                                                        #<?= $score['bib_number'] ?> 
                                                        <?= htmlspecialchars($score['first_name'] . ' ' . $score['last_name']) ?>
                                                    </div>
                                                    <div class="text-muted mb-1">
                                                        <?= htmlspecialchars($score['event_name']) ?>
                                                    </div>
                                                    <div class="text-muted mb-1">
                                                        Heat <?= $score['heat_number'] ?> • Run <?= $score['run_number'] ?>
                                                    </div>
                                                    <div class="text-muted" style="font-size: 0.75rem;">
                                                        <i class="fas fa-clock me-1"></i>
                                                        <?= date('M j, g:i A', strtotime($score['created_at'])) ?>
                                                    </div>
                                                </div>
                                                <div class="text-start text-sm-end">
                                                    <div class="badge bg-primary fs-6">
                                                        <?= number_format($score['total_score'], 2) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                
                <!-- Quick Actions -->
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-light">
                        <h5 class="mb-0">
                            <i class="fas fa-bolt me-2 text-warning"></i>
                            Quick Actions
                        </h5>
                    </div>
                    <div class="card-body p-2 p-md-3">
                        <div class="row g-2 g-md-3">
                            <div class="col-6 col-md-4">
                                <a href="score.php" class="btn btn-outline-primary w-100 py-2 py-md-3">
                                    <i class="fas fa-gavel fa-lg fa-md-2x d-block mb-2"></i>
                                    <strong class="d-block">Score Panel</strong>
                                    <small class="d-none d-md-block text-muted">Enter scores</small>
                                </a>
                            </div>
                            <div class="col-6 col-md-4">
                                <a href="../public_event_dashboard.php" class="btn btn-outline-info w-100 py-2 py-md-3">
                                    <i class="fas fa-tv fa-lg fa-md-2x d-block mb-2"></i>
                                    <strong class="d-block">Live Dashboard</strong>
                                    <small class="d-none d-md-block text-muted">View results</small>
                                </a>
                            </div>
                            <div class="col-6 col-md-4">
                                <a href="score_panel.html" class="btn btn-outline-success w-100 py-2 py-md-3">
                                    <i class="fas fa-clipboard-list fa-lg fa-md-2x d-block mb-2"></i>
                                    <strong class="d-block">Modern Panel</strong>
                                    <small class="d-none d-md-block text-muted">New interface</small>
                                </a>
                            </div>
                            <div class="col-6 col-md-4">
                                <a href="http://192.168.1.42/v2/logout.php" class="btn btn-outline-warning w-100 py-2 py-md-3">
                                    <i class="fas fa-sign-out-alt fa-lg fa-md-2x d-block mb-2"></i>
                                    <strong class="d-block">Logout</strong>
                                    <small class="d-none d-md-block text-muted">Sign out</small>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    </div>
</div>

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