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

// Get filter parameters
$filter_status = $_GET['status'] ?? '';
$filter_sport = $_GET['sport'] ?? '';
$search = $_GET['search'] ?? '';

// Build query with filters
$where_conditions = [];
$params = [];

if ($filter_status) {
    $where_conditions[] = "status = ?";
    $params[] = $filter_status;
}

if ($filter_sport) {
    $where_conditions[] = "sport_discipline = ?";
    $params[] = $filter_sport;
}

if ($search) {
    $where_conditions[] = "(name LIKE ? OR location LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$where_clause = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Fetch events with participant counts and sport details
$events_stmt = $pdo->prepare("
    SELECT e.*, 
           sf.name AS scoring_format_name,
           fsd.icon_path, fsd.short_name as sport_short_name,
           COUNT(ep.id) as participant_count,
           CASE 
               WHEN e.date < CURDATE() THEN 'past'
               WHEN e.date = CURDATE() THEN 'today'
               ELSE 'upcoming'
           END as time_status
    FROM events e
    LEFT JOIN event_participants ep ON e.id = ep.event_id
    LEFT JOIN scoring_formats sf ON e.scoring_format = sf.format_id
    LEFT JOIN figure_sports fs ON LOWER(e.sport_discipline) = LOWER(fs.sport_name)
    LEFT JOIN figure_sport_details fsd ON fs.id = fsd.sport_id
    $where_clause
    GROUP BY e.id
    ORDER BY e.date DESC
");
$events_stmt->execute($params);
$events = $events_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get filter options
$sports = $pdo->query("SELECT DISTINCT sport_discipline FROM events WHERE sport_discipline IS NOT NULL ORDER BY sport_discipline")->fetchAll(PDO::FETCH_COLUMN);
$statuses = ['draft', 'open', 'closed', 'completed'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event 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;
        }
        .bg-gradient-brand{
            background: linear-gradient(180deg, #1a1a2e 0%, #16213e 50%, #0f3460);
        }
        .format-badge img {
    object-fit: contain;
    filter: none;
    position: absolute;
}
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        
        .event-card {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            /* Ensure dropdowns aren't clipped by card */
            overflow: visible;
        }
        
        .event-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
    /* Ensure dropdowns render above and aren't clipped */
    .event-card .card-body { overflow: visible; }
    .event-card .dropdown-menu { z-index: 1060; }
    /* Fallback: ensure shown dropdowns are visible */
    .dropdown-menu.show { display: block; }

    /* Standout icon styles */
    .format-badge {
           width: 60px;
    height: 60px;
    background: #001023;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 2px 6px rgba(0,0,0,0.2);
    }
    
    .format-badge i { font-size: 18px; color: #198754; }
    .details-line i { opacity: .8; }
    .dot-sep::before { content: '\2022'; margin: 0 .5rem; opacity: .5; }
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    
    <div class="container-fluid py-4">
        <div class="row justify-content-center">
            <div class="col-xl-10">
                <!-- Header -->
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h2 class="mb-1">
                            <i class="fas fa-calendar-alt text-success me-2"></i>Event Management
                        </h2>
                        <p class="text-muted mb-0 small">Manage all your sporting events in one central hub</p>
                    </div>
                    <div class="d-flex gap-2">
                        <a href="event_create.php" class="btn btn-success btn-sm">
                            <i class="fas fa-plus me-1"></i>Create New Event
                        </a>
                    </div>
                </div>

                <!-- Summary Stats -->
                <div class="row g-2 mb-3">
                    <?php
                    $total_events = count($events);
                    $upcoming_events = count(array_filter($events, fn($e) => $e['time_status'] == 'upcoming'));
                    $active_events = count(array_filter($events, fn($e) => $e['status'] == 'open'));
                    $total_participants = array_sum(array_column($events, 'participant_count'));
                    ?>
                    <div class="col-lg-3 col-md-6">
                        <div class="card text-center h-100">
                            <div class="card-body py-2">
                                <div class="h4 text-primary mb-1"><?= $total_events ?></div>
                                <div class="text-muted small">Total Events</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card text-center h-100">
                            <div class="card-body py-2">
                                <div class="h4 text-info mb-1"><?= $upcoming_events ?></div>
                                <div class="text-muted small">Upcoming Events</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card text-center h-100">
                            <div class="card-body py-2">
                                <div class="h4 text-success mb-1"><?= $active_events ?></div>
                                <div class="text-muted small">Open for Registration</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="card text-center h-100">
                            <div class="card-body py-2">
                                <div class="h4 text-warning mb-1"><?= $total_participants ?></div>
                                <div class="text-muted small">Total Participants</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters -->
                <div class="form-section p-3 mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0">
                            <i class="fas fa-filter text-success me-2"></i>Filter Events
                        </h6>
                        <small class="text-muted">Showing <?= count($events) ?> events</small>
                    </div>
                    
                    <form method="get" class="row g-2">
                        <div class="col-lg-4 col-md-6">
                            <label class="form-label fw-medium small">Search Events</label>
                            <div class="input-group input-group-sm">
                                <span class="input-group-text">
                                    <i class="fas fa-search text-muted"></i>
                                </span>
                                <input type="text" class="form-control" name="search" 
                                       value="<?= htmlspecialchars($search) ?>" 
                                       placeholder="Search by name or location...">
                            </div>
                        </div>
                        
                        <div class="col-lg-2 col-md-3">
                            <label class="form-label fw-medium small">Status</label>
                            <select name="status" class="form-select form-select-sm">
                                <option value="">All Statuses</option>
                                <?php foreach ($statuses as $status): ?>
                                    <option value="<?= $status ?>" <?= $filter_status == $status ? 'selected' : '' ?>>
                                        <?= ucfirst($status) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-lg-3 col-md-3">
                            <label class="form-label fw-medium small">Sport Discipline</label>
                            <select name="sport" class="form-select form-select-sm">
                                <option value="">All Sports</option>
                                <?php foreach ($sports as $sport): ?>
                                    <option value="<?= $sport ?>" <?= $filter_sport == $sport ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($sport) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-lg-3 col-md-12 d-flex align-items-end gap-2">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="fas fa-filter me-1"></i>Apply Filters
                            </button>
                            <a href="events.php" class="btn btn-outline-secondary btn-sm">
                                <i class="fas fa-times me-1"></i>Clear
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Events Grid -->
                <?php if (empty($events)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-calendar-times fa-4x text-muted mb-3"></i>
                        <h4 class="text-muted">No Events Found</h4>
                        <p class="mb-4">No events match your current filters. Try adjusting your search criteria or create a new event to get started.</p>
                        <a href="event_create.php" class="btn btn-success">
                            <i class="fas fa-plus me-2"></i>Create Your First Event
                        </a>
                    </div>
                <?php else: ?>
                    <div class="row g-3">
                        <?php foreach ($events as $event): ?>
                            <?php
                            // Determine status badge color
                            $status_colors = [
                                'draft' => 'secondary',
                                'open' => 'success',
                                'live' => 'success',
                                'closed' => 'warning',
                                'completed' => 'info'
                            ];
                            
                            // Determine time badge
                            $time_colors = [
                                'past' => 'dark',
                                'today' => 'danger',
                                'upcoming' => 'primary'
                            ];
                            
                            $time_labels = [
                                'past' => 'Past',
                                'today' => 'Today',
                                'upcoming' => 'Upcoming'
                            ];
                            
                            // Sport icon mapping
                            $sport_icons = [
                                'Skateboarding' => 'fas fa-skating',
                                'BMX' => 'fas fa-bicycle',
                                'Snowboarding' => 'fas fa-snowboarding',
                                'Alpine Skiing' => 'fas fa-skiing',
                                'Figure Skating' => 'fas fa-skating',
                                'Ice Hockey' => 'fas fa-hockey-puck',
                                'Basketball' => 'fas fa-basketball-ball',
                                'Soccer' => 'fas fa-futbol',
                                'Tennis' => 'fas fa-table-tennis',
                                'Swimming' => 'fas fa-swimmer',
                                'default' => 'fas fa-trophy'
                            ];
                            
                            $icon = $sport_icons[$event['sport_discipline']] ?? $sport_icons['default'];

                            // Prefer scoring-format specific SVG if available
                            $format_key = $event['scoring_format'] ?? '';
                            $format_key_sanitized = strtolower(preg_replace('/[^a-z0-9_\-]/i', '_', $format_key));
                            // Resolve possible svg extension case
                            $format_img_rel = "../assets/img/SVG/{$format_key_sanitized}.svg";
                            $format_img_abs = __DIR__ . '/../assets/img/SVG/' . $format_key_sanitized . '.svg';
                            $format_img_abs_upper = __DIR__ . '/../assets/img/SVG/' . $format_key_sanitized . '.SVG';
                            if ($format_key && !file_exists($format_img_abs) && file_exists($format_img_abs_upper)) {
                                $format_img_rel = "../assets/img/SVG/{$format_key_sanitized}.SVG";
                                $format_img_abs = $format_img_abs_upper;
                            }
                            $has_format_img = $format_key && file_exists($format_img_abs);
                            ?>
                            
                            <div class="col-xl-4 col-lg-6">
                                <div class="card event-card h-100">
                                    <!-- Event Header -->
                                    <div class="card-header bg-gradient-brand text-white position-relative py-2">
                                        <!-- Time Badge -->
                                        <span class="badge bg-<?= $time_colors[$event['time_status']] ?> position-absolute end-0 bottom-0 m-2">
                                            <?= $time_labels[$event['time_status']] ?>
                                        </span>
                                        
                                        <!-- Status Badge -->
                                        <span class="badge bg-<?= $status_colors[$event['status']] ?> position-absolute top-0 end-0 m-2">
                                            <?= ucfirst($event['status']) ?>
                                        </span>
                                        
                                        <div class="d-flex align-items-center pt-2">
                                            <div class="format-badge me-3">
                                                <?php if ($has_format_img): ?>
                                                    <img src="<?= $format_img_rel ?>" alt="<?= htmlspecialchars($format_key) ?>">
                                                <?php else: ?>
                                                    <i class="<?= $icon ?>"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div>
                                                <h6 class="card-title mb-1"><?= htmlspecialchars($event['name']) ?></h6>
                                                <small class="opacity-75 d-flex align-items-center">
                                                    <?php if (!empty($event['icon_path']) && file_exists('../' . $event['icon_path'])): ?>
                                                        <img src="../<?= htmlspecialchars($event['icon_path']) ?>" 
                                                             alt="<?= htmlspecialchars($event['sport_discipline']) ?>" 
                                                             style="width: 16px; height: 16px; object-fit: contain; filter: brightness(0) invert(1);" 
                                                             class="me-1">
                                                    <?php endif; ?>
                                                    <?= htmlspecialchars($event['sport_short_name'] ?: $event['sport_discipline'] ?: 'Sport Event') ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Event Body -->
                                    <div class="card-body py-2">
                                        <!-- Event Details: single line with separators -->
                                        <div class="mb-2 details-line text-muted small">
                                            <span><i class="fas fa-calendar text-primary me-1"></i><?= date('M d, Y', strtotime($event['date'])) ?></span>
                                            <span class="dot-sep"></span>
                                            <span><i class="fas fa-map-marker-alt text-danger me-1"></i><?= htmlspecialchars($event['location']) ?></span>
                                            <?php if (!is_null($event['entry_fee']) && $event['entry_fee'] !== ''): ?>
                                                <span class="dot-sep"></span>
                                                <span><i class="fas fa-dollar-sign text-success me-1"></i>$<?= number_format((float)$event['entry_fee'], 2) ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($event['scoring_format'])): ?>
                                                <span class="row">
                                                <span title="Scoring Format"><i class="fas fa-puzzle-piece text-info me-1"></i><?= htmlspecialchars($event['scoring_format_name'] ?: str_replace('_',' ', $event['scoring_format'])) ?></span></span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <!-- Stats -->
                                        <div class="shadow rounded p-2 mb-2">
                                            <div class="row text-center">
                                                <div class="col-4">
                                                    <div class="h6 text-primary mb-0"><?= $event['participant_count'] ?></div>
                                                    <small class="text-muted">Participants</small>
                                                </div>
                                                <div class="col-4">
                                                    <div class="h6 text-info mb-0"><?= $event['heats_total'] ?></div>
                                                    <small class="text-muted">Heats</small>
                                                </div>
                                                <div class="col-4">
                                                    <div class="h6 text-warning mb-0"><?= $event['runs_per_heat'] ?></div>
                                                    <small class="text-muted">Runs</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Description -->
                                        <?php if ($event['description']): ?>
                                            <p class="text-muted small mb-2">
                                                <?= htmlspecialchars(substr($event['description'], 0, 100)) ?>
                                                <?= strlen($event['description']) > 100 ? '...' : '' ?>
                                            </p>
                                        <?php endif; ?>
                                        
                                        <!-- Action Buttons -->
                                        <div class="d-flex flex-wrap gap-1">
                                            <a href="event_edit.php?id=<?= $event['id'] ?>" class="btn btn-outline-primary btn-sm">
                                                <i class="fas fa-edit me-1"></i>Edit
                                            </a>
                                            <a href="event_dashboard.php?event_id=<?= $event['id'] ?>" class="btn btn-outline-info btn-sm">
                                                <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                                            </a>
                                            
                                            <?php if ($event['participant_count'] > 0): ?>
                                                <a href="heats_configure.php?event_id=<?= $event['id'] ?>" class="btn btn-outline-success btn-sm">
                                                    <i class="fas fa-users me-1"></i>Participants
                                                </a>
                                                <a href="../live_scoreboard_3.php?event_id=<?= $event['id'] ?>" class="btn btn-outline-warning btn-sm">
                                                    <i class="fas fa-chart-line me-1"></i>Scoreboard
                                                </a>
                                            <?php endif; ?>

                                            <div class="dropdown d-inline" data-bs-display="static">
                                                <button class="btn btn-outline-secondary btn-sm dropdown-toggle" type="button" 
                                                        data-bs-toggle="dropdown" data-bs-boundary="viewport" aria-expanded="false" title="More">
                                                    <i class="fas fa-ellipsis-h"></i>
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end">
                                                    <li><h6 class="dropdown-header">Quick Access</h6></li>
                                                    <li><a class="dropdown-item" href="../public_event_dashboard.php?event_id=<?= $event['id'] ?>" target="_blank">
                                                        <i class="fas fa-globe me-2"></i>Public Dashboard
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../live_scoreboard_tabs.php?event_id=<?= $event['id'] ?>" target="_blank">
                                                        <i class="fas fa-tv me-2"></i>Live Board (Tabs)
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="event_start_list.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-list me-2"></i>Start Lists
                                                    </a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><h6 class="dropdown-header">Export / Share</h6></li>
                                                    <li><a class="dropdown-item" href="../api/start_list_api.php?event_id=<?= $event['id'] ?>&format=csv">
                                                        <i class="fas fa-file-csv me-2"></i>Export Start List (CSV)
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../api/start_list_api.php?event_id=<?= $event['id'] ?>&format=json" target="_blank">
                                                        <i class="fas fa-code me-2"></i>Export Start List (JSON)
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="copyEventLink(<?= $event['id'] ?>, 'public'); return false;">
                                                        <i class="fas fa-link me-2"></i>Copy Public Link
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="copyEventLink(<?= $event['id'] ?>, 'live'); return false;">
                                                        <i class="fas fa-link me-2"></i>Copy Live Board Link
                                                    </a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><h6 class="dropdown-header">Manage</h6></li>
                                                    <li><a class="dropdown-item" href="event_categories.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-tags me-2"></i>Categories
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="judge_assign.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-gavel me-2"></i>Judges
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../judge/event_reports.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-file-alt me-2"></i>Reports
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../judge/score.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-star me-2"></i>Score Event
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="results_panel.php?event_id=<?= $event['id'] ?>">
                                                        <i class="fas fa-trophy me-2"></i>Results
                                                    </a></li>
                                                    <?php if ($event['participant_count'] == 0): ?>
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item text-danger" href="event_delete.php?id=<?= $event['id'] ?>" onclick="return confirm('Are you sure you want to delete this event?')">
                                                            <i class="fas fa-trash me-2"></i>Delete
                                                        </a></li>
                                                    <?php endif; ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>


   <script>
        // Simple auto-submit for filters
        document.querySelectorAll('select[name="status"], select[name="sport"]').forEach(select => {
            select.addEventListener('change', function() {
                this.form.submit();
            });
        });
        
        // Ensure dropdowns work - fallback initialization
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize all dropdowns manually if needed
            const dropdownTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="dropdown"]'));
            dropdownTriggerList.map(function (dropdownTrigger) {
                return new bootstrap.Dropdown(dropdownTrigger);
            });
            
            // Fallback: manual toggling when Bootstrap JS isn't active
            document.addEventListener('click', function(e) {
                const toggle = e.target.closest('[data-bs-toggle="dropdown"]');
                if (!toggle) return;
                // If bootstrap is available, let it handle
                if (window.bootstrap && bootstrap.Dropdown) return;
                e.preventDefault();
                e.stopPropagation();
                const dropdown = toggle.closest('.dropdown');
                const menu = dropdown ? dropdown.querySelector('.dropdown-menu') : null;
                if (!menu) return;
                const isShown = menu.classList.contains('show');
                // Close any other open menus
                document.querySelectorAll('.dropdown-menu.show').forEach(m => m.classList.remove('show'));
                if (!isShown) {
                    menu.classList.add('show');
                    toggle.setAttribute('aria-expanded', 'true');
                } else {
                    menu.classList.remove('show');
                    toggle.setAttribute('aria-expanded', 'false');
                }
            });
            // Close on outside click (fallback mode)
            document.addEventListener('click', function(e) {
                if (e.target.closest('.dropdown')) return;
                document.querySelectorAll('.dropdown-menu.show').forEach(m => m.classList.remove('show'));
                document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(t => t.setAttribute('aria-expanded', 'false'));
            });
        });

        // Helper: copy event links to clipboard
        function copyEventLink(eventId, type) {
            try {
                const base = window.location.origin + '/v2/';
                const url = type === 'live'
                    ? `${base}live_scoreboard_tabs.php?event_id=${eventId}`
                    : `${base}public_event_dashboard.php?event_id=${eventId}`;
                navigator.clipboard.writeText(url).then(() => {
                    // Small toast-like feedback
                    const tip = document.createElement('div');
                    tip.className = 'position-fixed top-0 start-50 translate-middle-x alert alert-success py-1 px-3 shadow-sm';
                    tip.style.zIndex = 1080;
                    tip.textContent = 'Link copied to clipboard';
                    document.body.appendChild(tip);
                    setTimeout(() => tip.remove(), 1200);
                });
            } catch (e) {
                alert('Copy failed. You can manually copy the link from the address bar.');
            }
        }
    </script>
</body>
</html>