<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fixture Details - Fixture Manager</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
        }
        .header {
            background-color: #007bff;
            color: white;
            padding: 1rem 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
        }
        .nav {
            display: flex;
            gap: 1rem;
        }
        .nav a {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background-color 0.3s;
        }
        .nav a:hover {
            background-color: rgba(255,255,255,0.1);
        }
        .container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 2rem;
        }
        .content {
            background: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .btn {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            display: inline-block;
            margin: 0.5rem 0;
            border: none;
            cursor: pointer;
            font-size: 0.9rem;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background-color: #e0a800;
        }
        .btn-success {
            background-color: #28a745;
        }
        .btn-success:hover {
            background-color: #218838;
        }
        .btn-sm {
            padding: 4px 8px;
            font-size: 0.8rem;
            margin: 0 2px;
        }
        .upload-form {
            display: inline-block;
            margin: 0 2px;
        }
        .upload-form input[type="file"] {
            display: none;
        }
        .upload-label {
            padding: 4px 8px;
            font-size: 0.8rem;
            background-color: #28a745;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
            margin: 0;
        }
        .upload-label:hover {
            background-color: #218838;
        }
        .zip-actions {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            align-items: center;
        }
        .progress-container {
            width: 200px;
            margin: 2px;
            display: none;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #f0f0f0;
            border-radius: 10px;
            overflow: hidden;
            border: 1px solid #ddd;
        }
        .progress-fill {
            height: 100%;
            background-color: #28a745;
            width: 0%;
            transition: width 0.3s ease;
            border-radius: 10px;
        }
        .progress-text {
            font-size: 0.7rem;
            text-align: center;
            line-height: 20px;
            color: white;
            font-weight: bold;
            text-shadow: 1px 1px 1px rgba(0,0,0,0.5);
        }
        .upload-status {
            font-size: 0.7rem;
            margin: 2px;
            padding: 2px 4px;
            border-radius: 3px;
            display: none;
        }
        .upload-status.uploading {
            background-color: #ffc107;
            color: #212529;
        }
        .upload-status.success {
            background-color: #28a745;
            color: white;
        }
        .upload-status.error {
            background-color: #dc3545;
            color: white;
        }
        .alert {
            padding: 12px;
            margin-bottom: 1rem;
            border-radius: 4px;
        }
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .fixture-info {
            background-color: #f8f9fa;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 2rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }
        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            background-color: white;
            border-radius: 6px;
            border-left: 4px solid #007bff;
        }
        .info-label {
            font-size: 1rem;
            color: #666;
            font-weight: 500;
            margin: 0;
            min-width: 120px;
        }
        .info-value {
            font-size: 1.1rem;
            font-weight: bold;
            color: #333;
            text-align: right;
            word-break: break-all;
            max-width: 70%;
        }
        .actions-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            flex-wrap: wrap;
            gap: 1rem;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 1rem;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .status-active {
            color: #28a745;
            font-weight: bold;
        }
        .status-inactive {
            color: #dc3545;
            font-weight: bold;
        }
        .match-row:hover {
            background-color: #f8f9fa;
        }
        .section {
            margin-bottom: 2rem;
        }
        .section h2 {
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="logo">🥊 Fixture Manager</div>
        <div class="nav">
            <a href="{{ url_for('main.dashboard') }}">Dashboard</a>
            <a href="{{ url_for('main.fixtures') }}">Fixtures</a>
            <a href="{{ url_for('main.uploads') }}">Uploads</a>
            <a href="{{ url_for('main.statistics') }}">Statistics</a>
            {% if current_user.is_admin %}
                <a href="{{ url_for('main.admin_panel') }}">Admin</a>
            {% endif %}
            <a href="{{ url_for('auth.logout') }}">Logout</a>
        </div>
    </div>

    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ 'error' if category == 'error' else 'success' }}">{{ message }}</div>
                {% endfor %}
            {% endif %}
        {% endwith %}

        <div class="content">
            <div class="actions-bar">
                <div>
                    <h1>Fixture Details</h1>
                    <a href="{{ url_for('main.fixtures') }}" class="btn">← Back to Fixtures</a>
                </div>
                <div>
                    <form method="POST" action="{{ url_for('main.delete_fixture', fixture_id=fixture_info.fixture_id) }}" 
                          style="display: inline;" 
                          onsubmit="return confirm('Are you sure you want to delete this entire fixture and all {{ fixture_info.total_matches }} matches? This action cannot be undone.');">
                        <button type="submit" class="btn btn-danger">Delete Entire Fixture</button>
                    </form>
                </div>
            </div>

            <!-- Fixture Information -->
            <div class="fixture-info">
                <div class="info-item">
                    <div class="info-label">Fixture ID</div>
                    <div class="info-value">{{ fixture_info.fixture_id[:8] }}...</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Filename</div>
                    <div class="info-value">{{ fixture_info.filename }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Upload Date</div>
                    <div class="info-value">{{ fixture_info.upload_date.strftime('%Y-%m-%d %H:%M') if fixture_info.upload_date else 'N/A' }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Total Matches</div>
                    <div class="info-value">{{ fixture_info.total_matches }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Active Matches</div>
                    <div class="info-value">{{ fixture_info.active_matches }}</div>
                </div>
                <div class="info-item">
                    <div class="info-label">Status</div>
                    <div class="info-value">
                        {% if fixture_info.active_matches == fixture_info.total_matches %}
                            <span class="status-active">All Active</span>
                        {% elif fixture_info.active_matches > 0 %}
                            <span style="color: #ffc107; font-weight: bold;">Partial</span>
                        {% else %}
                            <span class="status-inactive">Inactive</span>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- Matches Section -->
            <div class="section">
                <h2>Matches in this Fixture</h2>
                
                {% if matches %}
                <table>
                    <thead>
                        <tr>
                            <th>Match #</th>
                            <th>Fighter 1</th>
                            <th>Fighter 2</th>
                            <th>Venue</th>
                            <th>Status</th>
                            <th>ZIP Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for match in matches %}
                        <tr class="match-row">
                            <td>{{ match.match_number }}</td>
                            <td>{{ match.fighter1_township }}</td>
                            <td>{{ match.fighter2_township }}</td>
                            <td>{{ match.venue_kampala_township }}</td>
                            <td>
                                {% if match.active_status %}
                                    <span class="status-active">Active</span>
                                {% else %}
                                    <span class="status-inactive">Inactive</span>
                                {% endif %}
                            </td>
                            <td>
                                {% if match.zip_upload_status == 'completed' %}
                                    <span class="status-active">Completed</span>
                                {% elif match.zip_upload_status == 'pending' %}
                                    <span style="color: #ffc107;">Pending</span>
                                {% elif match.zip_upload_status == 'failed' %}
                                    <span class="status-inactive">Failed</span>
                                {% else %}
                                    <span style="color: #6c757d;">{{ match.zip_upload_status.title() }}</span>
                                {% endif %}
                            </td>
                            <td>
                                <div class="zip-actions" id="zip_actions_{{ match.id }}">
                                    <a href="{{ url_for('main.match_detail', id=match.id) }}?fixture_id={{ fixture_info.fixture_id }}" class="btn btn-sm">View Details</a>
                                    
                                    {% if match.zip_upload_status == 'completed' %}
                                        <!-- ZIP file exists - show replace and delete options -->
                                        <form class="upload-form" id="upload_form_{{ match.id }}" method="POST" action="{{ url_for('upload.upload_zip') }}" enctype="multipart/form-data">
                                            <input type="hidden" name="match_id" value="{{ match.id }}">
                                            <input type="file" id="zip_file_{{ match.id }}" name="zip_file" accept=".zip">
                                            <label for="zip_file_{{ match.id }}" class="upload-label btn-warning" title="Replace existing ZIP file">Replace ZIP</label>
                                        </form>
                                        <form class="upload-form" method="POST" action="{{ url_for('upload.delete_zip', match_id=match.id) }}" style="display: inline;">
                                            <button type="submit" class="btn btn-danger btn-sm" title="Delete ZIP file" onclick="return confirm('Are you sure you want to delete the ZIP file for Match #{{ match.match_number }}?')">Delete ZIP</button>
                                        </form>
                                    {% else %}
                                        <!-- No ZIP file or failed - show upload option -->
                                        <form class="upload-form" id="upload_form_{{ match.id }}" method="POST" action="{{ url_for('upload.upload_zip') }}" enctype="multipart/form-data">
                                            <input type="hidden" name="match_id" value="{{ match.id }}">
                                            <input type="file" id="zip_file_{{ match.id }}" name="zip_file" accept=".zip">
                                            <label for="zip_file_{{ match.id }}" class="upload-label" title="Upload ZIP file for this match">Upload ZIP</label>
                                        </form>
                                    {% endif %}
                                    
                                    <!-- Progress bar (hidden by default) -->
                                    <div class="progress-container" id="progress_{{ match.id }}">
                                        <div class="progress-bar">
                                            <div class="progress-fill" id="progress_fill_{{ match.id }}">
                                                <div class="progress-text" id="progress_text_{{ match.id }}">0%</div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Upload status (hidden by default) -->
                                    <div class="upload-status" id="status_{{ match.id }}"></div>
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
                {% else %}
                <p>No matches found in this fixture.</p>
                {% endif %}
            </div>

            <!-- Fixture ZIP Upload Section -->
            {% set matches_without_zip = matches|selectattr('zip_upload_status', 'ne', 'completed')|list %}
            {% if matches_without_zip %}
            <div class="section">
                <h2>Upload ZIP for All Matches</h2>
                <div style="background-color: #f8f9fa; padding: 1.5rem; border-radius: 8px; margin-bottom: 1rem;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
                        <div>
                            <h4 style="margin: 0; color: #333;">Bulk ZIP Upload</h4>
                            <p style="margin: 0.5rem 0 0 0; color: #666;">
                                Upload a single ZIP file that will be associated with all {{ matches_without_zip|length }} matches that don't have ZIP files yet.
                            </p>
                        </div>
                        <div style="text-align: right;">
                            <div style="font-size: 2rem; font-weight: bold; color: #007bff;">{{ matches_without_zip|length }}</div>
                            <div style="font-size: 0.9rem; color: #666;">matches pending</div>
                        </div>
                    </div>
                    
                    <!-- Upload Form -->
                    <form id="fixture_upload_form" method="POST" action="{{ url_for('upload.upload_fixture_zip', fixture_id=fixture_info.fixture_id) }}" enctype="multipart/form-data" style="margin-bottom: 1rem;">
                        <div style="display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
                            <div style="flex: 1; min-width: 300px;">
                                <input type="file" id="fixture_zip_file" name="zip_file" accept=".zip,.7z,.rar" style="width: 100%; padding: 0.5rem; border: 2px dashed #007bff; border-radius: 4px; background-color: white;">
                            </div>
                            <button type="submit" class="btn btn-success" style="padding: 0.75rem 1.5rem; font-weight: bold;">
                                <i class="fas fa-upload"></i> Upload ZIP for All Matches
                            </button>
                        </div>
                    </form>
                    
                    <!-- Progress Bar (hidden by default) -->
                    <div id="fixture_progress_container" style="display: none; margin-top: 1rem;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                            <span style="font-weight: bold;">Uploading...</span>
                            <span id="fixture_progress_text">0%</span>
                        </div>
                        <div class="progress-bar" style="width: 100%; height: 25px; background-color: #f0f0f0; border-radius: 12px; overflow: hidden; border: 1px solid #ddd;">
                            <div id="fixture_progress_fill" class="progress-fill" style="height: 100%; background-color: #28a745; width: 0%; transition: width 0.3s ease; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                                <span id="fixture_progress_inner_text" style="color: white; font-weight: bold; font-size: 0.9rem; text-shadow: 1px 1px 1px rgba(0,0,0,0.5);">0%</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Upload Status (hidden by default) -->
                    <div id="fixture_upload_status" class="upload-status" style="display: none; margin-top: 1rem; padding: 0.75rem; border-radius: 4px; font-weight: bold;"></div>
                    
                    <!-- Info Box -->
                    <div style="margin-top: 1rem; padding: 1rem; background-color: #e3f2fd; border-left: 4px solid #2196f3; border-radius: 4px;">
                        <div style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem;">
                            <i class="fas fa-info-circle" style="color: #2196f3;"></i>
                            <strong style="color: #1976d2;">How it works:</strong>
                        </div>
                        <ul style="margin: 0; padding-left: 1.5rem; color: #1976d2;">
                            <li>The same ZIP file will be associated with all matches that don't have one</li>
                            <li>Matches that already have ZIP files will not be affected</li>
                            <li>All affected matches will become active once the upload completes</li>
                            <li>Supports large files up to 2GB with progress tracking</li>
                        </ul>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- Associated Uploads Section -->
            {% if uploads %}
            <div class="section">
                <h2>Associated File Uploads</h2>
                <table>
                    <thead>
                        <tr>
                            <th>Filename</th>
                            <th>File Type</th>
                            <th>Size</th>
                            <th>Status</th>
                            <th>Upload Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for upload in uploads %}
                        <tr>
                            <td>{{ upload.original_filename }}</td>
                            <td>{{ upload.file_type.upper() }}</td>
                            <td>{{ "%.1f"|format(upload.file_size / 1024 / 1024) }} MB</td>
                            <td>
                                {% if upload.upload_status == 'completed' %}
                                    <span class="status-active">Completed</span>
                                {% elif upload.upload_status == 'failed' %}
                                    <span class="status-inactive">Failed</span>
                                {% else %}
                                    <span style="color: #ffc107;">{{ upload.upload_status.title() }}</span>
                                {% endif %}
                            </td>
                            <td>{{ upload.created_at.strftime('%Y-%m-%d %H:%M') if upload.created_at else 'N/A' }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% endif %}

            <!-- Quick Actions -->
            <div class="section">
                <h2>Quick Actions</h2>
                <div style="display: flex; gap: 1rem; flex-wrap: wrap;">
                    <a href="{{ url_for('upload.upload_fixture') }}" class="btn">Upload New Fixture</a>
                    <a href="{{ url_for('main.statistics') }}" class="btn">View Statistics</a>
                    <a href="{{ url_for('main.fixtures') }}" class="btn" style="background-color: #6c757d;">Back to All Fixtures</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        const CHUNK_SIZE = 1024 * 1024; // 1MB chunks
        let activeUploads = new Map();

        function uploadFileInChunks(file, matchId) {
            const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
            const uploadId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);

            let currentChunk = 0;

            // Show progress bar and hide upload form
            const uploadForm = document.getElementById(`upload_form_${matchId}`);
            const progressContainer = document.getElementById(`progress_${matchId}`);
            const statusDiv = document.getElementById(`status_${matchId}`);

            uploadForm.style.display = 'none';
            progressContainer.style.display = 'block';
            statusDiv.style.display = 'block';
            statusDiv.className = 'upload-status uploading';
            statusDiv.textContent = 'Uploading... 0%';

            function uploadChunk() {
                if (currentChunk >= totalChunks) {
                    // All chunks uploaded, finalize
                    finalizeUpload(uploadId, file.name, matchId);
                    return;
                }

                const start = currentChunk * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', currentChunk);
                formData.append('totalChunks', totalChunks);
                formData.append('uploadId', uploadId);
                formData.append('fileName', file.name);
                formData.append('matchId', matchId);

                fetch('/upload/chunk', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentChunk++;
                        const progress = (currentChunk / totalChunks) * 100;
                        updateProgress(matchId, Math.round(progress));
                        statusDiv.textContent = `Uploading... ${Math.round(progress)}%`;
                        uploadChunk();
                    } else {
                        throw new Error(data.error || 'Upload failed');
                    }
                })
                .catch(error => {
                    statusDiv.className = 'upload-status error';
                    statusDiv.textContent = 'Upload failed: ' + error.message;
                });
            }

            uploadChunk();
        }

        function finalizeUpload(uploadId, fileName, matchId) {
            const statusDiv = document.getElementById(`status_${matchId}`);

            fetch('/upload/finalize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    uploadId: uploadId,
                    fileName: fileName,
                    matchId: matchId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateProgress(matchId, 100);
                    statusDiv.className = 'upload-status success';
                    statusDiv.textContent = 'Upload successful!';
                    // Reload page after a short delay to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    statusDiv.className = 'upload-status error';
                    statusDiv.textContent = 'Finalization failed: ' + (data.error || 'Unknown error');
                }
            })
            .catch(error => {
                statusDiv.className = 'upload-status error';
                statusDiv.textContent = 'Finalization failed: ' + error.message;
            });
        }

        function startUpload(matchId) {
            const fileInput = document.getElementById(`zip_file_${matchId}`);
            const file = fileInput.files[0];

            if (!file) {
                return;
            }

            uploadFileInChunks(file, matchId);
        }

        function updateProgress(matchId, percent) {
            const progressFill = document.getElementById(`progress_fill_${matchId}`);
            const progressText = document.getElementById(`progress_text_${matchId}`);
            
            progressFill.style.width = percent + '%';
            progressText.textContent = percent + '%';
            
            // Change color based on progress
            if (percent < 50) {
                progressFill.style.backgroundColor = '#ffc107'; // Yellow
            } else if (percent < 100) {
                progressFill.style.backgroundColor = '#17a2b8'; // Blue
            } else {
                progressFill.style.backgroundColor = '#28a745'; // Green
            }
        }

        function handleUploadError(matchId, errorMessage) {
            const uploadForm = document.getElementById(`upload_form_${matchId}`);
            const progressContainer = document.getElementById(`progress_${matchId}`);
            const statusDiv = document.getElementById(`status_${matchId}`);
            
            // Show error status
            statusDiv.className = 'upload-status error';
            statusDiv.textContent = errorMessage;
            
            // Hide progress bar and show upload form again after delay
            setTimeout(() => {
                progressContainer.style.display = 'none';
                statusDiv.style.display = 'none';
                uploadForm.style.display = 'inline-block';
                
                // Reset file input
                const fileInput = document.getElementById(`zip_file_${matchId}`);
                fileInput.value = '';
            }, 3000);
        }

        // Cancel upload function (if needed)
        function cancelUpload(matchId) {
            const xhr = activeUploads.get(matchId);
            if (xhr) {
                xhr.abort();
            }
        }

        // Fixture-level upload functionality
        let fixtureUploadActive = false;

        function uploadFixtureFileInChunks(file) {
            const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
            const uploadId = Date.now() + '_' + Math.random().toString(36).substr(2, 9);

            let currentChunk = 0;

            // Show progress bar and hide upload form
            const uploadForm = document.getElementById('fixture_upload_form');
            const progressContainer = document.getElementById('fixture_progress_container');
            const statusDiv = document.getElementById('fixture_upload_status');

            uploadForm.style.display = 'none';
            progressContainer.style.display = 'block';
            statusDiv.style.display = 'block';
            statusDiv.className = 'upload-status uploading';
            statusDiv.textContent = 'Uploading to all matches... 0%';

            function uploadChunk() {
                if (currentChunk >= totalChunks) {
                    // All chunks uploaded, finalize
                    finalizeFixtureUpload(uploadId, file.name);
                    return;
                }

                const start = currentChunk * CHUNK_SIZE;
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);

                const formData = new FormData();
                formData.append('chunk', chunk);
                formData.append('chunkIndex', currentChunk);
                formData.append('totalChunks', totalChunks);
                formData.append('uploadId', uploadId);
                formData.append('fileName', file.name);

                fetch('/upload/chunk', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        currentChunk++;
                        const progress = (currentChunk / totalChunks) * 100;
                        updateFixtureProgress(Math.round(progress));
                        statusDiv.textContent = `Uploading to all matches... ${Math.round(progress)}%`;
                        uploadChunk();
                    } else {
                        throw new Error(data.error || 'Upload failed');
                    }
                })
                .catch(error => {
                    statusDiv.className = 'upload-status error';
                    statusDiv.textContent = 'Upload failed: ' + error.message;
                    fixtureUploadActive = false;
                });
            }

            uploadChunk();
        }

        function finalizeFixtureUpload(uploadId, fileName) {
            const statusDiv = document.getElementById('fixture_upload_status');

            fetch('/upload/finalize', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    uploadId: uploadId,
                    fileName: fileName
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateFixtureProgress(100);
                    statusDiv.className = 'upload-status success';
                    statusDiv.textContent = 'Upload successful! All matches are now active.';
                    // Reload page after a short delay to show updated status
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    statusDiv.className = 'upload-status error';
                    statusDiv.textContent = 'Finalization failed: ' + (data.error || 'Unknown error');
                }
                fixtureUploadActive = false;
            })
            .catch(error => {
                statusDiv.className = 'upload-status error';
                statusDiv.textContent = 'Finalization failed: ' + error.message;
                fixtureUploadActive = false;
            });
        }

        function startFixtureUpload() {
            const fileInput = document.getElementById('fixture_zip_file');
            const file = fileInput.files[0];

            if (!file) {
                return;
            }

            if (fixtureUploadActive) {
                return; // Prevent multiple uploads
            }

            fixtureUploadActive = true;
            uploadFixtureFileInChunks(file);
        }

        function updateFixtureProgress(percent) {
            const progressFill = document.getElementById('fixture_progress_fill');
            const progressText = document.getElementById('fixture_progress_text');
            const progressInnerText = document.getElementById('fixture_progress_inner_text');
            
            progressFill.style.width = percent + '%';
            progressText.textContent = percent + '%';
            progressInnerText.textContent = percent + '%';
            
            // Change color based on progress
            if (percent < 50) {
                progressFill.style.backgroundColor = '#ffc107'; // Yellow
            } else if (percent < 100) {
                progressFill.style.backgroundColor = '#17a2b8'; // Blue
            } else {
                progressFill.style.backgroundColor = '#28a745'; // Green
            }
        }

        function handleFixtureUploadError(errorMessage) {
            const uploadForm = document.getElementById('fixture_upload_form');
            const progressContainer = document.getElementById('fixture_progress_container');
            const statusDiv = document.getElementById('fixture_upload_status');
            
            // Show error status
            statusDiv.className = 'upload-status error';
            statusDiv.textContent = errorMessage;
            
            // Hide progress bar and show upload form again after delay
            setTimeout(() => {
                progressContainer.style.display = 'none';
                statusDiv.style.display = 'none';
                uploadForm.style.display = 'block';
                
                // Reset file input
                const fileInput = document.getElementById('fixture_zip_file');
                fileInput.value = '';
                fixtureUploadActive = false;
            }, 3000);
        }

        // Prevent form submission only for file upload forms (we handle them with AJAX)
        document.addEventListener('DOMContentLoaded', function() {
            // Only prevent submission for forms that contain file inputs (upload forms)
            const fileUploadForms = document.querySelectorAll('.upload-form');
            fileUploadForms.forEach(form => {
                const hasFileInput = form.querySelector('input[type="file"]');
                if (hasFileInput) {
                    form.addEventListener('submit', function(e) {
                        e.preventDefault();
                        return false;
                    });
                }
            });

            // Handle individual match file inputs
            const matchFileInputs = document.querySelectorAll('input[type="file"][id^="zip_file_"]');
            matchFileInputs.forEach(input => {
                input.addEventListener('change', function() {
                    if (this.files.length > 0) {
                        // Extract match ID from input ID (zip_file_123 -> 123)
                        const matchId = this.id.replace('zip_file_', '');
                        startUpload(parseInt(matchId));
                    }
                });
            });

            // Handle fixture upload form submission
            const fixtureUploadForm = document.getElementById('fixture_upload_form');
            if (fixtureUploadForm) {
                fixtureUploadForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    startFixtureUpload();
                    return false;
                });
            }

            // Handle file input change for fixture upload
            const fixtureFileInput = document.getElementById('fixture_zip_file');
            if (fixtureFileInput) {
                fixtureFileInput.addEventListener('change', function() {
                    if (this.files.length > 0) {
                        // Auto-start upload when file is selected (optional)
                        // startFixtureUpload();
                    }
                });
            }
        });
    </script>
</body>
</html>