<?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 container-StyleScore p-4">
                    <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'admin/event_actions_menu.php'; 
            ?>
<div class="row justify-content-center col-12">
	<div class="col-10">
        <!-- Hero / Highlights -->
        <div class="row g-2 align-items-stretch mb-3">
            <div class="col-lg-8">
                <div id="highlightsCarousel" class="carousel slide card border-0 shadow-sm h-100" data-bs-ride="carousel">
                    <div class="carousel-indicators">
                        <button type="button" data-bs-target="#highlightsCarousel" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button>
                        <button type="button" data-bs-target="#highlightsCarousel" data-bs-slide-to="1" aria-label="Slide 2"></button>
                        <button type="button" data-bs-target="#highlightsCarousel" data-bs-slide-to="2" aria-label="Slide 3"></button>
                    </div>
                    <div class="carousel-inner">
                        <div class="carousel-item active">
                            <div class="border-0 shadow-none card-body p-3 p-lg-4 text-center text-white bg-primary bg-gradient">
                                <h2 class="fw-bold mb-2">
                                    <i data-lucide="trophy" class="me-2"></i>StyleScore
                                </h2>
                                <p class="mb-3">Manage events, participants, judges, heats and live scoring in one place</p>
                                <div class="d-flex justify-content-center gap-2 flex-wrap">
                                    <a href="admin/event_create.php" class="btn btn-light">
                                        <i data-lucide="plus" class="me-1"></i>Create Event
                                    </a>
                                    <a href="judge/score.php" class="btn btn-outline-light">
                                        <i data-lucide="star" class="me-1"></i>Score Now
                                    </a>
                                    <a href="public_event_dashboard.php" target="_blank" class="btn btn-outline-light">
                                        <i data-lucide="tv" class="me-1"></i>Public View
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="carousel-item">
                            <div class="border-0 shadow-none card-body p-3 p-lg-4 text-center bg-light">
                                <h3 class="fw-bold mb-2">
                                    <i data-lucide="calendar" class="text-primary me-2"></i>Upcoming Events
                                </h3>
                                <?php if (empty($upcoming_events)): ?>
                                    <p class="text-muted mb-0">No upcoming events scheduled</p>
                                <?php else: ?>
                                    <div class="d-flex justify-content-center flex-wrap gap-2">
                                        <?php foreach ($upcoming_events as $ev): ?>
                                            <span class="badge rounded-pill text-bg-primary">
                                                <?= htmlspecialchars($ev['name']) ?> · <?= date('M d', strtotime($ev['date'])) ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="carousel-item">
                            <div class="border-0 shadow-none card-body p-3 p-lg-4 text-center bg-light">
                                <h3 class="fw-bold mb-2">
                                    <i data-lucide="zap" class="text-warning me-2"></i>Quick Actions
                                </h3>
                                <div class="d-flex justify-content-center flex-wrap gap-1">
                                    <a href="admin/participants.php" class="btn btn-outline-primary btn-sm">
                                        <i data-lucide="users" class="me-1"></i>Participants
                                    </a>
                                    <a href="admin/user_management.php" class="btn btn-outline-danger btn-sm">
                                        <i data-lucide="settings" class="me-1"></i>User Management
                                    </a>
                                    <a href="admin/token_management.php" class="btn btn-outline-warning btn-sm">
                                        <i data-lucide="coins" class="me-1"></i>Token System
                                    </a>
                                    <a href="admin/event_start_list.php" class="btn btn-outline-secondary btn-sm">
                                        <i data-lucide="list" class="me-1"></i>Start Lists
                                    </a>
                                    <a href="live_scoreboard_3.php" class="btn btn-outline-info btn-sm">
                                        <i data-lucide="trending-up" class="me-1"></i>Live Board
                                    </a>
                                    <a href="admin/results_styling.php" class="btn btn-outline-dark btn-sm">
                                        <i data-lucide="palette" class="me-1"></i>Results Styling
                                    </a>
                                    <a href="admin/scoring_formats.php" class="btn btn-outline-purple btn-sm">
                                        <i data-lucide="cog" class="me-1"></i>Scoring Formats
                                    </a>
                                    <a href="admin/figures_viewer.php" class="btn btn-outline-purple btn-sm">
                                        <i data-lucide="book-open" class="me-1"></i>Figures Dictionary
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <button class="carousel-control-prev" type="button" data-bs-target="#highlightsCarousel" data-bs-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="visually-hidden">Previous</span>
                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#highlightsCarousel" data-bs-slide="next">
                        <span class="carousel-control-next-icon" aria-hidden="true"></span>
                        <span class="visually-hidden">Next</span>
                    </button>
                </div>
            </div>

            <!-- Live / Status Panel -->
            <div class="col-lg-4">
                <div class="border-0 shadow-none card border-0 shadow-sm h-100">
                    <div class="border-0 shadow-none card-body p-3">
                        <div class="d-flex align-items-center justify-content-between mb-2">
                            <h6 class="fw-bold mb-0">
                                <i data-lucide="signal" class="text-success me-2"></i>Status
                            </h6>
                            <span class="badge text-bg-success">
                                <i data-lucide="loader" class="me-1"></i>Live Ready
                            </span>
                        </div>
                        <div class="d-grid gap-1">
                            <a href="judge/score.php" class="btn btn-success btn-sm">
                                <i data-lucide="gavel" class="me-1"></i>Judge Scoring
                            </a>
                            <a href="live_scoreboard_3.php" class="btn btn-outline-success btn-sm">
                                <i data-lucide="tv" class="me-1"></i>Open Live Scoreboard
                            </a>
                            <a href="public_event_dashboard.php" class="btn btn-outline-primary btn-sm" target="_blank">
                                <i data-lucide="megaphone" class="me-1"></i>Public Event Dashboard
                            </a>
                        </div>
                        <hr class="my-3">
                        <div class="small">
                            <div class="d-flex justify-content-between">
                                <span class="text-muted">Events</span>
                                <span class="fw-semibold"><?= (int)$stats['total_events'] ?></span>
                            </div>
                            <div class="progress my-2" role="progressbar" aria-label="Active events" aria-valuenow="<?= (int)$stats['active_events'] ?>" aria-valuemin="0" aria-valuemax="<?= max(1,(int)$stats['total_events']) ?>">
                                <div class="progress-bar bg-success" style="width: <?= (int)$stats['total_events'] ? min(100, round(($stats['active_events'] / max(1,$stats['total_events']))*100)) : 0 ?>%"></div>
                            </div>
                            <div class="d-flex justify-content-between">
                                <span class="text-muted">Today</span>
                                <span class="fw-semibold"><?= (int)$stats['todays_events'] ?></span>
                            </div>
                            <div class="progress my-2">
                                <div class="progress-bar bg-warning" style="width: <?= min(100, (int)$stats['todays_events'] * 20) ?>%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- KPI Cards -->
        <div class="row g-3 mb-4">
            <?php
                $kpis = [
                    ['icon' => 'calendar', 'label' => 'Total Events', 'value' => (int)$stats['total_events'], 'bg' => 'primary'],
                    ['icon' => 'play-circle', 'label' => 'Active Events', 'value' => (int)$stats['active_events'], 'bg' => 'success'],
                    ['icon' => 'clock', 'label' => 'Today', 'value' => (int)$stats['todays_events'], 'bg' => 'warning'],
                    ['icon' => 'users', 'label' => 'Participants', 'value' => (int)$stats['total_participants'], 'bg' => 'info'],
                    ['icon' => 'star', 'label' => 'Scores', 'value' => (int)$stats['total_scores'], 'bg' => 'secondary'],
                    ['icon' => 'gavel', 'label' => 'Judges', 'value' => (int)$stats['active_judges'], 'bg' => 'dark'],
                ];
            ?>
            <?php foreach ($kpis as $k): ?>
                <div class="col-6 col-md-4 col-lg-2">
                    <div class="border-0 shadow-none card border-0 shadow-sm h-100">
                        <div class="border-0 shadow-none card-body text-center">
                            <div class="rounded-circle bg-<?= $k['bg'] ?> bg-opacity-10 d-inline-flex align-items-center justify-content-center p-3 mb-2">
                                <i data-lucide="<?= $k['icon'] ?>" class="text-<?= $k['bg'] ?> fs-3"></i>
                            </div>
                            <div class="h4 fw-bold text-<?= $k['bg'] ?> mb-0"><?= $k['value'] ?></div>
                            <small class="text-muted"><?= htmlspecialchars($k['label']) ?></small>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Quick Actions -->
        <div class="border-0 shadow-none card border-0 shadow-sm mb-3">
            <div class="border-0 shadow-none card-body p-3">
                <div class="d-flex flex-wrap gap-1 justify-content-center">
                    <a href="admin/event_create.php" class="btn btn-success btn-sm">
                        <i data-lucide="plus" class="me-1"></i>Create Event
                    </a>
                    <a href="admin/participant_add.php" class="btn btn-primary btn-sm">
                        <i data-lucide="user-plus" class="me-1"></i>Add Participant
                    </a>
                    <a href="admin/events.php" class="btn btn-secondary btn-sm">
                        <i data-lucide="settings" class="me-1"></i>Manage Events
                    </a>
                    <a href="admin/user_management.php" class="btn btn-danger btn-sm">
                        <i data-lucide="user-cog" class="me-1"></i>User Management
                    </a>
                    <a href="admin/event_start_list.php" class="btn btn-outline-secondary btn-sm">
                        <i data-lucide="list" class="me-1"></i>Start Lists
                    </a>
                    <a href="judge/score.php" class="btn btn-warning btn-sm">
                        <i data-lucide="star" class="me-1"></i>Score Event
                    </a>
                    <a href="live_scoreboard_3.php" class="btn btn-info btn-sm">
                        <i data-lucide="trending-up" class="me-1"></i>Live Scoreboard
                    </a>
                    <a href="admin/scoring_formats.php" class="btn btn-dark btn-sm">
                        <i data-lucide="cog" class="me-1"></i>Scoring Formats
                    </a>
                    <a href="admin/figures_viewer.php" class="btn btn-secondary btn-sm">
                        <i data-lucide="book-open" class="me-1"></i>View Figures
                    </a>
                </div>
            </div>
        </div>

        <!-- Tabbed Content: Upcoming vs Recent Activity -->
        <ul class="nav nav-tabs mb-2" id="dashTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="upcoming-tab" data-bs-toggle="tab" data-bs-target="#upcoming-tab-pane" type="button" role="tab" aria-controls="upcoming-tab-pane" aria-selected="true">
                    <i data-lucide="calendar-plus" class="me-1"></i>Upcoming Events
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="recent-tab" data-bs-toggle="tab" data-bs-target="#recent-tab-pane" type="button" role="tab" aria-controls="recent-tab-pane" aria-selected="false">
                    <i data-lucide="history" class="me-1"></i>Recent Scoring
                </button>
            </li>
        </ul>
        <div class="tab-content" id="dashTabsContent">
            <div class="tab-pane fade show active" id="upcoming-tab-pane" role="tabpanel" aria-labelledby="upcoming-tab" tabindex="0">
                <div class="border-0 shadow-none card border-0 shadow-sm">
                    <div class="border-0 shadow-none card-body p-3">
                        <?php if (empty($upcoming_events)): ?>
                            <div class="text-center text-muted py-3">
                                <i data-lucide="calendar-x" class="fa-2x mb-2 opacity-50"></i>
                                <p class="mb-0 small">No upcoming events scheduled</p>
                            </div>
                        <?php else: ?>
                            <div class="row g-2">
                                <?php foreach ($upcoming_events as $event): ?>
                                    <div class="col-md-6 col-xl-4">
                                        <div class="border-start border-primary border-3 bg-light rounded p-2 h-100">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div>
                                                    <h6 class="fw-bold mb-1 small"><?= htmlspecialchars($event['name']) ?></h6>
                                                    <small class="text-muted d-block">
                                                        <i data-lucide="calendar" class="me-1"></i><?= date('M d, Y', strtotime($event['date'])) ?>
                                                        <i data-lucide="map-pin" class="ms-2 me-1"></i><?= htmlspecialchars($event['location']) ?>
                                                    </small>
                                                </div>
                                                <span class="badge text-bg-primary small"><?= $event['participant_count'] ?> participants</span>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="tab-pane fade" id="recent-tab-pane" role="tabpanel" aria-labelledby="recent-tab" tabindex="0">
                <div class="border-0 shadow-none card border-0 shadow-sm">
                    <div class="border-0 shadow-none card-body p-3">
                        <?php if (empty($recent_scores)): ?>
                            <div class="text-center text-muted py-3">
                                <i data-lucide="star" class="fa-2x mb-2 opacity-50"></i>
                                <p class="mb-0 small">No recent scoring activity</p>
                            </div>
                        <?php else: ?>
                            <div class="list-group list-group-flush">
                                <?php foreach ($recent_scores as $score): ?>
                                    <div class="list-group-item px-0 py-2">
                                        <div class="d-flex justify-content-between align-items-start">
                                            <div>
                                                <div class="fw-semibold small">
                                                    <i data-lucide="user" class="me-1 text-secondary"></i>
                                                    <?= htmlspecialchars($score['first_name'] . ' ' . $score['last_name']) ?>
                                                </div>
                                                <small class="text-muted">
                                                    <?= htmlspecialchars($score['event_name']) ?> • Judge: <?= htmlspecialchars($score['judge_name']) ?>
                                                </small>
                                            </div>
                                            <span class="badge text-bg-success small">Score: <?= (float)$score['score_value'] ?></span>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </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>