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

// Handle new series submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_series'])) {
    if (!empty($_POST['name']) && !empty($_POST['event_id'])) {
        $event_id = $_POST['event_id'];
        $name = $_POST['name'];
        $color = $_POST['color'];
        $start = (int)$_POST['start_number'];
        $end = (int)$_POST['end_number'];
        $missing = trim($_POST['missing_numbers']);
        $additional = trim($_POST['additional_numbers']);

        // Prepare full number list for new series
        $new_range = range($start, $end);
        $new_missing = array_filter(array_map('trim', explode(',', $missing)), 'is_numeric');
        $new_additional = array_filter(array_map('trim', explode(',', $additional)), 'is_numeric');
        $all_new = array_unique(array_merge($new_range, $new_additional));
        $all_new = array_diff($all_new, $new_missing);

        // Check for conflicts with existing series in this event
        $conflict_series = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ?");
        $conflict_series->execute([$event_id]);

        $has_conflict = false;
        foreach ($conflict_series as $existing) {
            $existing_range = range($existing['start_number'], $existing['end_number']);
            $existing_missing = array_filter(array_map('trim', explode(',', $existing['missing_numbers'])), 'is_numeric');
            $existing_additional = array_filter(array_map('trim', explode(',', $existing['additional_numbers'])), 'is_numeric');
            $existing_all = array_unique(array_merge($existing_range, $existing_additional));
            $existing_all = array_diff($existing_all, $existing_missing);

            $overlap = array_intersect($all_new, $existing_all);
            if (count($overlap) > 0) {
                $has_conflict = true;
                $conflict_details = [
                    'series_name' => $existing['name'],
                    'conflicts' => implode(', ', $overlap)
                ];
                break;
            }
        }

        if ($has_conflict && !isset($_POST['force_create'])) {
            ob_start();
            ?>
            <div class="container-fluid container-StyleScore p-4">
                <div class="alert alert-danger alert alert-dismissible fade show" role="alert">
                    <strong>⚠️ Conflict Detected:</strong> BIB numbers overlap with series <strong><?php echo htmlspecialchars($conflict_details['series_name']); ?></strong>.<br>
Conflicting numbers: <code><?php echo htmlspecialchars($conflict_details['conflicts']); ?></code>

                    <form method="post" class="d-inline">
                        <?php foreach ($_POST as $key => $value): ?>
                            <input type="hidden" name="<?php echo htmlspecialchars($key) ?>" value="<?php echo  htmlspecialchars($value) ?>">
                        <?php endforeach; ?>
                        <input type="hidden" name="force_create" value="1">
                        <button type="submit" class="btn btn-sm btn-danger ms-2">Ignore and Force Creation</button>
                    </form>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            </div>
            <?php
            echo ob_get_clean();
            return;
        }
        }

        $check = $pdo->prepare("SELECT COUNT(*) FROM bib_series WHERE event_id = ? AND name = ?");
        $check->execute([$event_id, $name]);
        if ($check->fetchColumn() == 0) {
            $stmt = $pdo->prepare("INSERT INTO bib_series (event_id, name, color, start_number, end_number, missing_numbers, additional_numbers) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$event_id, $name, $color, $start, $end, $missing, $additional]);
        }
    }


// Handle delete
if (isset($_GET['delete_series'])) {
    $stmt = $pdo->prepare("DELETE FROM bib_series WHERE id = ?");
    $stmt->execute([$_GET['delete_series']]);
    header("Location: bib_assign.php?event_id=" . (int)$_GET['event_id']);
    exit;
}

// Fetch events
$events = $pdo->query("SELECT id, name, date FROM events ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch BIB series
$bib_series = [];
if (!empty($_GET['event_id'])) {
    $stmt = $pdo->prepare("SELECT * FROM bib_series WHERE event_id = ? ORDER BY id DESC");
    $stmt->execute([$_GET['event_id']]);
    $bib_series = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BIB Series Assignment</title>
   <?php include_once '../includes/stylesheets.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script></head>
<body class="body-bg-aurora-bright">
<?php include '../menu.php'; ?>

<div class="container-fluid container-StyleScore p-4">
        <!-- Event Actions Menu -->
    <div class="row mb-4">
        <div class="col-12">
            <?php       
            $use_localStorage = true;
            $show_header = false;
            include 'event_actions_menu.php'; 
            ?>
        </div>
    </div>
    <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                        <h1 class="h3 mb-1">
                                <i class="fas fa-tags text-primary me-2"></i>BIB Series Manager
                        </h1>
                        <p class="text-muted mb-0">Create and manage BIB number series for events</p>
                </div>
                <div class="text-end">
                        <small class="text-muted d-block mb-2">
                                <i class="fas fa-info-circle me-1"></i>Organize participant numbering
                        </small>
                        <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-toggle="modal" data-bs-target="#helpModal">
                                <i class="fas fa-circle-question me-1"></i>Help
                        </button>
                </div>
        </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-circle-question me-2 text-info"></i>BIB Series Assignment — 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/bib_assign_help.html" style="border:0;width:100%;height:100%;" title="BIB Series Assignment Help"></iframe>
                    </div>
                </div>
            </div>
        </div>



    <!-- Event Selection -->
    <div class="border-0 shadow-none card bg-primary text-white mb-4">
        <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center border-0">
            <h5 class="mb-0">
                <i class="fas fa-calendar-alt me-2"></i>Event Selection
            </h5>
        </div>
        <div class="border-0 shadow-none card-body">
            <form method="get">
                <div class="row g-3 align-items-end">
                    <div class="col-md-8">
                        <label class="form-label text-white">Select Event:</label>
                        <select name="event_id" class="form-select" onchange="this.form.submit()">
                            <option value="">-- Choose Event --</option>
                            <?php foreach ($events as $e): ?>
                                <option value="<?= $e['id'] ?>" <?= ($_GET['event_id'] ?? '') == $e['id'] ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($e['name']) ?> (<?= htmlspecialchars($e['date']) ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-light">
                            <i class="fas fa-search me-2"></i>Load Event
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <?php if (!empty($_GET['event_id'])): ?>
    
    <!-- Create New BIB Series -->
    <div class="row g-4 mb-4">
        <div class="col-lg-8">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-plus-circle text-success me-2"></i>Create New BIB Series
                    </h6>
                    <small class="text-muted">Add a new number series</small>
                </div>
                <div class="border-0 shadow-none card-body">
                    <form method="post">
                        <input type="hidden" name="event_id" value="<?= $_GET['event_id'] ?>">
                        <input type="hidden" name="create_series" value="1">

                        <div class="row g-3">
                            <!-- Series Name -->
                            <div class="col-12">
                                <label class="form-label fw-medium">
                                    <i class="fas fa-tag text-primary me-1"></i>Series Name
                                </label>
                                <input type="text" name="name" class="form-control" placeholder="e.g., Elite Athletes, Juniors, etc." required>
                            </div>

                            <!-- Number Range -->
                            <div class="col-md-6">
                                <label class="form-label fw-medium">
                                    <i class="fas fa-arrow-right text-info me-1"></i>Start Number
                                </label>
                                <input type="number" name="start_number" class="form-control" placeholder="1" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-medium">
                                    <i class="fas fa-arrow-left text-info me-1"></i>End Number
                                </label>
                                <input type="number" name="end_number" class="form-control" placeholder="100" required>
                            </div>

                            <!-- Optional Numbers -->
                            <div class="col-md-6">
                                <label class="form-label fw-medium">
                                    <i class="fas fa-minus-circle text-warning me-1"></i>Missing Numbers
                                    <small class="text-muted">(optional)</small>
                                </label>
                                <input type="text" name="missing_numbers" class="form-control" placeholder="e.g., 13, 33, 66">
                                <small class="form-text text-muted">Comma-separated numbers to exclude</small>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-medium">
                                    <i class="fas fa-plus-circle text-success me-1"></i>Additional Numbers
                                    <small class="text-muted">(optional)</small>
                                </label>
                                <input type="text" name="additional_numbers" class="form-control" placeholder="e.g., 150, 200, 250">
                                <small class="form-text text-muted">Comma-separated numbers to include</small>
                            </div>

                            <!-- Submit Button -->
                            <div class="col-12">
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary btn-lg">
                                        <i class="fas fa-plus-circle me-2"></i>Create BIB Series
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <!-- Color Selection Sidebar -->
        <div class="col-lg-4">
            <div class="border-0 shadow-none card">
                <div class="border-0 shadow-none card-header">
                    <h6 class="mb-0">
                        <i class="fas fa-palette text-warning me-2"></i>Series Color
                    </h6>
                </div>
                <div class="border-0 shadow-none card-body">
                    <!-- Predefined Colors -->
                    <div class="mb-3">
                        <label class="form-label small fw-medium">Quick Select:</label>
                        <div class="d-flex gap-2 flex-wrap">
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#000000" style="width: 45px; height: 45px; background-color: #000000; border-radius: 8px;" title="Black"></button>
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#007BFF" style="width: 45px; height: 45px; background-color: #007BFF; border-radius: 8px;" title="Blue"></button>
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#DC3545" style="width: 45px; height: 45px; background-color: #DC3545; border-radius: 8px;" title="Red"></button>
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#FD7E14" style="width: 45px; height: 45px; background-color: #FD7E14; border-radius: 8px;" title="Orange"></button>
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#28A745" style="width: 45px; height: 45px; background-color: #28A745; border-radius: 8px;" title="Green"></button>
                            <button type="button" class="btn p-0 color-pick border border-2" data-color="#6F42C1" style="width: 45px; height: 45px; background-color: #6F42C1; border-radius: 8px;" title="Purple"></button>
                        </div>
                    </div>
                    
                    <!-- Custom Color Input -->
                    <div class="mb-3">
                        <label class="form-label small fw-medium">Custom Color:</label>
                        <div class="input-group mb-2">
                            <span class="input-group-text px-3" id="colorPreview" style="background-color: #000000; min-width: 50px;">&nbsp;</span>
                            <input type="text" name="color" id="colorInput" class="form-control" placeholder="#000000" pattern="^#[0-9A-Fa-f]{6}$">
                        </div>
                        <input type="color" id="colorPicker" class="form-control form-control-color w-100" style="height: 45px;">
                        <small class="form-text text-muted">Click colors above, use picker, or enter hex code</small>
                    </div>
                    
                    <!-- Color Preview -->
                    <div class="text-center">
                        <div class="badge text-white px-3 py-2" id="colorBadgePreview" style="background-color: #000000; font-size: 0.9rem;">
                            Sample BIB Color
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Existing BIB Series -->
    <div class="border-0 shadow-none card">
        <div class="border-0 shadow-none card-header d-flex justify-content-between align-items-center">
            <h6 class="mb-0">
                <i class="fas fa-list text-info me-2"></i>Existing BIB Series
            </h6>
            <span class="badge bg-secondary"><?= count($bib_series) ?> series</span>
        </div>
        <div class="border-0 shadow-none card-body p-0">
            <?php if (empty($bib_series)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">No BIB Series Created</h5>
                    <p class="text-muted">Create your first BIB series using the form above</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">
                                    <i class="fas fa-tag me-1"></i>Series Name
                                </th>
                                <th scope="col" class="text-center">
                                    <i class="fas fa-arrows-alt-h me-1"></i>Range
                                </th>
                                <th scope="col" class="text-center">
                                    <i class="fas fa-minus-circle me-1"></i>Missing
                                </th>
                                <th scope="col" class="text-center">
                                    <i class="fas fa-plus-circle me-1"></i>Additional
                                </th>
                                <th scope="col" class="text-center">
                                    <i class="fas fa-palette me-1"></i>Color
                                </th>
                                <th scope="col" class="text-center">
                                    <i class="fas fa-cogs me-1"></i>Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($bib_series as $series): ?>
                                <?php
                                // Calculate total numbers
                                $range_numbers = range($series['start_number'], $series['end_number']);
                                $missing_numbers = array_filter(array_map('trim', explode(',', $series['missing_numbers'])), 'is_numeric');
                                $additional_numbers = array_filter(array_map('trim', explode(',', $series['additional_numbers'])), 'is_numeric');
                                $total_numbers = count($range_numbers) - count($missing_numbers) + count($additional_numbers);
                                ?>
                                <tr>
                                    <td>
                                        <div class="fw-medium"><?= htmlspecialchars($series['name']) ?></div>
                                        <small class="text-muted"><?= $total_numbers ?> total numbers</small>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge bg-primary"><?= $series['start_number'] ?> - <?= $series['end_number'] ?></span>
                                    </td>
                                    <td class="text-center">
                                        <?php if (!empty(trim($series['missing_numbers']))): ?>
                                            <span class="badge bg-warning text-dark"><?= htmlspecialchars($series['missing_numbers']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">None</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if (!empty(trim($series['additional_numbers']))): ?>
                                            <span class="badge bg-success"><?= htmlspecialchars($series['additional_numbers']) ?></span>
                                        <?php else: ?>
                                            <span class="text-muted">None</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <div class="d-flex align-items-center justify-content-center gap-2">
                                            <span class="badge text-white px-3 py-2" style="background-color: <?= $series['color'] ?>;">BIB</span>
                                            <code class="small"><?= $series['color'] ?></code>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group" role="group">
                                            <a href="bib_edit.php?id=<?= $series['id'] ?>&event_id=<?= $_GET['event_id'] ?>" 
                                               class="btn btn-sm btn-outline-warning" title="Edit Series">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="?delete_series=<?= $series['id'] ?>&event_id=<?= $_GET['event_id'] ?>" 
                                               class="btn btn-sm btn-outline-danger" 
                                               title="Delete Series"
                                               onclick="return confirm('Are you sure you want to delete this BIB series?\n\nSeries: <?= htmlspecialchars($series['name']) ?>\nRange: <?= $series['start_number'] ?> - <?= $series['end_number'] ?>\n\nThis action cannot be undone.')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>
	
	<script>
document.addEventListener('DOMContentLoaded', function() {
    const colorInput = document.getElementById('colorInput');
    const colorPreview = document.getElementById('colorPreview');
    const colorPicker = document.getElementById('colorPicker');
    const colorBadgePreview = document.getElementById('colorBadgePreview');
    const colorPicks = document.querySelectorAll('.color-pick');
    
    // Handle predefined color selection
    colorPicks.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const color = this.getAttribute('data-color');
            setColor(color);
            setActiveColorButton(this);
        });
    });
    
    // Handle color picker input
    colorPicker.addEventListener('input', function() {
        const color = this.value.toUpperCase();
        setColor(color);
        updateActiveButtonFromColor(color);
    });
    
    // Handle manual color input
    colorInput.addEventListener('input', function() {
        const color = this.value.toUpperCase();
        if (isValidHexColor(color)) {
            updateColorPreview(color);
            colorPicker.value = color;
            updateActiveButtonFromColor(color);
        }
    });
    
    // Set color in all inputs and previews
    function setColor(color) {
        colorInput.value = color;
        colorPicker.value = color;
        updateColorPreview(color);
    }
    
    // Update color preview elements
    function updateColorPreview(color) {
        if (isValidHexColor(color)) {
            // Update input group preview
            colorPreview.style.backgroundColor = color;
            
            // Update badge preview
            if (colorBadgePreview) {
                colorBadgePreview.style.backgroundColor = color;
                
                // Adjust text color for better visibility
                const rgb = hexToRgb(color);
                const brightness = (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
                colorBadgePreview.style.color = brightness > 128 ? '#000000' : '#ffffff';
            }
        }
    }
    
    // Set active state for color button
    function setActiveColorButton(button) {
        // Remove active state from all buttons
        colorPicks.forEach(btn => {
            btn.classList.remove('border-primary');
            btn.style.borderWidth = '2px';
        });
        
        // Add active state to clicked button
        button.classList.add('border-primary');
        button.style.borderWidth = '3px';
    }
    
    // Update active button based on color value
    function updateActiveButtonFromColor(color) {
        colorPicks.forEach(btn => {
            btn.classList.remove('border-primary');
            btn.style.borderWidth = '2px';
        });
        
        // Find matching predefined color
        colorPicks.forEach(button => {
            if (button.getAttribute('data-color').toLowerCase() === color.toLowerCase()) {
                setActiveColorButton(button);
            }
        });
    }
    
    // Validate hex color
    function isValidHexColor(color) {
        return /^#[0-9A-F]{6}$/i.test(color);
    }
    
    // Convert hex to RGB for brightness calculation
    function hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    
    // Initialize with black as default
    const defaultColor = '#000000';
    setColor(defaultColor);
    const blackButton = document.querySelector('[data-color="#000000"]');
    if (blackButton) {
        setActiveColorButton(blackButton);
    }
});
</script>


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