{% 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='/dashboard/cashier'">
                            <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" id="btn-new-bet">
                            <i class="fas fa-plus me-2"></i>New 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-8">
                        <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-4">
                        <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>
            </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-info">Cashier</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>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load bets on page load
    loadBets();

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

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

    // 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 selectedDate = dateInput.value;

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

    console.log('📡 Making API request to /api/cashier/bets for date:', selectedDate);

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

    fetch(`/api/cashier/bets?date=${selectedDate}`)
        .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-clock me-1"></i>Date & Time</th>
                        <th><i class="fas fa-list-ol me-1"></i>Details</th>
                        <th><i class="fas fa-dollar-sign me-1"></i>Total Amount</th>
                        <th><i class="fas fa-chart-line me-1"></i>Status</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);
        
        // 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 === 'won')) {
                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>';
        }

        tableHTML += `
            <tr>
                <td><strong>${bet.uuid.substring(0, 8)}...</strong></td>
                <td>${betDateTime}</td>
                <td>${bet.details ? bet.details.length : 0} selections</td>
                <td><strong>$${totalAmount}</strong></td>
                <td>${statusBadge}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary"
                            onclick="window.location.href='/cashier/bets/${bet.uuid}'"
                            title="View Details">
                        <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">
                        <i class="fas fa-print"></i>
                    </button>
                    ${overallStatus === 'pending' ? `
                    <button class="btn btn-sm btn-outline-danger ms-1 btn-cancel-bet"
                            data-bet-id="${bet.uuid}"
                            title="Cancel Bet">
                        <i class="fas fa-ban"></i>
                    </button>
                    ` : ''}
                </td>
            </tr>
        `;
    });

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

    container.innerHTML = tableHTML;

    // Add event listeners for cancel buttons
    container.querySelectorAll('.btn-cancel-bet').forEach(button => {
        button.addEventListener('click', function() {
            const betId = this.getAttribute('data-bet-id');
            if (confirm('Are you sure you want to cancel this bet? This action cannot be undone.')) {
                cancelBet(betId);
            }
        });
    });

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

function updateBettingStats(stats) {
    if (!stats) return;
    
    document.getElementById('total-bets').textContent = stats.total_bets || 0;
    document.getElementById('total-amount').textContent = '$' + (parseFloat(stats.total_amount || 0).toFixed(2));
    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 cancelBet(betId) {
    fetch(`/api/cashier/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 cancelled successfully!', 'success');
        } else {
            showNotification('Failed to cancel bet: ' + (data.error || 'Unknown error'), 'error');
        }
    })
    .catch(error => {
        showNotification('Error cancelling bet: ' + error.message, 'error');
    });
}

function printBet(betId) {
    // Placeholder function for printing bet receipt
    // This will be implemented later with actual print functionality
    console.log('Print bet requested for bet ID:', betId);
    showNotification('Print functionality will be implemented soon!', 'info');
    
    // TODO: Implement actual print functionality
    // This could involve:
    // 1. Opening a new window with a formatted receipt
    // 2. Calling a print API endpoint
    // 3. Generating a PDF for printing
}

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

    // Auto-remove after 3 seconds
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}
</script>
<!-- Include the main dashboard.js for timer functionality -->
<script src="{{ url_for('static', filename='js/dashboard.js') }}"></script>
<script>
// Initialize dashboard with timer functionality
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Dashboard with timer support
    if (typeof Dashboard !== 'undefined') {
        Dashboard.init({
            user: {
                username: '{{ current_user.username }}',
                role: 'cashier'
            }
        });
    }
});
</script>
{% endblock %}