{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-coins me-2"></i>Betting Management
            <small class="text-muted">Welcome, {{ current_user.username }}</small>
        </h1>
    </div>
</div>

<!-- Back Button and New Bet 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-list me-2"></i>Bets Management
                </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='{{ url_for('main.index') }}'">
                            <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                        </button>
                    </div>
                    <div class="col-md-6 mb-3 text-end">
                        <button class="btn btn-success me-2" id="btn-new-bet">
                            <i class="fas fa-plus me-2"></i>New Bet
                        </button>
                        <button class="btn btn-info" id="btn-verify-bet">
                            <i class="fas fa-qrcode me-2"></i>Verify Bet
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Bets Table - Left Side -->
    <div class="col-lg-9 col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-4">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-calendar-alt me-2"></i>Bets for Today
                            <span class="badge bg-info ms-2" id="bets-count">0</span>
                        </h5>
                    </div>
                    <div class="col-md-2">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-calendar"></i>
                            </span>
                            <input type="date" class="form-control" id="bet-date-picker"
                                   value="{{ today_date }}" max="{{ today_date }}">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <select class="form-select" id="bet-status-filter">
                            <option value="">All Status</option>
                            <option value="won">Won</option>
                            <option value="lost">Lost</option>
                            <option value="pending">Pending</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <input type="number" class="form-control" id="match-number-filter"
                               placeholder="Match # (optional)" min="1">
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="bets-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading bets...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Same as Cashier Dashboard -->
    <div class="col-lg-3 col-md-4">
        <!-- Current Display Status - Smaller and Compact -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-desktop me-2"></i>Display Status
                </h6>
            </div>
            <div class="card-body p-3">
                <div class="d-flex flex-column">
                    <!-- Video Status -->
                    <div class="text-center mb-3">
                        <div class="d-flex flex-column align-items-center">
                            <i class="fas fa-video text-primary mb-1" style="font-size: 1.5rem;"></i>
                            <small class="text-primary fw-bold" id="video-status-text">Stopped</small>
                            <small class="text-muted">Video Status</small>
                        </div>
                    </div>

                    <!-- Overlay Status -->
                    <div class="text-center">
                        <div class="d-flex flex-column align-items-center">
                            <i class="fas fa-layer-group text-success mb-1" style="font-size: 1.5rem;"></i>
                            <small class="text-success fw-bold" id="overlay-status-text">Ready</small>
                            <small class="text-muted">Overlay Status</small>
                        </div>
                    </div>
                </div>

                <div class="small">
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted">Video:</span>
                        <small id="current-video-path" class="text-truncate" style="max-width: 120px;">No video loaded</small>
                    </div>
                    <div class="d-flex justify-content-between">
                        <span class="text-muted">Template:</span>
                        <small id="current-template-name">default</small>
                    </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">Login Time</dt>
                    <dd id="login-time">{{ current_user.last_login.strftime('%H:%M') if current_user.last_login else 'Just now' }}</dd>

                    <dt class="text-muted">System Status</dt>
                    <dd>
                        <span class="badge bg-success" id="system-status">Online</span>
                    </dd>
                </dl>
            </div>
        </div>

        <!-- Today's Betting Activity -->
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-bar me-2"></i>Today's Betting
                </h6>
            </div>
            <div class="card-body p-3 text-center">
                <div class="row">
                    <div class="col-6">
                        <h5 class="text-primary mb-1" id="total-bets">0</h5>
                        <small class="text-muted">Total Bets</small>
                    </div>
                    <div class="col-6">
                        <h5 class="text-success mb-1" id="total-amount">$0.00</h5>
                        <small class="text-muted">Total Amount</small>
                    </div>
                </div>
                <div class="row mt-2">
                    <div class="col-4">
                        <h6 class="text-success mb-1" id="won-bets">0</h6>
                        <small class="text-muted">Won</small>
                    </div>
                    <div class="col-4">
                        <h6 class="text-danger mb-1" id="lost-bets">0</h6>
                        <small class="text-muted">Lost</small>
                    </div>
                    <div class="col-4">
                        <h6 class="text-warning mb-1" id="pending-bets">0</h6>
                        <small class="text-muted">Pending</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Thermal Receipt Print Modal -->
<div class="modal fade" id="printReceiptModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-print me-2"></i>Print Receipt
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-0">
                <div id="thermal-receipt" class="thermal-receipt">
                    <!-- Receipt content will be dynamically generated -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>Cancel
                </button>
                <button type="button" class="btn btn-primary" id="btn-print-receipt">
                    <i class="fas fa-print me-1"></i>Print
                </button>
            </div>
        </div>
    </div>
</div>
<!-- Keyboard Shortcuts Help Panel -->
<div id="keyboard-help-panel" class="keyboard-help-panel">
    <div class="keyboard-help-header">
        <i class="fas fa-keyboard me-2"></i>
        <strong>Keyboard Shortcuts</strong>
        <button type="button" class="btn-close btn-close-white ms-auto" onclick="toggleKeyboardHelp()"></button>
    </div>
    <div class="keyboard-help-content">
        <div class="keyboard-shortcut">
            <kbd>Enter</kbd>
            <span>Create New Bet</span>
        </div>
        <div class="keyboard-shortcut">
            <kbd>v</kbd>
            <span>Verify Bet</span>
        </div>
    </div>
</div>

<style>
.keyboard-help-panel {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: rgba(0, 123, 255, 0.95);
    color: white;
    border-radius: 8px;
    padding: 0;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    z-index: 1050;
    min-width: 250px;
    backdrop-filter: blur(10px);
}

.keyboard-help-header {
    background: rgba(0, 0, 0, 0.2);
    padding: 10px 15px;
    border-radius: 8px 8px 0 0;
    display: flex;
    align-items: center;
    font-size: 14px;
}

.keyboard-help-content {
    padding: 15px;
}

.keyboard-shortcut {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 13px;
}

.keyboard-shortcut:last-child {
    margin-bottom: 0;
}

.keyboard-shortcut kbd {
    background: rgba(255, 255, 255, 0.2);
    border: 1px solid rgba(255, 255, 255, 0.3);
    border-radius: 3px;
    padding: 2px 6px;
    font-size: 11px;
    font-weight: bold;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.keyboard-help-panel.minimized {
    width: 50px;
    height: 50px;
    min-width: auto;
    cursor: pointer;
}

.keyboard-help-panel.minimized .keyboard-help-content,
.keyboard-help-panel.minimized .keyboard-help-header .btn-close {
    display: none;
}

.keyboard-help-panel.minimized .keyboard-help-header {
    justify-content: center;
    padding: 0;
    height: 50px;
    border-radius: 50%;
}

.keyboard-help-panel.minimized .keyboard-help-header strong {
    display: none;
}

.keyboard-help-panel.minimized .keyboard-help-header i {
    font-size: 18px;
}
</style>

{% 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) {
    // Update all currency amounts
    document.querySelectorAll('.currency-amount').forEach(element => {
        const amount = parseFloat(element.dataset.amount || 0);
        element.textContent = formatCurrency(amount);
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // Load bets on page load
    loadBets();

    // Initialize keyboard help panel
    initializeKeyboardHelp();

    // Date picker change event
    document.getElementById('bet-date-picker').addEventListener('change', function() {
        loadBets();
    });

    // Status filter change event
    document.getElementById('bet-status-filter').addEventListener('change', function() {
        loadBets();
    });

    // Match number filter change event
    document.getElementById('match-number-filter').addEventListener('input', function() {
        loadBets();
    });

    // New bet button
    document.getElementById('btn-new-bet').addEventListener('click', function() {
        window.location.href = '/bets/new';
    });

    // Verify bet button
    document.getElementById('btn-verify-bet').addEventListener('click', function() {
        window.location.href = '/verify-bet';
    });

    // Keyboard navigation: Enter key moves to /bets/new, 'v' or 'V' moves to verification
    document.addEventListener('keydown', function(event) {
        // Only handle keys if not in an input field
        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA' || event.target.tagName === 'SELECT') {
            return;
        }

        // Enter key moves to new bet page
        if (event.key === 'Enter') {
            event.preventDefault();
            window.location.href = '/bets/new';
        }

        // 'v' or 'V' key moves to bet verification page
        if (event.key === 'v' || event.key === 'V') {
            event.preventDefault();
            window.location.href = '/verify-bet';
        }
    });

    // Print receipt button in modal
    const printReceiptBtn = document.getElementById('btn-print-receipt');
    if (printReceiptBtn) {
        printReceiptBtn.addEventListener('click', function() {
            printThermalReceipt();
        });
    }

    // Status update functions (same as cashier dashboard)
    function updateVideoStatus() {
        fetch('/api/video/status')
        .then(response => response.json())
        .then(data => {
            const status = data.player_status || 'stopped';
            document.getElementById('video-status-text').textContent =
                status.charAt(0).toUpperCase() + status.slice(1);
        })
        .catch(error => {
            document.getElementById('video-status-text').textContent = 'Unknown';
        });
    }

    // Initial status update
    updateVideoStatus();

    // Periodic status updates
    setInterval(updateVideoStatus, 5000);  // Every 5 seconds
    setInterval(loadBets, 10000); // Auto-refresh bets every 10 seconds
});

// Function to load and display bets
function loadBets() {
    console.log('🔍 loadBets() called');

    const container = document.getElementById('bets-container');
    const countBadge = document.getElementById('bets-count');
    const dateInput = document.getElementById('bet-date-picker');
    const statusFilter = document.getElementById('bet-status-filter');
    const matchFilter = document.getElementById('match-number-filter');

    const selectedDate = dateInput.value;
    const selectedStatus = statusFilter.value;
    const selectedMatch = matchFilter.value;

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

    console.log('📡 Making API request to /api/cashier/bets with filters:', {
        date: selectedDate,
        status: selectedStatus,
        match: selectedMatch
    });

    // Show loading state
    container.innerHTML = `
        <div class="text-center text-muted">
            <i class="fas fa-spinner fa-spin me-2"></i>Loading bets...
        </div>
    `;

    // Build query string with filters
    let queryParams = `date=${selectedDate}`;
    if (selectedStatus) {
        queryParams += `&status=${selectedStatus}`;
    }
    if (selectedMatch) {
        queryParams += `&match_number=${selectedMatch}`;
    }

    fetch(`/api/cashier/bets?${queryParams}`)
        .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-info ms-2' : 'badge bg-secondary ms-2';

                // Update statistics
                updateBettingStats(data.stats);

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

function updateBetsTable(data, container) {
    if (data.total === 0) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>No bets found for the selected date
                <div class="mt-2">
                    <button class="btn btn-success" onclick="document.getElementById('btn-new-bet').click()">
                        <i class="fas fa-plus me-2"></i>Create Your First Bet
                    </button>
                </div>
            </div>
        `;
        return;
    }

    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-striped table-hover">
                <thead class="table-dark">
                    <tr>
                        <th><i class="fas fa-hashtag me-1"></i>Bet ID</th>
                        <th><i class="fas fa-barcode me-1"></i>Barcode</th>
                        <th><i class="fas fa-clock me-1"></i>Date & Time</th>
                        <th><i class="fas fa-list-ol me-1"></i>Details</th>
                        <th><i class="fas fa-hashtag me-1"></i>Match</th>
                        <th><i class="fas fa-dollar-sign me-1"></i>Payin</th>
                        <th><i class="fas fa-trophy me-1"></i>Payout</th>
                        <th><i class="fas fa-chart-line me-1"></i>Status</th>
                        <th><i class="fas fa-money-bill me-1"></i>Payment</th>
                        <th><i class="fas fa-cogs me-1"></i>Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;

    data.bets.forEach(bet => {
        const betDateTime = new Date(bet.bet_datetime).toLocaleString();
        const totalAmount = parseFloat(bet.total_amount).toFixed(2);

        // Collect unique match numbers
        const matchNumbers = [...new Set(bet.details ? bet.details.map(detail => detail.match ? detail.match.match_number : 'Unknown').filter(n => n !== 'Unknown') : [])];

        // Determine overall bet status based on details
        let overallStatus = 'pending';
        let statusBadge = '';

        if (bet.details && bet.details.length > 0) {
            const statuses = bet.details.map(detail => detail.result);
            if (statuses.every(status => status === 'win')) {
                overallStatus = 'won';
                statusBadge = '<span class="badge bg-success"><i class="fas fa-trophy me-1"></i>Won</span>';
            } else if (statuses.some(status => status === 'lost')) {
                overallStatus = 'lost';
                statusBadge = '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Lost</span>';
            } else if (statuses.some(status => status === 'cancelled')) {
                overallStatus = 'cancelled';
                statusBadge = '<span class="badge bg-secondary"><i class="fas fa-ban me-1"></i>Cancelled</span>';
            } else {
                statusBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
            }
        } else {
            statusBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
        }

        // Payment status badge
        const paidBadge = bet.paid ?
            '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Paid</span>' :
            '<span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Unpaid</span>';

        // Calculate payout for winning bets
        let payoutAmount = 0.0;
        if (overallStatus === 'won' && bet.details) {
            payoutAmount = bet.details
                .filter(detail => detail.result === 'win')
                .reduce((sum, detail) => sum + parseFloat(detail.win_amount || 0), 0);
        }
        const payoutDisplay = payoutAmount > 0 ? formatCurrency(payoutAmount.toFixed(2)) : '-';

        tableHTML += `
            <tr>
                <td><strong>${bet.uuid.substring(0, 8)}...</strong></td>
                <td>${bet.barcode_data ? bet.barcode_data.substring(0, 16) + '...' : 'N/A'}</td>
                <td>${betDateTime}</td>
                <td>${bet.details ? bet.details.length : 0} selections</td>
                <td>${matchNumbers.length > 0 ? matchNumbers.join(', ') : 'N/A'}</td>
                <td><strong class="currency-amount" data-amount="${totalAmount}">${formatCurrency(totalAmount)}</strong></td>
                <td><strong class="currency-amount" data-amount="${payoutAmount}">${payoutDisplay}</strong></td>
                <td>${statusBadge}</td>
                <td>${paidBadge}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary"
                            onclick="window.location.href='/bets/${bet.uuid}'"
                            title="View Details">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-info ms-1 btn-preview-bet"
                            data-bet-id="${bet.uuid}"
                            title="Preview Bet Receipt">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-secondary ms-1 btn-print-bet"
                            data-bet-id="${bet.uuid}"
                            title="Print Bet Receipt Directly">
                        <i class="fas fa-print"></i>
                    </button>
                    <button class="btn btn-sm btn-outline-danger ms-1 btn-delete-bet"
                            data-bet-id="${bet.uuid}"
                            title="Delete Bet">
                        <i class="fas fa-trash"></i>
                    </button>
                </td>
            </tr>
        `;
    });

    tableHTML += `
                </tbody>
            </table>
        </div>
    `;

    container.innerHTML = tableHTML;

    // Add event listeners for delete buttons
    container.querySelectorAll('.btn-delete-bet').forEach(button => {
        button.addEventListener('click', function() {
            const betId = this.getAttribute('data-bet-id');
            if (confirm('Are you sure you want to permanently delete this bet? This action cannot be undone and will remove all bet data from the database.')) {
                deleteBet(betId);
            }
        });
    });

    // Add event listeners for preview buttons
    container.querySelectorAll('.btn-preview-bet').forEach(button => {
        button.addEventListener('click', function() {
            const betId = this.getAttribute('data-bet-id');
            generateThermalReceiptFromList(betId);
        });
    });

    // Add event listeners for direct print buttons
    container.querySelectorAll('.btn-print-bet').forEach(button => {
        button.addEventListener('click', function() {
            const betId = this.getAttribute('data-bet-id');
            directPrintBet(betId);
        });
    });
}

function updateBettingStats(stats) {
    if (!stats) return;
    
    document.getElementById('total-bets').textContent = stats.total_bets || 0;
    const totalAmountElement = document.getElementById('total-amount');
    totalAmountElement.dataset.amount = stats.total_amount || 0;
    totalAmountElement.textContent = formatCurrency(stats.total_amount || 0);
    document.getElementById('won-bets').textContent = stats.won_bets || 0;
    document.getElementById('lost-bets').textContent = stats.lost_bets || 0;
    document.getElementById('pending-bets').textContent = stats.pending_bets || 0;
}

function deleteBet(betId) {
    fetch(`/api/bets/${betId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Refresh the bets table
            loadBets();
            showNotification('Bet deleted successfully!', 'success');
        } else {
            showNotification('Failed to delete bet: ' + (data.error || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        showNotification('Error deleting bet: ' + error.message, 'error');
    });
}

function generateThermalReceiptFromList(betId) {
    // Fetch bet details from API
    fetch(`/api/cashier/bets/${betId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const betData = transformBetDataForReceipt(data.bet);
                const receiptContainer = document.getElementById('thermal-receipt');
                const receiptHtml = generateReceiptHtml(betData);
                receiptContainer.innerHTML = receiptHtml;

                // Generate verification codes for preview
                generateVerificationCodes(betData.uuid).then(() => {
                    // Show the modal after verification codes are loaded
                    const modal = new bootstrap.Modal(document.getElementById('printReceiptModal'));
                    modal.show();
                }).catch(error => {
                    console.warn('Error generating verification codes for preview, showing modal anyway:', error);
                    // Show modal even if verification codes fail
                    const modal = new bootstrap.Modal(document.getElementById('printReceiptModal'));
                    modal.show();
                });
            } else {
                showNotification('Failed to load bet details for printing: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error loading bet details: ' + error.message, 'error');
        });
}

function transformBetDataForReceipt(betData) {
    // Transform API response to match the expected format
    return {
        uuid: betData.uuid,
        bet_datetime: betData.bet_datetime,
        fixture_id: betData.fixture_id,
        total_amount: betData.total_amount,
        bet_count: betData.details_count || betData.details.length,
        bet_details: betData.details.map(detail => ({
            match_number: detail.match ? detail.match.match_number : 'Unknown',
            fighter1: detail.match ? detail.match.fighter1_township : 'Unknown',
            fighter2: detail.match ? detail.match.fighter2_township : 'Unknown',
            venue: detail.match ? detail.match.venue_kampala_township : 'Unknown',
            outcome: detail.outcome,
            amount: detail.amount,
            result: detail.result
        }))
    };
}

function generateReceiptHtml(betData) {
    const currentDateTime = new Date().toLocaleString();

    let receiptHtml = `
        <div class="thermal-receipt-content">
            <!-- Header -->
            <div class="receipt-header">
                <div class="receipt-title">BETTING SLIP</div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Bet Information -->
            <div class="receipt-info">
                <div class="receipt-row">
                    <span>BET ID:</span>
                    <span>${betData.uuid.substring(0, 8).toUpperCase()}</span>
                </div>
                <div class="receipt-row">
                    <span>DATE:</span>
                    <span>${betData.bet_datetime}</span>
                </div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Bet Details -->
            <div class="receipt-bets">
    `;

    let totalAmount = 0;
    betData.bet_details.forEach((detail, index) => {
        totalAmount += parseFloat(detail.amount);
        receiptHtml += `
                <div class="receipt-bet-item">
                    <div class="receipt-match">
                        MATCH #${detail.match_number}
                    </div>
                    <div class="receipt-match-details">
                        ${detail.fighter1} vs ${detail.fighter2}
                    </div>
                    <div class="receipt-venue">
                        @ ${detail.venue}
                    </div>
                    <div class="receipt-bet-line">
                        <span>OUTCOME: ${detail.outcome}</span>
                        <span>${formatCurrency(parseFloat(detail.amount))}</span>
                    </div>
                </div>
        `;

        if (index < betData.bet_details.length - 1) {
            receiptHtml += `<div class="receipt-separator">- - - - - - - - - - - - - - - - -</div>`;
        }
    });

    receiptHtml += `
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- Total -->
            <div class="receipt-total">
                <div class="receipt-total-line">
                    <span>TOTAL AMOUNT:</span>
                    <span>${formatCurrency(totalAmount)}</span>
                </div>
            </div>

            <!-- Separator -->
            <div class="receipt-separator">================================</div>

            <!-- QR Code and Barcode (conditional based on settings) -->
            <div class="receipt-verification" id="receipt-verification-${betData.uuid}">
                <!-- QR Code and Barcode will be conditionally added here -->
            </div>

            <!-- Footer -->
            <div class="receipt-footer">
                <div>Thank you for betting with MBetter!</div>
                <div>Keep this slip for verification</div>
                <div class="receipt-timestamp">Printed: ${currentDateTime}</div>
            </div>
        </div>
    `;

    return receiptHtml;
}

function generateQRCode(betUuid) {
    // Simple QR code generation using a free service
    const qrContainer = document.getElementById(`qr-code-${betUuid}`);
    if (qrContainer) {
        // Use QR Server API for generating QR code
        const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(betUuid)}&format=png`;
        qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="QR Code" class="qr-image">`;
    }
}

function generateVerificationCodes(betUuid) {
    return new Promise((resolve) => {
        const verificationContainer = document.getElementById(`receipt-verification-${betUuid}`);
        if (!verificationContainer) {
            resolve();
            return;
        }

        let completedOperations = 0;
        const totalOperations = 2; // QR code check + barcode check

        function checkComplete() {
            completedOperations++;
            if (completedOperations >= totalOperations) {
                resolve();
            }
        }

        // Check QR code settings - QR codes should NOT print if disabled
        // Default to NOT showing QR codes if API fails
        let shouldShowQR = false;

        try {
            // Try to get QR settings from API
            fetch('/api/qrcode-settings')
                .then(response => {
                    if (!response.ok) {
                        console.warn('QR settings API failed with status:', response.status);
                        checkComplete();
                        return null;
                    }
                    return response.json();
                })
                .then(qrSettings => {
                    if (qrSettings && qrSettings.success && qrSettings.settings) {
                        shouldShowQR = qrSettings.settings.enabled === true && qrSettings.settings.show_on_thermal === true;
                        console.log('QR settings check result:', shouldShowQR, qrSettings.settings);
                    } else {
                        console.warn('Invalid QR settings response:', qrSettings);
                        shouldShowQR = false; // Default to not showing
                    }

                    // Add QR code if enabled
                    if (shouldShowQR) {
                        console.log('Adding QR code to receipt');
                        const qrHtml = `
                            <div class="receipt-qr">
                                <div class="qr-code" id="qr-code-${betUuid}"></div>
                                <div class="qr-text">Scan QR for verification</div>
                            </div>
                        `;
                        verificationContainer.insertAdjacentHTML('beforeend', qrHtml);

                        // Generate QR code
                        const qrContainer = document.getElementById(`qr-code-${betUuid}`);
                        if (qrContainer) {
                            const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${encodeURIComponent(betUuid)}&format=png`;
                            qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="QR Code" class="qr-image">`;
                        }
                    } else {
                        console.log('QR code disabled - not adding to receipt');
                    }
                    checkComplete();
                })
                .catch(error => {
                    console.warn('Failed to check QR code settings, defaulting to disabled:', error);
                    shouldShowQR = false; // Default to not showing on error
                    checkComplete();
                });
        } catch (error) {
            console.warn('Error in QR code settings check, defaulting to disabled:', error);
            shouldShowQR = false; // Default to not showing on error
            checkComplete();
        }

        // Check barcode settings
        fetch(`/api/barcode-data/${betUuid}`)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.enabled && data.barcode_data && data.barcode_data.show_on_thermal && data.barcode_data.image_base64) {
                    // Add barcode to receipt
                    const barcodeHtml = `
                        <div class="receipt-barcode" id="barcode-container-${betUuid}">
                            <div class="barcode-image" id="barcode-${betUuid}"></div>
                            <div class="barcode-text">Scan barcode for verification</div>
                        </div>
                    `;
                    verificationContainer.insertAdjacentHTML('beforeend', barcodeHtml);

                    // Display barcode
                    const barcodeElement = document.getElementById(`barcode-${betUuid}`);
                    if (barcodeElement) {
                        barcodeElement.innerHTML = `<img src="data:image/png;base64,${data.barcode_data.image_base64}" alt="Barcode" class="barcode-img" style="width: ${data.barcode_data.width}px; height: ${data.barcode_data.height}px;">`;
                    }
                }
                checkComplete();
            })
            .catch(error => {
                console.warn('Failed to check barcode settings:', error);
                checkComplete();
            });
    });
}

function printThermalReceipt() {
    const printContent = document.getElementById('thermal-receipt').innerHTML;
    const printWindow = window.open('', '', 'height=600,width=400');
    
    printWindow.document.write(`
        <html>
        <head>
            <title>Betting Receipt</title>
            <style>
                @media print {
                    body { margin: 0; padding: 10px; font-family: 'Courier New', monospace; }
                    .thermal-receipt-content { width: 100%; }
                    .receipt-header { text-align: center; margin-bottom: 10px; }
                    .receipt-title { font-size: 18px; font-weight: bold; margin-bottom: 2px; }
                    .receipt-separator { text-align: center; margin: 8px 0; font-size: 10px; }
                    .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 10px 0; }
                    .receipt-row, .receipt-bet-line, .receipt-total-line { 
                        display: flex; justify-content: space-between; margin-bottom: 2px; font-size: 11px;
                    }
                    .receipt-bet-item { margin-bottom: 8px; }
                    .receipt-match { font-weight: bold; font-size: 12px; text-align: center; }
                    .receipt-match-details { font-size: 10px; text-align: center; margin-bottom: 2px; }
                    .receipt-venue { font-size: 9px; text-align: center; margin-bottom: 3px; }
                    .receipt-status { font-size: 9px; text-align: center; margin-top: 2px; }
                    .receipt-total { border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
                    .receipt-verification { text-align: center; margin: 10px 0; }
                    .receipt-qr, .receipt-barcode { margin: 5px 0; }
                    .qr-image { width: 80px; height: 80px; }
                    .qr-text, .barcode-text { font-size: 9px; margin-top: 3px; }
                    .barcode-img { max-width: 120px; height: auto; }
                    .receipt-footer { text-align: center; font-size: 9px; margin-top: 10px; border-top: 1px solid #000; padding-top: 5px; }
                    .receipt-timestamp { margin-top: 5px; font-size: 8px; }
                }
                
                body { 
                    font-family: 'Courier New', monospace; 
                    font-size: 11px; 
                    line-height: 1.2; 
                    color: #000; 
                    background: #fff; 
                }
                .thermal-receipt-content {
                    max-width: 300px;
                    margin: 0 auto;
                    padding: 10px;
                }
                .receipt-header { text-align: center; margin-bottom: 15px; }
                .receipt-title { font-size: 20px; font-weight: bold; margin-bottom: 3px; letter-spacing: 2px; }
                .receipt-separator { 
                    text-align: center; 
                    margin: 12px 0; 
                    font-size: 11px; 
                    letter-spacing: -1px; 
                }
                .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 15px 0; }
                .receipt-row, .receipt-bet-line, .receipt-total-line { 
                    display: flex; 
                    justify-content: space-between; 
                    margin-bottom: 3px; 
                    font-size: 12px;
                }
                .receipt-bet-item { margin-bottom: 12px; }
                .receipt-match { font-weight: bold; font-size: 13px; text-align: center; }
                .receipt-match-details { font-size: 11px; text-align: center; margin-bottom: 3px; }
                .receipt-venue { font-size: 10px; text-align: center; margin-bottom: 4px; color: #666; }
                .receipt-status { font-size: 10px; text-align: center; margin-top: 3px; font-weight: bold; }
                .receipt-total { 
                    border-top: 2px solid #000; 
                    padding-top: 8px; 
                    font-weight: bold; 
                    font-size: 14px;
                }
                .qr-image { width: 100px; height: 100px; border: 1px solid #ccc; }
                .qr-text { font-size: 10px; margin-top: 5px; }
                .receipt-footer {
                    text-align: center;
                    font-size: 10px;
                    margin-top: 15px;
                    border-top: 1px solid #000;
                    padding-top: 8px;
                }
                .receipt-timestamp { margin-top: 8px; font-size: 9px; color: #666; }
            </style>
        </head>
        <body>
            ${printContent}
        </body>
        </html>
    `);
    
    printWindow.document.close();
    printWindow.focus();
    
    // Wait for images to load then print
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}

function directPrintBet(betId) {
    // Fetch bet details and print directly without modal
    fetch(`/api/cashier/bets/${betId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const betData = transformBetDataForReceipt(data.bet);
                const receiptHtml = generateReceiptHtml(betData);

                // Create temporary container for receipt content
                const tempContainer = document.createElement('div');
                tempContainer.innerHTML = receiptHtml;
                tempContainer.style.display = 'none';
                document.body.appendChild(tempContainer);

                // Generate verification codes and wait for completion
                generateVerificationCodes(betData.uuid).then(() => {
                    // Get the updated HTML content after verification codes are added
                    const updatedReceiptHtml = tempContainer.innerHTML;
                    printDirectly(updatedReceiptHtml);
                    document.body.removeChild(tempContainer);
                }).catch(error => {
                    console.warn('Error generating verification codes, printing without them:', error);
                    // Print anyway even if verification codes fail
                    printDirectly(receiptHtml);
                    document.body.removeChild(tempContainer);
                });
            } else {
                showNotification('Failed to load bet details for printing: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error loading bet details: ' + error.message, 'error');
        });
}

function printDirectly(printContent) {
    const printWindow = window.open('', '', 'height=600,width=400');
    
    printWindow.document.write(`
        <html>
        <head>
            <title>Betting Receipt</title>
            <style>
                @media print {
                    body { margin: 0; padding: 10px; font-family: 'Courier New', monospace; }
                    .thermal-receipt-content { width: 100%; }
                    .receipt-header { text-align: center; margin-bottom: 10px; }
                    .receipt-logo { font-size: 24px; margin-bottom: 5px; }
                    .boxing-glove { color: #000; }
                    .receipt-title { font-size: 18px; font-weight: bold; margin-bottom: 2px; }
                    .receipt-subtitle { font-size: 12px; margin-bottom: 5px; }
                    .receipt-separator { text-align: center; margin: 8px 0; font-size: 10px; }
                    .receipt-info, .receipt-bets, .receipt-total, .receipt-footer { margin: 10px 0; }
                    .receipt-row, .receipt-bet-line, .receipt-total-line {
                        display: flex; justify-content: space-between; margin-bottom: 2px; font-size: 11px;
                    }
                    .receipt-bet-item { margin-bottom: 8px; }
                    .receipt-match { font-weight: bold; font-size: 12px; text-align: center; }
                    .receipt-match-details { font-size: 10px; text-align: center; margin-bottom: 2px; }
                    .receipt-venue { font-size: 9px; text-align: center; margin-bottom: 3px; }
                    .receipt-status { font-size: 9px; text-align: center; margin-top: 2px; }
                    .receipt-total { border-top: 1px solid #000; padding-top: 5px; font-weight: bold; }
                    .receipt-verification { text-align: center; margin: 10px 0; }
                    .receipt-qr, .receipt-barcode { margin: 5px 0; text-align: center; }
                    .qr-image { width: 80px; height: 80px; }
                    .qr-text, .barcode-text { font-size: 9px; margin-top: 3px; }
                    .barcode-img { width: auto; height: auto; max-width: 150px; }
                    .receipt-footer { text-align: center; font-size: 9px; margin-top: 10px; border-top: 1px solid #000; padding-top: 5px; }
                    .receipt-timestamp { margin-top: 5px; font-size: 8px; }
                }
            </style>
        </head>
        <body onload="window.print(); window.close();">
            ${printContent}
        </body>
        </html>
    `);
    
    printWindow.document.close();
}

function initializeKeyboardHelp() {
    const helpPanel = document.getElementById('keyboard-help-panel');

    // Auto-minimize after 10 seconds
    setTimeout(() => {
        if (helpPanel && !helpPanel.classList.contains('minimized')) {
            helpPanel.classList.add('minimized');
        }
    }, 10000);

    // Add global keyboard listener for 'h' key to toggle help
    document.addEventListener('keydown', function(event) {
        if (event.key === 'h' || event.key === 'H') {
            event.preventDefault();
            toggleKeyboardHelp();
        }
    });
}

function toggleKeyboardHelp() {
    const helpPanel = document.getElementById('keyboard-help-panel');
    if (helpPanel) {
        helpPanel.classList.toggle('minimized');
    }
}

function showNotification(message, type = 'info') {
    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 %}