{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-info-circle me-2"></i>Bet Details
            <small class="text-muted">Bet ID: {{ bet.uuid[:8] }}...</small>
        </h1>
    </div>
</div>

<!-- Back button and controls -->
<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-cog me-2"></i>Bet Controls
                </h5>
            </div>
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-md-3 mb-3">
                        <a href="{{ url_for('main.bets') }}" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-arrow-left me-2"></i>Back to Bets
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <button class="btn btn-outline-info w-100 btn-preview-bet"
                                data-bet-id="{{ bet.uuid }}"
                                title="Preview Bet Receipt">
                            <i class="fas fa-eye me-2"></i>Preview Receipt
                        </button>
                    </div>
                    <div class="col-md-3 mb-3">
                        <button class="btn btn-outline-primary w-100 btn-print-bet"
                                data-bet-id="{{ bet.uuid }}"
                                title="Print Bet Receipt Directly">
                            <i class="fas fa-print me-2"></i>Print Directly
                        </button>
                    </div>
                    <div class="col-md-3 mb-3">
                        {% if bet.has_pending %}
                        <button class="btn btn-danger w-100" id="btn-cancel-bet" data-bet-uuid="{{ bet.uuid }}">
                            <i class="fas fa-times me-2"></i>Cancel Entire Bet
                        </button>
                        {% endif %}
                    </div>
                    <div class="col-md-3 mb-3">
                        <div class="text-center">
                            <strong class="text-success h4 currency-amount" data-amount="{{ bet.total_amount|round(2) }}">Total: €{{ bet.total_amount|round(2) }}</strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Main Content Layout -->
<div class="row">
    <!-- Bet Details List - 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-ul me-2"></i>Bet Details
                    <span class="badge bg-info ms-2">{{ bet.bet_count }} items</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="bet-details-container">
                    {% if bet.bet_details %}
                    <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>Match</th>
                                    <th><i class="fas fa-target me-1"></i>Outcome</th>
                                    <th><i class="fas fa-euro-sign me-1"></i>Amount</th>
                                    <th><i class="fas fa-flag me-1"></i>Result</th>
                                    <th><i class="fas fa-cogs me-1"></i>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for detail in bet.bet_details %}
                                <tr>
                                    <td>
                                        <strong>Match #{{ detail.match.match_number }}</strong><br>
                                        <small class="text-muted">
                                            {{ detail.match.fighter1_township }} vs {{ detail.match.fighter2_township }}
                                        </small>
                                    </td>
                                    <td>
                                        <span class="badge bg-primary">{{ detail.outcome }}</span>
                                    </td>
                                    <td>
                                        <strong class="currency-amount" data-amount="{{ detail.amount|round(2) }}">€{{ detail.amount|round(2) }}</strong>
                                    </td>
                                    <td>
                                        {% if detail.result == 'pending' %}
                                            <span class="badge bg-warning">Pending</span>
                                        {% elif detail.result == 'win' %}
                                            <span class="badge bg-success">Won</span>
                                        {% elif detail.result == 'lost' %}
                                            <span class="badge bg-danger">Lost</span>
                                        {% elif detail.result == 'cancelled' %}
                                            <span class="badge bg-secondary">Cancelled</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if detail.result == 'pending' %}
                                        <button class="btn btn-sm btn-outline-danger btn-delete-detail"
                                                data-detail-id="{{ detail.id }}"
                                                title="Delete this bet detail">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                        {% else %}
                                        <span class="text-muted">No actions</span>
                                        {% endif %}
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% else %}
                    <div class="text-center text-muted">
                        <i class="fas fa-inbox me-2"></i>No bet details found
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    <!-- Right Column - Bet Summary -->
    <div class="col-lg-3 col-md-4">
        <!-- Bet Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-info me-2"></i>Bet Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <dl class="mb-0 small">
                    <dt class="text-muted">Bet UUID</dt>
                    <dd class="font-monospace">{{ bet.uuid }}</dd>

                    <dt class="text-muted">Created</dt>
                    <dd>{{ bet.bet_datetime.strftime('%Y-%m-%d %H:%M') }}</dd>

                    <dt class="text-muted">Fixture</dt>
                    <dd>{{ bet.fixture_id }}</dd>

                    <dt class="text-muted">Total Items</dt>
                    <dd><span class="badge bg-info">{{ bet.bet_count }}</span></dd>

                    <dt class="text-muted">Total Amount</dt>
                    <dd><strong class="text-success currency-amount" data-amount="{{ bet.total_amount|round(2) }}">€{{ bet.total_amount|round(2) }}</strong></dd>

                    <dt class="text-muted">Status</dt>
                    <dd>
                        {% if bet.has_pending %}
                            <span class="badge bg-warning">Has Pending</span>
                        {% else %}
                            <span class="badge bg-success">Completed</span>
                        {% endif %}
                    </dd>

                    <dt class="text-muted">Payment Status</dt>
                    <dd>
                        {% if bet.paid %}
                            <span class="badge bg-success"><i class="fas fa-check me-1"></i>Paid</span>
                        {% else %}
                            <span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Unpaid</span>
                        {% endif %}
                    </dd>
                </dl>
            </div>
        </div>

        <!-- QR Code for Verification -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-qrcode me-2"></i>Bet Verification
                </h6>
            </div>
            <div class="card-body p-3 text-center">
                <div id="bet-verification-qr" class="mb-3">
                    <div class="spinner-border spinner-border-sm" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                <p class="text-muted small">
                    Scan this QR code for bet verification
                </p>
                <div class="input-group input-group-sm">
                    <input type="text" class="form-control" id="bet-uuid-text" value="{{ bet.uuid }}" readonly>
                    <button class="btn btn-outline-secondary btn-sm" onclick="copyBetUuid()">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Payment Actions -->
        {% if not bet.paid %}
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-money-bill me-2"></i>Payment Actions
                </h6>
            </div>
            <div class="card-body p-3">
                <button class="btn btn-success w-100" id="btn-mark-paid" data-bet-uuid="{{ bet.uuid }}">
                    <i class="fas fa-check me-2"></i>Mark as Paid
                </button>
                <p class="text-muted small mt-2 mb-0">
                    Mark this bet as paid when payment is received from customer
                </p>
            </div>
        </div>
        {% endif %}

        <!-- Results Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-pie me-2"></i>Results Summary
                </h6>
            </div>
            <div class="card-body p-3">
                <div class="row text-center">
                    <div class="col-6 mb-2">
                        <h6 class="text-warning mb-1">{{ results.pending }}</h6>
                        <small class="text-muted">Pending</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-success mb-1">{{ results.won }}</h6>
                        <small class="text-muted">Won</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-danger mb-1">{{ results.lost }}</h6>
                        <small class="text-muted">Lost</small>
                    </div>
                    <div class="col-6 mb-2">
                        <h6 class="text-secondary mb-1">{{ results.cancelled }}</h6>
                        <small class="text-muted">Cancelled</small>
                    </div>
                </div>
                <hr class="my-2">
                <div class="text-center">
                    <strong class="text-success currency-amount" data-amount="{{ results.winnings|round(2) }}">Winnings: €{{ results.winnings|round(2) }}</strong>
                </div>
            </div>
        </div>

        <!-- Session Info -->
        <div class="card">
            <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">Current Time</dt>
                    <dd id="current-time">Loading...</dd>
                </dl>
            </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>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/currency.js') }}"></script>
<script type="application/json" id="bet-data-json">
{
    "uuid": "{{ bet.uuid }}",
    "bet_datetime": "{{ bet.bet_datetime.strftime('%Y-%m-%d %H:%M:%S') }}",
    "fixture_id": "{{ bet.fixture_id }}",
    "total_amount": {{ bet.total_amount|round(2) }},
    "bet_count": {{ bet.bet_count }},
    "bet_details": [
        {% for detail in bet.bet_details %}
        {
            "match_number": "{{ detail.match.match_number if detail.match else 'Unknown' }}",
            "fighter1": "{{ detail.match.fighter1_township if detail.match else 'Unknown' }}",
            "fighter2": "{{ detail.match.fighter2_township if detail.match else 'Unknown' }}",
            "venue": "{{ detail.match.venue_kampala_township if detail.match else 'Unknown' }}",
            "outcome": "{{ detail.outcome }}",
            "amount": {{ detail.amount|round(2) }},
            "result": "{{ detail.result }}"
        }{% if not loop.last %},{% endif %}
        {% endfor %}
    ]
}
</script>
<script>
// Global bet data for printing
window.betData = JSON.parse(document.getElementById('bet-data-json').textContent);

// 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);
        const prefix = element.textContent.includes('Total:') ? 'Total: ' :
                      element.textContent.includes('Winnings:') ? 'Winnings: ' : '';
        element.textContent = prefix + formatCurrency(amount);
    });
});

document.addEventListener('DOMContentLoaded', function() {
    // Generate QR code for bet verification
    generateBetVerificationQR();
    
    // Cancel entire bet button
    const cancelBetBtn = document.getElementById('btn-cancel-bet');
    if (cancelBetBtn) {
        cancelBetBtn.addEventListener('click', function() {
            const betUuid = this.dataset.betUuid;
            cancelEntireBet(betUuid);
        });
    }
    
    // Delete bet detail buttons
    const deleteDetailBtns = document.querySelectorAll('.btn-delete-detail');
    deleteDetailBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const detailId = this.dataset.detailId;
            deleteBetDetail(detailId);
        });
    });

    // Preview bet button
    const previewBetBtns = document.querySelectorAll('.btn-preview-bet');
    previewBetBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const betId = this.dataset.betId;
            generateThermalReceipt(betId);
        });
    });

    // Print bet button (direct print)
    const printBetBtns = document.querySelectorAll('.btn-print-bet');
    printBetBtns.forEach(function(btn) {
        btn.addEventListener('click', function() {
            const betId = this.dataset.betId;
            directPrintBet(betId);
        });
    });
    
    // Print receipt button in modal
    const printReceiptBtn = document.getElementById('btn-print-receipt');
    if (printReceiptBtn) {
        printReceiptBtn.addEventListener('click', function() {
            printThermalReceipt();
        });
    }
    
    // Mark as paid button
    const markPaidBtn = document.getElementById('btn-mark-paid');
    if (markPaidBtn) {
        markPaidBtn.addEventListener('click', function() {
            const betUuid = this.dataset.betUuid;
            markBetAsPaid(betUuid);
        });
    }
    
    // Update current time every second
    setInterval(updateCurrentTime, 1000);
    updateCurrentTime();
});

function generateThermalReceipt(betId) {
    // Get bet details from the global bet data
    const receiptContainer = document.getElementById('thermal-receipt');
    const receiptHtml = generateReceiptHtml(window.betData);
    receiptContainer.innerHTML = receiptHtml;
    
    // Show the modal
    const modal = new bootstrap.Modal(document.getElementById('printReceiptModal'));
    modal.show();
}

function generateReceiptHtml(betData) {
    const currentDateTime = new Date().toLocaleString();
    
    let receiptHtml = `
        <div class="thermal-receipt-content">
            <!-- Header with Boxing Glove Icon -->
            <div class="receipt-header">
                <div class="receipt-logo">
                    <i class="fas fa-hand-rock boxing-glove"></i>
                </div>
                <div class="receipt-title">MBETTER</div>
                <div class="receipt-subtitle">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 class="receipt-row">
                    <span>FIXTURE:</span>
                    <span>${betData.fixture_id}</span>
                </div>
                <div class="receipt-row">
                    <span>ITEMS:</span>
                    <span>${betData.bet_count}</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 class="receipt-status">
                        STATUS: ${detail.result.toUpperCase()}
                    </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 -->
            <div class="receipt-verification">
                <div class="receipt-qr">
                    <div class="qr-code" id="qr-code-${betData.uuid}"></div>
                    <div class="qr-text">Scan QR for verification</div>
                </div>
                <div class="receipt-barcode" id="barcode-container-${betData.uuid}" style="display: none;">
                    <div class="barcode-image" id="barcode-${betData.uuid}"></div>
                    <div class="barcode-text">Scan barcode for verification</div>
                </div>
            </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>
    `;
    
    // Generate QR code and barcode after inserting HTML
    setTimeout(() => {
        generateQRCode(betData.uuid);
        generateBarcodeForReceipt(betData.uuid);
    }, 100);
    
    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 generateBarcodeForReceipt(betUuid) {
    // Generate barcode for thermal receipt if enabled
    fetch(`/api/barcode-data/${betUuid}`)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.enabled && data.barcode_data) {
                const barcodeData = data.barcode_data;
                
                // Only show barcode if configured for thermal receipts
                if (barcodeData.show_on_thermal && barcodeData.image_base64) {
                    const barcodeContainer = document.getElementById(`barcode-container-${betUuid}`);
                    const barcodeElement = document.getElementById(`barcode-${betUuid}`);
                    
                    if (barcodeContainer && barcodeElement) {
                        // Display the barcode image
                        barcodeElement.innerHTML = `<img src="data:image/png;base64,${barcodeData.image_base64}" alt="Barcode" class="barcode-img" style="max-width: ${barcodeData.width}px; height: ${barcodeData.height}px;">`;
                        barcodeContainer.style.display = 'block';
                    }
                }
            }
        })
        .catch(error => {
            console.warn('Failed to load barcode data:', error);
            // Don't show error to user, just log it - barcodes are optional
        });
}

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-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; }
                    .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-logo { font-size: 28px; margin-bottom: 5px; }
                .boxing-glove { color: #000; }
                .receipt-title { font-size: 20px; font-weight: bold; margin-bottom: 3px; letter-spacing: 2px; }
                .receipt-subtitle { font-size: 14px; margin-bottom: 5px; }
                .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;
                }
                .receipt-verification { text-align: center; margin: 15px 0; }
                .receipt-qr, .receipt-barcode { margin: 8px 0; }
                .qr-image { width: 100px; height: 100px; border: 1px solid #ccc; }
                .qr-text, .barcode-text { font-size: 10px; margin-top: 5px; }
                .barcode-img { max-width: 150px; height: auto; border: 1px solid #ccc; }
                .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 deleteBetDetail(detailId) {
    if (confirm('Are you sure you want to delete this bet detail? This action cannot be undone.')) {
        fetch(`/api/cashier/bet-details/${detailId}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Bet detail deleted successfully', 'success');
                // Reload the page to update the display
                window.location.reload();
            } else {
                showNotification('Failed to delete bet detail: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error deleting bet detail: ' + error.message, 'error');
        });
    }
}

function cancelEntireBet(betUuid) {
    if (confirm('Are you sure you want to cancel the entire bet? All pending bet details will be cancelled. This action cannot be undone.')) {
        fetch(`/api/cashier/bets/${betUuid}`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Entire bet cancelled successfully', 'success');
                // Redirect back to bets list
                window.location.href = '/bets';
            } else {
                showNotification('Failed to cancel bet: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error cancelling bet: ' + error.message, 'error');
        });
    }
}

function updateCurrentTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString();
    const timeElement = document.getElementById('current-time');
    if (timeElement) {
        timeElement.textContent = timeString;
    }
}

function generateBetVerificationQR() {
    const betUuid = window.betData.uuid;
    const qrContainer = document.getElementById('bet-verification-qr');
    
    if (qrContainer && betUuid) {
        // Use QR Server API for generating QR code
        const qrImageUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(betUuid)}&format=png`;
        qrContainer.innerHTML = `<img src="${qrImageUrl}" alt="Bet Verification QR Code" class="img-fluid" style="max-width: 200px;">`;
    }
}

function copyBetUuid() {
    const element = document.getElementById('bet-uuid-text');
    if (element) {
        element.select();
        element.setSelectionRange(0, 99999);
        document.execCommand('copy');
        
        // Show feedback
        const button = element.nextElementSibling;
        const originalHtml = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check"></i>';
        button.classList.add('btn-success');
        button.classList.remove('btn-outline-secondary');
        
        setTimeout(() => {
            button.innerHTML = originalHtml;
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
        }, 2000);
        
        showNotification('Bet UUID copied to clipboard!', 'success');
    }
}

function markBetAsPaid(betUuid) {
    if (confirm('Are you sure you want to mark this bet as paid? This action cannot be undone.')) {
        fetch(`/api/bets/${betUuid}/mark-paid`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('Bet marked as paid successfully!', 'success');
                // Reload the page to update the display
                window.location.reload();
            } else {
                showNotification('Failed to mark bet as paid: ' + (data.error || 'Unknown error'), 'error');
            }
        })
        .catch(error => {
            showNotification('Error marking bet as paid: ' + error.message, 'error');
        });
    }
}

function directPrintBet(betId) {
    // Use the global bet data for direct printing
    const receiptHtml = generateReceiptHtml(window.betData);
    printDirectly(receiptHtml);
}

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 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 %}