{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-plus-circle me-2"></i>Create New Bet
            <small class="text-muted">Select matches and outcomes</small>
        </h1>
    </div>
</div>

<!-- Back Button and Submit Button -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-gamepad me-2"></i>Available Matches for Betting
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-outline-secondary" onclick="window.location.href='/bets'">
                            <i class="fas fa-arrow-left me-2"></i>Back to Bets
                        </button>
                    </div>
                    <div class="col-md-6 mb-3 text-end">
                        <button class="btn btn-success" id="btn-submit-bet" disabled>
                            <i class="fas fa-check me-2"></i>Submit Bet
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Available Matches - Left Side -->
    <div class="col-lg-9 col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-list me-2"></i>Today's Matches Available for Betting
                    <span class="badge bg-success ms-2" id="available-matches-count">0</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="available-matches-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading available matches...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Current Bet Summary -->
    <div class="col-lg-3 col-md-4">
        <!-- Current Bet Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-receipt me-2"></i>Bet Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <div id="bet-summary-content">
                    <div class="text-center text-muted">
                        <i class="fas fa-info-circle me-2"></i>
                        <small>Enter amounts for outcomes to start building your bet</small>
                    </div>
                </div>
                <div class="border-top pt-3 mt-3" id="bet-total-section" style="display: none;">
                    <div class="d-flex justify-content-between">
                        <strong>Total Amount:</strong>
                        <strong class="text-success" id="bet-total-amount">USh 0.00</strong>
                    </div>
                </div>
            </div>
        </div>

        <!-- Session Information -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-user me-2"></i>Session Info
                </h6>
            </div>
            <div class="card-body p-3">
                <dl class="mb-0 small">
                    <dt class="text-muted">User</dt>
                    <dd>{{ current_user.username }}</dd>

                    <dt class="text-muted">Role</dt>
                    <dd>
                        <span class="badge bg-primary">{{ 'Admin' if current_user.is_admin else 'User' }}</span>
                    </dd>

                    <dt class="text-muted">Date</dt>
                    <dd id="current-date">{{ current_date }}</dd>
                </dl>
            </div>
        </div>

        <!-- Quick Betting Tips -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-lightbulb me-2"></i>Betting Tips
                </h6>
            </div>
            <div class="card-body p-3">
                <ul class="small mb-0 list-unstyled">
                    <li class="mb-2">
                        <i class="fas fa-check-circle text-success me-2"></i>
                        Enter amounts for outcomes to create combination bets
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-dollar-sign text-info me-2"></i>
                        Enter amounts with 2 decimal precision
                    </li>
                    <li class="mb-2">
                        <i class="fas fa-eye text-warning me-2"></i>
                        Review your selections before submitting
                    </li>
                    <li>
                        <i class="fas fa-ban text-danger me-2"></i>
                        Only pending bets can be cancelled
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/currency.js') }}"></script>
<script>
// Update currency symbols when settings are loaded
document.addEventListener('currencySettingsLoaded', function(event) {
    const currencySymbol = event.detail.symbol;
    
    // Update all currency symbol spans
    document.querySelectorAll('.currency-symbol').forEach(span => {
        span.textContent = currencySymbol;
    });
    
    // Update all currency amounts
    document.querySelectorAll('.currency-amount').forEach(element => {
        const amount = parseFloat(element.dataset.amount || 0);
        element.textContent = formatCurrency(amount);
    });
    
    // Update bet total amount
    const totalElement = document.getElementById('bet-total-amount');
    if (totalElement && totalElement.dataset.amount) {
        const amount = parseFloat(totalElement.dataset.amount);
        totalElement.textContent = formatCurrency(amount);
    }
});
document.addEventListener('DOMContentLoaded', function() {
    // Load available matches on page load
    loadAvailableMatches();

    // Submit bet button
    document.getElementById('btn-submit-bet').addEventListener('click', function() {
        submitBet();
    });
});

let selectedOutcomes = new Map(); // matchId -> { outcomes: [], amounts: [] }

// Function to load and display available matches for betting
function loadAvailableMatches() {
    console.log('🔍 loadAvailableMatches() called');

    const container = document.getElementById('available-matches-container');
    const countBadge = document.getElementById('available-matches-count');

    if (!container) {
        console.error('❌ available-matches-container not found');
        return;
    }

    console.log('📡 Making API request to /api/cashier/available-matches');

    fetch('/api/cashier/available-matches')
        .then(response => {
            console.log('📡 API response status:', response.status);
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('📦 API response data:', data);

            if (data.success) {
                // Update count badge
                countBadge.textContent = data.total;
                countBadge.className = data.total > 0 ? 'badge bg-success ms-2' : 'badge bg-warning ms-2';

                updateAvailableMatchesDisplay(data, container);
            } else {
                container.innerHTML = `
                    <div class="text-center text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${data.error || 'Unknown error'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('❌ Error loading matches:', error);
            container.innerHTML = `
                <div class="text-center text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>Error loading matches: ${error.message}
                </div>
            `;
        });
}

function generateOutcomeOptionsHTML(match, matchId) {
    // Use actual outcomes from the database if available, otherwise fallback to defaults
    let outcomes = match.outcomes || [];
    
    // If no outcomes from database, use standard fallback
    if (outcomes.length === 0) {
        console.warn(`No outcomes found for match ${matchId}, using standard fallback`);
        outcomes = [
            { outcome_name: 'WIN1', display_name: `WIN1 - ${match.fighter1_township}`, outcome_id: null },
            { outcome_name: 'WIN2', display_name: `WIN2 - ${match.fighter2_township}`, outcome_id: null },
            { outcome_name: 'X', display_name: 'X - Draw', outcome_id: null }
        ];
    }
    
    let outcomesHTML = '';
    const colors = ['border-success text-success', 'border-danger text-danger', 'border-warning text-warning', 'border-info text-info', 'border-primary text-primary'];
    
    outcomes.forEach((outcome, index) => {
        const colorClass = colors[index % colors.length];
        const outcomeName = outcome.outcome_name;
        const displayName = outcome.display_name || outcome.outcome_name;
        
        outcomesHTML += `
            <div class="col-md-4 mb-3">
                <div class="card ${colorClass.split(' ')[0]}">
                    <div class="card-body text-center p-3">
                        <div class="mb-2">
                            <label class="form-label fw-bold ${colorClass.split(' ')[1]}">
                                ${displayName}
                            </label>
                        </div>
                        <div class="input-group input-group-sm">
                            <span class="input-group-text currency-symbol">USh</span>
                            <input type="number" class="form-control amount-input"
                                   id="amount-${matchId}-${outcomeName}"
                                   data-match-id="${matchId}"
                                   data-outcome="${outcomeName}"
                                   placeholder="0.00" step="0.01" min="0.01">
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    return outcomesHTML;
}

function updateAvailableMatchesDisplay(data, container) {
    if (data.total === 0) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>No matches available for betting today
                <div class="mt-2">
                    <small>Matches must be in 'bet' status to accept wagers</small>
                </div>
            </div>
        `;
        return;
    }

    let htmlContent = '';

    data.matches.forEach(match => {
        const matchId = match.id;
        const startTime = match.start_time ? new Date(match.start_time).toLocaleString() : 'TBD';
        
        htmlContent += `
            <div class="card mb-3 match-card" data-match-id="${matchId}">
                <div class="card-header bg-light">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h6 class="mb-0">
                                <i class="fas fa-fist-raised me-2 text-primary"></i>
                                Match #${match.match_number}: ${match.fighter1_township} vs ${match.fighter2_township}
                            </h6>
                            <small class="text-muted">
                                <i class="fas fa-map-marker-alt me-1"></i>${match.venue_kampala_township} • 
                                <i class="fas fa-clock me-1"></i>${startTime}
                            </small>
                        </div>
                        <div class="col-md-4 text-end">
                            <button class="btn btn-outline-primary btn-sm toggle-match" data-match-id="${matchId}">
                                <i class="fas fa-chevron-down me-1"></i>Select Outcomes
                            </button>
                        </div>
                    </div>
                </div>
                <div class="card-body match-outcomes" id="outcomes-${matchId}" style="display: none;">
                    <div class="row">
                        <div class="col-12">
                            <h6 class="text-primary mb-3">
                                <i class="fas fa-target me-2"></i>Available Betting Outcomes
                            </h6>
                        </div>
                    </div>
                    <div class="row">
                        ${generateOutcomeOptionsHTML(match, matchId)}
                    </div>
                </div>
            </div>
        `;
    });

    container.innerHTML = htmlContent;

    // Add event listeners for toggle buttons
    container.querySelectorAll('.toggle-match').forEach(button => {
        button.addEventListener('click', function() {
            const matchId = this.getAttribute('data-match-id');
            const outcomesDiv = document.getElementById(`outcomes-${matchId}`);
            const icon = this.querySelector('i');
            
            if (outcomesDiv.style.display === 'none') {
                outcomesDiv.style.display = 'block';
                icon.className = 'fas fa-chevron-up me-1';
                this.innerHTML = '<i class="fas fa-chevron-up me-1"></i>Hide Outcomes';
            } else {
                outcomesDiv.style.display = 'none';
                icon.className = 'fas fa-chevron-down me-1';
                this.innerHTML = '<i class="fas fa-chevron-down me-1"></i>Select Outcomes';
            }
        });
    });

    // Add event listeners for amount inputs only
    container.querySelectorAll('.amount-input').forEach(input => {
        input.addEventListener('input', function() {
            updateBetSummary();
        });
    });
}

function updateBetSummary() {
    const summaryContent = document.getElementById('bet-summary-content');
    const totalSection = document.getElementById('bet-total-section');
    const totalAmountElement = document.getElementById('bet-total-amount');
    const submitButton = document.getElementById('btn-submit-bet');
    
    // Clear previous selections
    selectedOutcomes.clear();
    
    let totalAmount = 0;
    let hasSelections = false;
    let summaryHTML = '';
    
    // Collect all amount inputs with values > 0
    document.querySelectorAll('.amount-input').forEach(input => {
        const amount = parseFloat(input.value) || 0;
        
        if (amount > 0) {
            const matchId = input.getAttribute('data-match-id');
            const outcome = input.getAttribute('data-outcome');
            
            hasSelections = true;
            totalAmount += amount;
            
            // Store selection
            if (!selectedOutcomes.has(matchId)) {
                selectedOutcomes.set(matchId, { outcomes: [], amounts: [] });
            }
            const matchSelections = selectedOutcomes.get(matchId);
            matchSelections.outcomes.push(outcome);
            matchSelections.amounts.push(amount);
            
            // Get match info for display
            const matchCard = input.closest('.match-card');
            const matchTitle = matchCard.querySelector('h6').textContent.trim();
            
            summaryHTML += `
                <div class="mb-2 p-2 bg-light rounded">
                    <small class="fw-bold d-block">${matchTitle.split(':')[1]}</small>
                    <small class="text-primary">${outcome}</small>
                    <div class="text-end">
                        <strong class="text-success currency-amount" data-amount="${amount}">${formatCurrency(amount)}</strong>
                    </div>
                </div>
            `;
        }
    });
    
    if (hasSelections) {
        summaryContent.innerHTML = summaryHTML;
        totalSection.style.display = 'block';
        totalAmountElement.textContent = formatCurrency(totalAmount);
        submitButton.disabled = false;
    } else {
        summaryContent.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>
                <small>Enter amounts for outcomes to start building your bet</small>
            </div>
        `;
        totalSection.style.display = 'none';
        submitButton.disabled = true;
    }
}

function submitBet() {
    if (selectedOutcomes.size === 0) {
        showNotification('Please select at least one outcome with an amount', 'error');
        return;
    }
    
    // Prepare bet data
    const betData = {
        bet_details: []
    };
    
    selectedOutcomes.forEach((selections, matchId) => {
        selections.outcomes.forEach((outcome, index) => {
            betData.bet_details.push({
                match_id: parseInt(matchId),
                outcome: outcome,
                amount: selections.amounts[index]
            });
        });
    });
    
    console.log('📤 Submitting bet data:', betData);
    
    // Submit to API
    fetch('/api/cashier/bets', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(betData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('Bet submitted successfully!', 'success');
            setTimeout(() => {
                window.location.href = `/bets/${data.bet_id}`;
            }, 1500);
        } else {
            showNotification('Failed to submit bet: ' + (data.error || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        showNotification('Error submitting bet: ' + error.message, 'error');
    });
}

function showNotification(message, type = 'info') {
    // Simple notification system - could be enhanced with toast notifications
    const alertClass = type === 'success' ? 'alert-success' : type === 'error' ? 'alert-danger' : 'alert-info';
    const notification = document.createElement('div');
    notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
    notification.style.top = '20px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(notification);

    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}
</script>
{% endblock %}