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

$message = '';
$debug_info = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $debug_info = '<div class="alert alert-info">Form submitted with data: ' . print_r($_POST, true) . '</div>';
    
    try {
        // Validate required fields
        if (empty($_POST['name']) || empty($_POST['date']) || empty($_POST['location']) || empty($_POST['sport_discipline'])) {
            throw new Exception('Required fields are missing');
        }
        
        $name = trim($_POST['name']);
        $date = $_POST['date'];
        $location = trim($_POST['location']);
        $sport_discipline = $_POST['sport_discipline'];
        $description = trim($_POST['description'] ?? '');
        $registration_deadline = !empty($_POST['registration_deadline']) ? $_POST['registration_deadline'] : null;

        // Set default values for detailed fields that will be configured later
        $max_participants = null;
        $entry_fee = 0;
        $contact_email = null;
        $contact_phone = null;
        $scoring_mode = 'best'; // Default scoring mode
        $runs_per_heat = 2; // Default runs per heat
        $heats_total = 1; // Default total heats
        $status = 'draft'; // Start as draft

        $stmt = $pdo->prepare("INSERT INTO events (name, date, location, sport_discipline, description, max_participants, entry_fee, contact_email, contact_phone, scoring_mode, runs_per_heat, heats_total, registration_deadline, status)
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        if ($stmt->execute([$name, $date, $location, $sport_discipline, $description, $max_participants, $entry_fee, $contact_email, $contact_phone, $scoring_mode, $runs_per_heat, $heats_total, $registration_deadline, $status])) {
            $event_id = $pdo->lastInsertId();
            // Redirect to edit page for detailed configuration
            header('Location: event_edit.php?id=' . $event_id . '&created=1');
            exit;
        } else {
            $errorInfo = $stmt->errorInfo();
            $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle"></i> Failed to create event. Database error: ' . htmlspecialchars($errorInfo[2]) . '
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>';
        }
    } catch (Exception $e) {
        $message = '<div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-triangle"></i> Error: ' . htmlspecialchars($e->getMessage()) . '
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>';
    }
}

// Load sports from figure_sports table
$sports_stmt = $pdo->prepare("SELECT sport_name FROM figure_sports WHERE is_active = 1 ORDER BY sport_name");
$sports_stmt->execute();
$available_sports = $sports_stmt->fetchAll(PDO::FETCH_COLUMN);

// Load scoring formats grouped by sport to show format icons under each sport
$formats_stmt = $pdo->prepare("SELECT format_id, name, sport FROM scoring_formats ORDER BY sport, name");
$formats_stmt->execute();
$scoring_formats = $formats_stmt->fetchAll(PDO::FETCH_ASSOC);
$formats_by_sport = [];
foreach ($scoring_formats as $fmt) {
    $sport_key = strtolower(trim($fmt['sport'] ?? ''));
    if ($sport_key === '') continue;
    if (!isset($formats_by_sport[$sport_key])) $formats_by_sport[$sport_key] = [];
    $formats_by_sport[$sport_key][] = $fmt;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create New Event - 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>
        .form-section {
            background: #ffffff;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            border-left: 4px solid #198754;
        }
        
        .required::after {
            content: ' *';
            color: #dc3545;
        }

        /* Sport picker modal */
        .sport-tile {
            cursor: pointer;
            border: 1px solid #e5e7eb;
            border-radius: .5rem;
            background: transparent;
            transition: border-color .15s ease, background-color .15s ease;
            padding: 16px;
            display: flex;
            flex-direction: column;
            align-items: stretch;
            gap: 10px;
        }
        .sport-tile:hover { border-color: #19875466; background-color: rgba(25,135,84,0.03); }
        .sport-icon-badge {
            width: 56px; height: 56px; border-radius: 50%; background: #fff; display: inline-flex; align-items:center; justify-content:center;
            box-shadow: 0 2px 6px rgba(0,0,0,.15);
        }
        .sport-icon-badge img { width: 36px; height: 36px; object-fit: contain; }
        .sport-icon-badge i { font-size: 24px; color: #198754; }
        .sport-name { font-weight: 700; }
        .sport-grid { overflow: auto; }
        .sport-filter { border-radius: .5rem; }
    .format-icons { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 12px; }
    .format-item { text-align: center; }
    .format-item img { width: 100px; height: 100px; min-width: 100px; min-height: 100px; object-fit: contain; background: transparent; }
    
    </style>
</head>
<body class="body-bg-aurora-bright">
    <?php include '../menu.php'; ?>
    <!-- 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 class="fas fa-question"></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 class="fas fa-calendar-plus me-2"></i>Create Event 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/event_create_help.html" style="width:100%;height:100%;border:0;" title="Create Event Help"></iframe>
                </div>
            </div>
        </div>
    </div>
    <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-4">
                    <div>
                        <h1 class="h2 mb-1">
                            <i class="fas fa-calendar-plus text-success me-2"></i>Create New Event
                        </h1>
                        <p class="text-muted mb-0">Start by providing basic event information. You'll be able to configure detailed settings after creation.</p>
                    </div>
                    <div>
                        <a href="events.php" class="btn btn-outline-primary">
                            <i class="fas fa-list me-1"></i>All Events
                        </a>
                    </div>
                </div>

                <?php if (!empty($message)): ?>
                    <?php echo $message; ?>
                <?php endif; ?>
                
                <?php if (!empty($debug_info)): ?>
                    <?php echo $debug_info; ?>
                <?php endif; ?>

                <!-- Create Form -->
                <form method="POST" class="needs-validation" novalidate>
                    <div class="row g-4">
                        <!-- Basic Information -->
                        <div class="col-lg-8">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-info-circle text-success me-2"></i>Basic Information
                                </h5>
                                
                                <div class="mb-3">
                                    <label for="name" class="form-label fw-bold required">Event Name</label>
                                    <input type="text" class="form-control" id="name" name="name" 
                                           placeholder="e.g., Summer Championship 2025" required>
                                    <div class="invalid-feedback">Please provide a valid event name.</div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="sport_discipline" class="form-label fw-bold required d-flex align-items-center justify-content-between">
                                            <span>Sport Discipline</span>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal" data-bs-target="#sportPickerModal">
                                                <i class="fas fa-th-large me-1"></i>Browse tiles
                                            </button>
                                        </label>
                                        <select class="form-select" id="sport_discipline" name="sport_discipline" required>
                                            <option value="">Select Sport</option>
                                            
                                            <!-- Dynamic Sports from Database -->
                                            <optgroup label="Available Sports">
                                                <?php foreach ($available_sports as $sport): ?>
                                                    <option value="<?= htmlspecialchars($sport) ?>">
                                                        <?= htmlspecialchars(ucwords(str_replace('_', ' ', $sport))) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            
                                            <!-- Legacy/Additional Sports -->
                                            <optgroup label="Additional Sports">
                                                <?php 
                                                // Additional sports that might not be in figure_sports table yet
                                                $additional_sports = [
                                                    'Alpine Skiing', 'Cross-Country Skiing', 'Freestyle Skiing', 'Ski Jumping', 
                                                    'Biathlon', 'Bobsled', 'Luge', 'Skeleton', 'Figure Skating', 'Speed Skating', 
                                                    'Ice Hockey', 'Curling', 'Ski Mountaineering', 'Snowmobiling', 'Ice Climbing',
                                                    'Scooter', 'Inline Skating', 'Other'
                                                ];
                                                
                                                foreach ($additional_sports as $sport): 
                                                    // Only show if not already in database sports
                                                    if (!in_array(strtolower(str_replace(' ', '_', $sport)), array_map('strtolower', $available_sports))):
                                                ?>
                                                    <option value="<?= htmlspecialchars($sport) ?>">
                                                        <?= htmlspecialchars($sport) ?>
                                                    </option>
                                                <?php 
                                                    endif;
                                                endforeach; 
                                                ?>
                                            </optgroup>
                                        </select>
                                        <div class="invalid-feedback">Please select a sport discipline.</div>
                                        <div class="form-text">
                                            Sports are loaded from the figures database. 
                                            <a href="figures_management.php" target="_blank">Manage sports</a>
                                        </div>
                                    </div>

                                    <div class="col-md-6 mb-3">
                                        <label for="date" class="form-label fw-bold required">Event Date</label>
                                        <input type="date" class="form-control" id="date" name="date" required>
                                        <div class="invalid-feedback">Please provide a valid date.</div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-8 mb-3">
                                        <label for="location" class="form-label fw-bold required">Location</label>
                                        <input type="text" class="form-control" id="location" name="location" 
                                               placeholder="e.g., Central Skate Park, New York" required>
                                        <div class="invalid-feedback">Please provide a valid location.</div>
                                    </div>

                                    <div class="col-md-4 mb-3">
                                        <label for="registration_deadline" class="form-label fw-bold">Registration Deadline</label>
                                        <input type="date" class="form-control" id="registration_deadline" name="registration_deadline">
                                        <div class="form-text">Optional - leave empty if no deadline</div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="description" class="form-label fw-bold">Description</label>
                                    <textarea class="form-control" id="description" name="description" rows="3" 
                                              placeholder="Brief description of the event, rules, or special notes..."></textarea>
                                    <div class="form-text">You can add more detailed information after creating the event</div>
                                </div>
                            </div>
                        </div>

                        <!-- Quick Setup Guide -->
                        <div class="col-lg-4">
                            <div class="form-section p-4">
                                <h5 class="mb-3">
                                    <i class="fas fa-rocket text-success me-2"></i>What's Next?
                                </h5>
                                
                                <div class="mb-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="badge bg-success rounded-pill me-2">1</span>
                                        <span class="fw-bold">Create Event</span>
                                    </div>
                                    <p class="text-muted small mb-0 ms-4">Fill in the basic information and create your event</p>
                                </div>

                                <div class="mb-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="badge bg-outline-secondary rounded-pill me-2">2</span>
                                        <span class="text-muted">Configure Details</span>
                                    </div>
                                    <p class="text-muted small mb-0 ms-4">Set up scoring, participants, and event settings</p>
                                </div>

                                <div class="mb-3">
                                    <div class="d-flex align-items-center mb-2">
                                        <span class="badge bg-outline-secondary rounded-pill me-2">3</span>
                                        <span class="text-muted">Go Live</span>
                                    </div>
                                    <p class="text-muted small mb-0 ms-4">Open registration and start your event</p>
                                </div>

                                <hr class="my-3">

                                <div class="alert alert-light border-0">
                                    <i class="fas fa-lightbulb text-warning me-2"></i>
                                    <strong>Pro Tip:</strong> You can start with minimal information and configure everything else in the detailed edit page.
                                </div>
                            </div>
                        </div>

                        <!-- Submit Actions -->
                        <div class="col-12">
                            <div class="form-section p-4">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div class="text-muted">
                                        <small><span class="text-danger">*</span> Required fields | Additional settings can be configured after creation</small>
                                    </div>
                                    <div>
                                        <a href="events.php" class="btn btn-outline-secondary me-2">
                                            <i class="fas fa-times me-1"></i>Cancel
                                        </a>
                                        <button type="submit" class="btn btn-success">
                                            <i class="fas fa-arrow-right me-1"></i>Create & Configure
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

<script>
// Bootstrap form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        var forms = document.getElementsByClassName('needs-validation');
        var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();
</script>

<!-- Sport Picker Modal -->
<div class="modal fade" id="sportPickerModal" tabindex="-1" aria-labelledby="sportPickerLabel" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen p-3">
        <div class="modal-content bg-transparent">
           
            <div class="modal-body border-0">
              
                <div class="sport-grid">
                    <style>
                                                .format-item img {
                            width: 100px;
                            height: 100px;
                            min-width: 100px;
                            min-height: 100px;
                            object-fit: contain;
                            background: transparent;
                            background: radial-gradient(closest-side, #212529b0 0%, #212529b0 100%, #f69d3c00 90%);
                        }
                                            .modal { backdrop-filter: none; }
                                                .flex-icony {
                            display: flex;
                            max-width: 90vw;
                            flex-wrap: wrap;
                            align-content: center;
                            align-items: center;
                            justify-content: center;
                            gap: 1em;
                        }
                                                
                                                .format-icons {
                            display: flex
                        ;
                            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
                            gap: 12px;
                            align-content: center;
                            justify-content: center;

                        }
                        .sport-tile {    backdrop-filter: blur(5px) brightness(0.8); border: 0px solid rgba(255, 255, 255, 0.2); border-radius: .5rem;  }
                        .sport-tile:hover {    backdrop-filter: blur(10px) brightness(0.5); border: 0px solid rgba(255, 255, 255, 0.2); border-radius: .5rem;  }
                    </style>
                        <div class="flex-icony">
                                <?php
                                // Use a simple icon map as fallback when no SVG exists
                                $sport_icons = [
                                        'skateboard' => 'fas fa-skating',
                                        'bmx' => 'fas fa-bicycle',
                                        'snowboard' => 'fas fa-snowboarding',
                                        'alpine_skiing' => 'fas fa-skiing',
                                        'freeski' => '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',
                                        'inline' => 'fas fa-person-running',
                                        'surf' => 'fas fa-water',
                                        'kitesurf' => 'fas fa-wind',
                                        'parkour' => 'fas fa-person-running',
                                        'breaking' => 'fas fa-music',
                                        'wakeboard' => 'fas fa-water',
                                        'default' => 'fas fa-trophy'
                                ];

                                foreach ($available_sports as $sport):
                                        $slug = strtolower(trim($sport));
                                        $label = ucwords(str_replace('_', ' ', $sport));
                                        // Attempt to find a matching SVG by sport slug
                                        $svgRel = "../assets/img/SVG/{$slug}.svg";
                                        $svgAbs = __DIR__ . "/../assets/img/SVG/{$slug}.svg";
                                        $svgAbsUpper = __DIR__ . "/../assets/img/SVG/{$slug}.SVG";
                                        if (!file_exists($svgAbs) && file_exists($svgAbsUpper)) {
                                                $svgRel = "../assets/img/SVG/{$slug}.SVG";
                                                $svgAbs = $svgAbsUpper;
                                        }
                                        $hasSvg = file_exists($svgAbs);
                                        $iconClass = $sport_icons[$slug] ?? $sport_icons['default'];
                                        $sport_formats = $formats_by_sport[$slug] ?? [];
                                ?>
                                
                                        <div class="sport-tile" data-sport="<?= htmlspecialchars($sport) ?>">
                                                <div class="text-light text-center fa-2x"><?= htmlspecialchars($label) ?></div>
                                                <?php if (!empty($sport_formats)): ?>
                                                    <div class="format-icons" aria-label="Available formats for <?= htmlspecialchars($label) ?>">
                                                        <?php foreach ($sport_formats as $fmt): 
                                                            $fid = $fmt['format_id'];
                                                            $fname = $fmt['name'] ?? $fid;
                                                            $fidSlug = strtolower(trim($fid));
                                                            $fRel = "../assets/img/SVG/{$fidSlug}.svg";
                                                            $fAbs = __DIR__ . "/../assets/img/SVG/{$fidSlug}.svg";
                                                            $fAbsUpper = __DIR__ . "/../assets/img/SVG/{$fidSlug}.SVG";
                                                            if (!file_exists($fAbs) && file_exists($fAbsUpper)) { $fRel = "../assets/img/SVG/{$fidSlug}.SVG"; $fAbs = $fAbsUpper; }
                                                            if (file_exists($fAbs)):
                                                        ?>
                                                            <div class="format-item">
                                                                <img src="<?= $fRel ?>" alt="<?= htmlspecialchars($fid) ?>">
                                                                <div class="format-label text-info fa-1x"><?= htmlspecialchars($fname) ?></div>
                                                            </div>
                                                        <?php endif; endforeach; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <div class="text-muted small">No formats found</div>
                                                <?php endif; ?>
                                        </div>
                               
                                <?php endforeach; ?>
                        </div>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
    </div>

<script>
// Sport picker interactions
document.addEventListener('DOMContentLoaded', function() {
    const tiles = document.querySelectorAll('#sportPickerModal .sport-tile');
    const select = document.getElementById('sport_discipline');
    const filterInput = document.getElementById('sportFilterInput');
    const modalEl = document.getElementById('sportPickerModal');

    tiles.forEach(tile => {
        tile.addEventListener('click', () => {
            const sport = tile.getAttribute('data-sport');
            if (!sport || !select) return;
            // If the value exists in the select, set it; otherwise append an option
            let exists = Array.from(select.options).some(o => o.value.toLowerCase() === sport.toLowerCase());
            if (!exists) {
                const opt = document.createElement('option');
                opt.value = sport;
                opt.textContent = sport.replaceAll('_',' ').replace(/\b\w/g, m => m.toUpperCase());
                select.appendChild(opt);
            }
            select.value = sport;
            select.dispatchEvent(new Event('change'));

            // Visual feedback
            tiles.forEach(t => t.classList.remove('border-success'));
            tile.classList.add('border-success');

            // Close modal shortly after selection and ensure proper cleanup
            if (modalEl) {
                const modal = bootstrap.Modal.getInstance(modalEl) || new bootstrap.Modal(modalEl);
                const onHidden = () => {
                    try { modal.dispose(); } catch (e) {}
                    // Cleanup any stray backdrops just in case
                    document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
                    document.body.classList.remove('modal-open');
                    document.body.style.removeProperty('padding-right');
                    // Return focus to the select for accessibility
                    if (select && typeof select.focus === 'function') select.focus();
                    modalEl.removeEventListener('hidden.bs.modal', onHidden);
                };
                modalEl.addEventListener('hidden.bs.modal', onHidden, { once: true });
                setTimeout(() => modal.hide(), 200);
            }
        });
    });

    // Simple filter
    if (filterInput) {
        filterInput.addEventListener('input', function() {
            const q = this.value.toLowerCase().trim();
            tiles.forEach(tile => {
                const name = tile.querySelector('.sport-name')?.textContent.toLowerCase() || '';
                tile.parentElement.style.display = name.includes(q) ? '' : 'none';
            });
        });
    }

    // Auto-open the sport picker after 1000ms if no sport is selected yet
    setTimeout(() => {
        if (!modalEl) return;
        const hasSelection = select && select.value && select.value.trim() !== '';
        if (!hasSelection && !modalEl.classList.contains('show')) {
            const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
            modal.show();
        }
    }, 1000);
});
</script>

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