{% 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-4 mb-3">
                        <a href="{{ url_for('main.cashier_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-4 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-4 mb-3">
                        <div class="text-center">
                            <strong class="text-success h4">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>€{{ 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">€{{ 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>
                </dl>
            </div>
        </div>

        <!-- 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">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-info">Cashier</span>
                    </dd>

                    <dt class="text-muted">Current Time</dt>
                    <dd id="current-time">{{ moment().format('HH:mm:ss') }}</dd>
                </dl>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Cancel entire bet button
    const cancelBetBtn = document.getElementById('btn-cancel-bet');
    if (cancelBetBtn) {
        cancelBetBtn.addEventListener('click', function() {
            const betUuid = this.dataset.betUuid;
            cancelEntireBet(betUuid);
        });
    }
    
    // Update current time every second
    setInterval(updateCurrentTime, 1000);
    updateCurrentTime();
});

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}/cancel`, {
            method: 'POST',
            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 = '/cashier/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 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 %}