<?php
session_start();
include 'includes/db.php';

// Get dashboard statistics
$stats = [];

try {
    // Total events
    $stats['total_events'] = $pdo->query("SELECT COUNT(*) FROM events")->fetchColumn();

    // Active events (open for registration)
    $stats['active_events'] = $pdo->query("SELECT COUNT(*) FROM events WHERE status = 'open'")->fetchColumn();

    // Today's events
    $stats['todays_events'] = $pdo->query("SELECT COUNT(*) FROM events WHERE date = CURDATE()")->fetchColumn();

    // Total participants
    $stats['total_participants'] = $pdo->query("SELECT COUNT(*) FROM participants")->fetchColumn();

    // Total scores submitted
    $stats['total_scores'] = $pdo->query("SELECT COUNT(*) FROM scores")->fetchColumn();

    // Active judges
    $stats['active_judges'] = $pdo->query("SELECT COUNT(*) FROM judges")->fetchColumn();

    // Recent events (last 5) - using date instead of created_at
    $recent_events = $pdo->query("
        SELECT e.*, COUNT(ep.id) as participant_count 
        FROM events e 
        LEFT JOIN event_participants ep ON e.id = ep.event_id 
        GROUP BY e.id 
        ORDER BY e.date DESC 
        LIMIT 5
    ")->fetchAll(PDO::FETCH_ASSOC);

    // Upcoming events (next 5)
    $upcoming_events = $pdo->query("
        SELECT e.*, COUNT(ep.id) as participant_count 
        FROM events e 
        LEFT JOIN event_participants ep ON e.id = ep.event_id 
        WHERE e.date >= CURDATE() 
        GROUP BY e.id 
        ORDER BY e.date ASC 
        LIMIT 5
    ")->fetchAll(PDO::FETCH_ASSOC);

    // Recent scoring activity (last 10 scores) - simplified query
    $recent_scores = [];
    try {
        $recent_scores = $pdo->query("
            SELECT s.score_value, s.created_at,
                   e.name as event_name, 
                   p.first_name, p.last_name, 
                   j.name as judge_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
            JOIN judges j ON s.judge_id = j.id
            ORDER BY s.id DESC
            LIMIT 10
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        $recent_scores = [];
    }

} catch (Exception $e) {
    $stats = [
        'total_events' => 0,
        'active_events' => 0,
        'todays_events' => 0,
        'total_participants' => 0,
        'total_scores' => 0,
        'active_judges' => 0
    ];
    $recent_events = [];
    $upcoming_events = [];
    $recent_scores = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StyleScore Dashboard</title>
    <?php include_once 'includes/stylesheets.php'; ?>
</head>
<body class="body-bg-aurora-bright">
    <?php include 'menu.php'; ?>

    <div class="container-fluid p-4">
        <?php       
        $use_localStorage = true;
        $show_header = false;
        include 'admin/event_actions_menu.php'; 
        ?>

        <!-- Hero Section -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-0 shadow">
                    <div class="card-body text-center py-3">
                        <h2 class="fw-bold mb-2 text-primary">
                            <i data-lucide="trophy" class="me-2"></i>StyleScore Dashboard
                        </h2>
                        <p class="mb-3 text-muted">Complete event management and live scoring platform</p>
                        <div class="d-flex justify-content-center gap-2 flex-wrap">
                            <a href="admin/event_create.php" class="btn btn-primary">
                                <i data-lucide="plus" class="me-1"></i>Create Event
                            </a>
                            <a href="judge/score.php" class="btn btn-outline-primary">
                                <i data-lucide="star" class="me-1"></i>Score Now
                            </a>
                            <a href="public_event_dashboard.php" target="_blank" class="btn btn-outline-secondary">
                                <i data-lucide="tv" class="me-1"></i>Public View
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white border-0">
                        <h5 class="mb-0">
                            <i data-lucide="zap" class="me-2 text-warning"></i>Quick Actions
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-2">
                            <?php
                            $quick_actions = [
                                ['title' => 'Create Event', 'url' => 'admin/event_create.php', 'icon' => 'plus', 'color' => 'success'],
                                ['title' => 'Manage Events', 'url' => 'admin/events.php', 'icon' => 'settings', 'color' => 'primary'],
                                ['title' => 'Add Participant', 'url' => 'admin/participant_add.php', 'icon' => 'user-plus', 'color' => 'info'],
                                ['title' => 'View Participants', 'url' => 'admin/participants.php', 'icon' => 'users', 'color' => 'secondary'],
                                ['title' => 'Judge Scoring', 'url' => 'judge/score.php', 'icon' => 'star', 'color' => 'warning'],
                                ['title' => 'Live Scoreboard', 'url' => 'live_scoreboard_3.php', 'icon' => 'trending-up', 'color' => 'danger'],
                                ['title' => 'Start Lists', 'url' => 'admin/event_start_list.php', 'icon' => 'list', 'color' => 'dark'],
                                ['title' => 'Scoring Formats', 'url' => 'admin/scoring_formats.php', 'icon' => 'cog', 'color' => 'primary'],
                                ['title' => 'Figures Dictionary', 'url' => 'admin/figures_viewer.php', 'icon' => 'book-open', 'color' => 'info'],
                                ['title' => 'User Management', 'url' => 'admin/user_management.php', 'icon' => 'user-cog', 'color' => 'danger'],
                                ['title' => 'Token System', 'url' => 'admin/token_management.php', 'icon' => 'coins', 'color' => 'warning'],
                                ['title' => 'Results Styling', 'url' => 'admin/results_styling.php', 'icon' => 'palette', 'color' => 'secondary']
                            ];
                            ?>
                            <?php foreach ($quick_actions as $action): ?>
                                <div class="col-md-6 col-lg-4 col-xl-3">
                                    <a href="<?= $action['url'] ?>" class="btn btn-outline-<?= $action['color'] ?> w-100 text-start">
                                        <i data-lucide="<?= $action['icon'] ?>" class="me-2"></i><?= $action['title'] ?>
                                    </a>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Events & Activity -->
        <div class="row g-4">
            <!-- Upcoming Events -->
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-0">
                        <h5 class="mb-0">
                            <i data-lucide="calendar-plus" class="me-2 text-primary"></i>Upcoming Events
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($upcoming_events)): ?>
                            <div class="text-center text-muted py-4">
                                <i data-lucide="calendar-x" class="mb-3 opacity-50" style="width: 48px; height: 48px;"></i>
                                <p class="mb-0">No upcoming events scheduled</p>
                                <a href="admin/event_create.php" class="btn btn-primary btn-sm mt-2">
                                    <i data-lucide="plus" class="me-1"></i>Create First Event
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($upcoming_events as $event): ?>
                                    <div class="list-group-item px-0 py-3 border-start border-primary border-3">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <h6 class="fw-bold mb-1"><?= htmlspecialchars($event['name']) ?></h6>
                                                <p class="text-muted mb-1 small">
                                                    <i data-lucide="calendar" class="me-1" style="width: 16px; height: 16px;"></i>
                                                    <?= date('M d, Y', strtotime($event['date'])) ?>
                                                </p>
                                                <p class="text-muted mb-0 small">
                                                    <i data-lucide="map-pin" class="me-1" style="width: 16px; height: 16px;"></i>
                                                    <?= htmlspecialchars($event['location'] ?? 'Location TBD') ?>
                                                </p>
                                            </div>
                                            <span class="badge bg-primary"><?= $event['participant_count'] ?> participants</span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Recent Scoring Activity -->
            <div class="col-lg-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-header bg-white border-0">
                        <h5 class="mb-0">
                            <i data-lucide="activity" class="me-2 text-success"></i>Recent Scoring Activity
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recent_scores)): ?>
                            <div class="text-center text-muted py-4">
                                <i data-lucide="star" class="mb-3 opacity-50" style="width: 48px; height: 48px;"></i>
                                <p class="mb-0">No recent scoring activity</p>
                                <a href="judge/score.php" class="btn btn-success btn-sm mt-2">
                                    <i data-lucide="star" class="me-1"></i>Start Scoring
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach (array_slice($recent_scores, 0, 6) as $score): ?>
                                    <div class="list-group-item px-0 py-2">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <div class="fw-semibold small">
                                                    <i data-lucide="user" class="me-1 text-secondary" style="width: 16px; height: 16px;"></i>
                                                    <?= htmlspecialchars($score['first_name'] . ' ' . $score['last_name']) ?>
                                                </div>
                                                <div class="text-muted small">
                                                    <?= htmlspecialchars($score['event_name']) ?> • <?= htmlspecialchars($score['judge_name']) ?>
                                                </div>
                                            </div>
                                            <span class="badge bg-success"><?= number_format((float)$score['score_value'], 1) ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- StyleScore JavaScript includes -->
    <?php include_once __DIR__ . '/includes/scripts.php'; ?>
    
    <!-- Dashboard specific JavaScript -->
    <script>
        // Dashboard initialization
        document.addEventListener('DOMContentLoaded', function() {
            // Any dashboard-specific initialization can go here
            console.log('StyleScore Dashboard loaded successfully');
        });
    </script>

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