<!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" onchange="startUpload({{ match.id }})">
                                            <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" onchange="startUpload({{ match.id }})">
                                            <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>

            <!-- 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>
        let activeUploads = new Map();

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

            // 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...';

            // Create FormData
            const formData = new FormData();
            formData.append('zip_file', file);
            formData.append('match_id', matchId);

            // Create XMLHttpRequest for progress tracking
            const xhr = new XMLHttpRequest();
            activeUploads.set(matchId, xhr);

            // Progress event handler
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    updateProgress(matchId, percentComplete);
                }
            });

            // Load event handler (upload complete)
            xhr.addEventListener('load', function() {
                if (xhr.status === 200) {
                    // 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 {
                    // Error
                    handleUploadError(matchId, 'Upload failed');
                }
                activeUploads.delete(matchId);
            });

            // Error event handler
            xhr.addEventListener('error', function() {
                handleUploadError(matchId, 'Network error');
                activeUploads.delete(matchId);
            });

            // Abort event handler
            xhr.addEventListener('abort', function() {
                handleUploadError(matchId, 'Upload cancelled');
                activeUploads.delete(matchId);
            });

            // Start upload
            xhr.open('POST', '{{ url_for("upload.upload_zip") }}', true);
            xhr.send(formData);
        }

        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();
            }
        }

        // Prevent form submission on file change (we handle it with AJAX)
        document.addEventListener('DOMContentLoaded', function() {
            const uploadForms = document.querySelectorAll('.upload-form');
            uploadForms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    return false;
                });
            });
        });
    </script>
</body>
</html>