<?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'; ?>
    <script src="https://unpkg.com/lucide@latest"></script>
    <!-- Help Button and Modal -->
    <div class="position-fixed end-0 top-0 p-3  help_f_button" style="z-index: 1055;">
        <button type="button" class="btn btn-info btn-lg rounded-circle shadow" title="Help / Guide" data-bs-toggle="modal" data-bs-target="#helpModal" style="width:56px; height:56px;">
            <i data-lucide="help-circle" style="width:24px;height:24px;"></i>
        </button>
    </div>
    <!-- Help Modal -->
    <div class="modal fade" id="helpModal" tabindex="-1" aria-labelledby="helpModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="helpModalLabel"><i data-lucide="calendar" class="me-2" style="width:16px;height:16px;"></i>Event Management Help</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body p-0" style="height:80vh;">
                    <iframe src="../help/events_help.html" style="width:100%;height:100%;border:0;" title="Event Management Help"></iframe>
                </div>
            </div>
        </div>
    </div>
     <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 container-StyleScore p-4">
        <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        <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 data-lucide="calendar" class="text-success me-2" style="width:20px;height:20px;"></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 data-lucide="plus" class="me-1" style="width:14px;height:14px;"></i>Create New Event
                        </a>
                    </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 data-lucide="filter" class="text-success me-2" style="width:16px;height:16px;"></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 data-lucide="search" class="text-muted" style="width:14px;height:14px;"></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 data-lucide="filter" class="me-1" style="width:14px;height:14px;"></i>Apply Filters
                            </button>
                            <a href="events.php" class="btn btn-outline-secondary btn-sm">
                                <i data-lucide="x" class="me-1" style="width:14px;height:14px;"></i>Clear
                            </a>
                        </div>
                    </form>
                </div>

                <!-- Events Grid -->
                <?php if (empty($events)): ?>
                    <div class="text-center py-5">
                        <i data-lucide="calendar-x" class="text-muted mb-3" style="width:64px;height:64px;"></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 data-lucide="plus" class="me-2" style="width:16px;height:16px;"></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' => 'trophy',
                                'BMX' => 'bike',
                                'Snowboarding' => 'snowflake',
                                'Alpine Skiing' => 'mountain',
                                'Figure Skating' => 'trophy',
                                'Ice Hockey' => 'trophy',
                                'Basketball' => 'trophy',
                                'Soccer' => 'trophy',
                                'Tennis' => 'trophy',
                                'Swimming' => 'waves',
                                'default' => '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="border-1 shadow-none card event-card h-100">
                                    <!-- Event Header -->
                                    <div class="border-0 shadow-none 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 data-lucide="<?= $icon ?>" style="width:18px;height:18px;"></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="border-0 shadow-none card-body py-2">
                                        <!-- Event Details: single line with separators -->
                                        <div class="mb-2 details-line text-muted small">
                                            <span><i data-lucide="calendar" class="text-primary me-1" style="width:14px;height:14px;"></i><?= date('M d, Y', strtotime($event['date'])) ?></span>
                                            <span class="dot-sep"></span>
                                            <span><i data-lucide="map-pin" class="text-danger me-1" style="width:14px;height:14px;"></i><?= htmlspecialchars($event['location']) ?></span>
                                            <?php if (!is_null($event['entry_fee']) && $event['entry_fee'] !== ''): ?>
                                                <span class="dot-sep"></span>
                                                <span><i data-lucide="dollar-sign" class="text-success me-1" style="width:14px;height:14px;"></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 data-lucide="puzzle" class="text-info me-1" style="width:14px;height:14px;"></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="h5 text-primary mb-0"><?= $event['participant_count'] ?></div>
                                                    <small class="text-muted">Participants</small>
                                                </div>
                                                <div class="col-4">
                                                    <div class="h5 text-info mb-0"><?= $event['heats_total'] ?></div>
                                                    <small class="text-muted">Heats</small>
                                                </div>
                                                <div class="col-4">
                                                    <div class="h5 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 data-lucide="edit" class="me-1" style="width:14px;height:14px;"></i>Edit
                                            </a>
                                            <a href="event_dashboard.php?event_id=<?= $event['id'] ?>" class="btn btn-outline-info btn-sm">
                                                <i data-lucide="gauge" class="me-1" style="width:14px;height:14px;"></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 data-lucide="users" class="me-1" style="width:14px;height:14px;"></i>Participants
                                                </a>
                                                <a href="../live_scoreboard_3.php?event_id=<?= $event['id'] ?>" class="btn btn-outline-warning btn-sm">
                                                    <i data-lucide="line-chart" class="me-1" style="width:14px;height:14px;"></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 data-lucide="more-horizontal" style="width:16px;height:16px;"></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 data-lucide="globe" class="me-2" style="width:14px;height:14px;"></i>Public Dashboard
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../live_scoreboard_tabs.php?event_id=<?= $event['id'] ?>" target="_blank">
                                                        <i data-lucide="monitor" class="me-2" style="width:14px;height:14px;"></i>Live Board (Tabs)
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="event_start_list.php?event_id=<?= $event['id'] ?>">
                                                        <i data-lucide="list" class="me-2" style="width:14px;height:14px;"></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 data-lucide="file-down" class="me-2" style="width:14px;height:14px;"></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 data-lucide="code" class="me-2" style="width:14px;height:14px;"></i>Export Start List (JSON)
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="copyEventLink(<?= $event['id'] ?>, 'public'); return false;">
                                                        <i data-lucide="link" class="me-2" style="width:14px;height:14px;"></i>Copy Public Link
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="#" onclick="copyEventLink(<?= $event['id'] ?>, 'live'); return false;">
                                                        <i data-lucide="link" class="me-2" style="width:14px;height:14px;"></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 data-lucide="tags" class="me-2" style="width:14px;height:14px;"></i>Categories
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="judge_assign.php?event_id=<?= $event['id'] ?>">
                                                        <i data-lucide="gavel" class="me-2" style="width:14px;height:14px;"></i>Judges
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../judge/event_reports.php?event_id=<?= $event['id'] ?>">
                                                        <i data-lucide="file-text" class="me-2" style="width:14px;height:14px;"></i>Reports
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="../judge/score.php?event_id=<?= $event['id'] ?>">
                                                        <i data-lucide="star" class="me-2" style="width:14px;height:14px;"></i>Score Event
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="results_panel.php?event_id=<?= $event['id'] ?>">
                                                        <i data-lucide="trophy" class="me-2" style="width:14px;height:14px;"></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 data-lucide="trash-2" class="me-2" style="width:14px;height:14px;"></i>Delete
                                                        </a></li>
                                                    <?php endif; ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>


    <script>
          document.addEventListener('DOMContentLoaded', () => { if (window.lucide) lucide.createIcons(); });
        // 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>

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