{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-chart-bar me-2"></i>Extraction Statistics
            <small class="text-muted">Match betting analytics and performance metrics</small>
        </h1>
    </div>
</div>

<!-- Statistics Overview Cards -->
<div class="row mb-4">
    <div class="col-md-3 mb-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-trophy text-warning fa-2x mb-2"></i>
                <h4 class="card-title" id="total-matches">0</h4>
                <p class="card-text text-muted">Total Matches</p>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-coins text-success fa-2x mb-2"></i>
                <h4 class="card-title" id="total-collected">USh 0</h4>
                <p class="card-text text-muted">Total Collected</p>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-hand-holding-usd text-primary fa-2x mb-2"></i>
                <h4 class="card-title" id="total-redistributed">USh 0</h4>
                <p class="card-text text-muted">Total Redistributed</p>
            </div>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="card">
            <div class="card-body text-center">
                <i class="fas fa-chart-line text-info fa-2x mb-2"></i>
                <h4 class="card-title" id="net-profit">USh 0</h4>
                <p class="card-text text-muted">Net Profit</p>
            </div>
        </div>
    </div>
</div>

<!-- Filters 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-filter me-2"></i>Filters
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label class="form-label">Date Range</label>
                        <select class="form-select" id="date-range">
                            <option value="today">Today</option>
                            <option value="week">This Week</option>
                            <option value="month" selected>This Month</option>
                            <option value="all">All Time</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Fixture ID</label>
                        <input type="text" class="form-control" id="fixture-filter" placeholder="Filter by fixture ID">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Result Type</label>
                        <select class="form-select" id="result-filter">
                            <option value="">All Results</option>
                            <option value="UNDER">UNDER</option>
                            <option value="OVER">OVER</option>
                            <option value="WIN1">WIN1</option>
                            <option value="WIN2">WIN2</option>
                            <option value="KO1">KO1</option>
                            <option value="KO2">KO2</option>
                            <option value="DRAW">DRAW</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-grid">
                            <button class="btn btn-primary" id="apply-filters">
                                <i class="fas fa-search me-1"></i>Apply Filters
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Statistics Table -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-table me-2"></i>Match Statistics
                    <span class="badge bg-primary ms-2" id="stats-count">0</span>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover" id="statistics-table">
                        <thead class="table-dark">
                            <tr>
                                <th><i class="fas fa-calendar me-1"></i>Date/Time</th>
                                <th><i class="fas fa-hashtag me-1"></i>Match #</th>
                                <th><i class="fas fa-layer-group me-1"></i>Fixture</th>
                                <th><i class="fas fa-trophy me-1"></i>Result</th>
                                <th><i class="fas fa-coins me-1"></i>Collected</th>
                                <th><i class="fas fa-hand-holding-usd me-1"></i>Redistributed</th>
                                <th><i class="fas fa-chart-line me-1"></i>Profit</th>
                                <th><i class="fas fa-percentage me-1"></i>Profit %</th>
                                <th><i class="fas fa-info-circle me-1"></i>Details</th>
                            </tr>
                        </thead>
                        <tbody id="statistics-tbody">
                            <tr>
                                <td colspan="9" class="text-center text-muted">
                                    <i class="fas fa-spinner fa-spin me-2"></i>Loading statistics...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Statistics Details Modal -->
<div class="modal fade" id="statsDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Match Statistics Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="stats-details-content">
                <!-- Details will be loaded here -->
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    let currentFilters = {
        date_range: 'month',
        fixture_id: '',
        result: ''
    };

    // Load initial statistics
    loadStatistics();

    // Apply filters button
    document.getElementById('apply-filters').addEventListener('click', function() {
        currentFilters.date_range = document.getElementById('date-range').value;
        currentFilters.fixture_id = document.getElementById('fixture-filter').value.trim();
        currentFilters.result = document.getElementById('result-filter').value;

        loadStatistics();
    });

    function loadStatistics() {
        const tbody = document.getElementById('statistics-tbody');
        tbody.innerHTML = `
            <tr>
                <td colspan="9" class="text-center text-muted">
                    <i class="fas fa-spinner fa-spin me-2"></i>Loading statistics...
                </td>
            </tr>
        `;

        fetch('/api/statistics?' + new URLSearchParams(currentFilters))
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    updateOverviewCards(data.summary);
                    updateStatisticsTable(data.statistics);
                } else {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="9" class="text-center text-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i>${data.error || 'Failed to load statistics'}
                            </td>
                        </tr>
                    `;
                }
            })
            .catch(error => {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="9" class="text-center text-danger">
                            <i class="fas fa-exclamation-triangle me-2"></i>Error loading statistics: ${error.message}
                        </td>
                    </tr>
                `;
            });
    }

    function updateOverviewCards(summary) {
        document.getElementById('total-matches').textContent = summary.total_matches;
        document.getElementById('total-collected').textContent = formatCurrency(summary.total_collected);
        document.getElementById('total-redistributed').textContent = formatCurrency(summary.total_redistributed);
        document.getElementById('net-profit').textContent = formatCurrency(summary.net_profit);

        // Color code profit
        const profitElement = document.getElementById('net-profit');
        if (summary.net_profit > 0) {
            profitElement.className = 'card-title text-success';
        } else if (summary.net_profit < 0) {
            profitElement.className = 'card-title text-danger';
        } else {
            profitElement.className = 'card-title text-muted';
        }
    }

    function updateStatisticsTable(statistics) {
        const tbody = document.getElementById('statistics-tbody');
        const countBadge = document.getElementById('stats-count');

        countBadge.textContent = statistics.length;

        if (statistics.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="9" class="text-center text-muted">
                        <i class="fas fa-info-circle me-2"></i>No statistics found for the selected filters
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = statistics.map(stat => {
            const profit = stat.total_amount_collected - stat.total_redistributed;
            const profitPercent = stat.total_amount_collected > 0 ?
                ((profit / stat.total_amount_collected) * 100).toFixed(1) : '0.0';

            const profitClass = profit > 0 ? 'text-success' : profit < 0 ? 'text-danger' : 'text-muted';

            return `
                <tr>
                    <td>${new Date(stat.match_datetime).toLocaleString()}</td>
                    <td><strong>${stat.match_id}</strong></td>
                    <td><code>${stat.fixture_id}</code></td>
                    <td>
                        <span class="badge bg-${getResultBadgeClass(stat.actual_result)}">
                            ${stat.actual_result}
                        </span>
                    </td>
                    <td class="text-success">${formatCurrency(stat.total_amount_collected)}</td>
                    <td class="text-primary">${formatCurrency(stat.total_redistributed)}</td>
                    <td class="${profitClass}"><strong>${formatCurrency(profit)}</strong></td>
                    <td class="${profitClass}"><strong>${profitPercent}%</strong></td>
                    <td>
                        <button class="btn btn-sm btn-outline-info" onclick="showStatsDetails(${stat.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                    </td>
                </tr>
            `;
        }).join('');
    }

    function getResultBadgeClass(result) {
        const classes = {
            'UNDER': 'warning',
            'OVER': 'warning',
            'WIN1': 'success',
            'WIN2': 'success',
            'KO1': 'danger',
            'KO2': 'danger',
            'DRAW': 'secondary'
        };
        return classes[result] || 'primary';
    }

    function formatCurrency(amount) {
        return new Intl.NumberFormat('en-UG', {
            style: 'currency',
            currency: 'UGX',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        }).format(amount).replace('UGX', 'USh');
    }
});

// Global function for showing statistics details
function showStatsDetails(statsId) {
    const modal = new bootstrap.Modal(document.getElementById('statsDetailsModal'));
    const content = document.getElementById('stats-details-content');

    content.innerHTML = '<div class="text-center"><i class="fas fa-spinner fa-spin"></i> Loading details...</div>';
    modal.show();

    fetch(`/api/statistics/${statsId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const stat = data.statistics;
                const breakdown = JSON.parse(stat.result_breakdown || '{}');

                content.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>Match Information</h6>
                            <table class="table table-sm">
                                <tr><td><strong>Match ID:</strong></td><td>${stat.match_id}</td></tr>
                                <tr><td><strong>Fixture ID:</strong></td><td><code>${stat.fixture_id}</code></td></tr>
                                <tr><td><strong>Date/Time:</strong></td><td>${new Date(stat.match_datetime).toLocaleString()}</td></tr>
                                <tr><td><strong>Actual Result:</strong></td><td><span class="badge bg-primary">${stat.actual_result}</span></td></tr>
                                <tr><td><strong>Extraction Result:</strong></td><td>${stat.extraction_result || 'N/A'}</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>Financial Summary</h6>
                            <table class="table table-sm">
                                <tr><td><strong>Total Bets:</strong></td><td>${stat.total_bets}</td></tr>
                                <tr><td><strong>Amount Collected:</strong></td><td class="text-success">${formatCurrency(stat.total_amount_collected)}</td></tr>
                                <tr><td><strong>Amount Redistributed:</strong></td><td class="text-primary">${formatCurrency(stat.total_redistributed)}</td></tr>
                                <tr><td><strong>Net Profit:</strong></td><td class="${stat.total_amount_collected - stat.total_redistributed > 0 ? 'text-success' : 'text-danger'}"><strong>${formatCurrency(stat.total_amount_collected - stat.total_redistributed)}</strong></td></tr>
                            </table>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-12">
                            <h6>UNDER/OVER Breakdown</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-body text-center">
                                            <h5 class="text-warning">${stat.under_bets}</h5>
                                            <p class="mb-1">UNDER Bets</p>
                                            <small class="text-muted">${formatCurrency(stat.under_amount)}</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="card">
                                        <div class="card-body text-center">
                                            <h5 class="text-warning">${stat.over_bets}</h5>
                                            <p class="mb-1">OVER Bets</p>
                                            <small class="text-muted">${formatCurrency(stat.over_amount)}</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    ${stat.cap_applied ? `
                    <div class="row mt-3">
                        <div class="col-12">
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <strong>CAP Applied:</strong> Redistribution was capped at ${stat.cap_percentage}%
                            </div>
                        </div>
                    </div>
                    ` : ''}
                `;
            } else {
                content.innerHTML = `<div class="alert alert-danger">${data.error || 'Failed to load details'}</div>`;
            }
        })
        .catch(error => {
            content.innerHTML = `<div class="alert alert-danger">Error loading details: ${error.message}</div>`;
        });
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('en-UG', {
        style: 'currency',
        currency: 'UGX',
        minimumFractionDigits: 0,
        maximumFractionDigits: 0
    }).format(amount).replace('UGX', 'USh');
}
</script>
{% endblock %}