{% 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>Reports
            <small class="text-muted">Welcome, {{ current_user.username }}</small>
        </h1>
    </div>
</div>

<!-- Back 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-chart-line me-1"></i>Daily Reports
                </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='/'">
                            <i class="fas fa-arrow-left me-2"></i>Back to Dashboard
                        </button>
                    </div>
                    <div class="col-md-6 mb-3 text-end">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-calendar"></i>
                            </span>
                            <input type="date" class="form-control" id="report-date-picker"
                                   value="{{ today_date }}" max="{{ today_date }}">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Daily Summary -->
<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-tachometer-alt me-2"></i>Daily Summary
                    <span class="badge bg-info ms-2" id="summary-date">{{ today_date }}</span>
                    <button class="btn btn-sm btn-success ms-2" onclick="downloadReport()">
                        <i class="fas fa-download me-1"></i>Download Excel
                    </button>
                </h5>
            </div>
            <div class="card-body">
                <div id="daily-summary-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading daily summary...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Match Reports 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-list-ul me-2"></i>Match Reports
                    <span class="badge bg-info ms-2" id="matches-count">0</span>
                </h5>
            </div>
            <div class="card-body">
                <div id="match-reports-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading match reports...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Match Details Modal -->
<div class="modal fade" id="matchDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-info-circle me-2"></i>Match Details - <span id="modal-match-title"></span>
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="match-details-container">
                    <div class="text-center text-muted">
                        <i class="fas fa-spinner fa-spin me-2"></i>Loading match details...
                    </div>
                </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>Close
                </button>
            </div>
        </div>
    </div>
</div>

{% 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 reports on page load
    loadReports();

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

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

    const dateInput = document.getElementById('report-date-picker');
    const selectedDate = dateInput.value;

    // Update summary date badge
    document.getElementById('summary-date').textContent = selectedDate;

    // Load daily summary
    loadDailySummary(selectedDate);

    // Load match reports
    loadMatchReports(selectedDate);
}

// Function to load daily summary
function loadDailySummary(date) {
    const container = document.getElementById('daily-summary-container');

    console.log('📡 Making API request to /api/reports/daily-summary for date:', date);

    fetch(`/api/reports/daily-summary?date=${date}`)
        .then(response => {
            console.log('📡 Daily summary response status:', response.status);
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('📦 Daily summary response data:', data);

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

// Function to update daily summary display
function updateDailySummary(summary) {
    const container = document.getElementById('daily-summary-container');

    const summaryHTML = `
        <div class="row text-center">
            <div class="col-md-3 mb-3">
                <div class="card h-100 border-success">
                    <div class="card-body">
                        <h5 class="card-title text-success">
                            <i class="fas fa-arrow-up me-2"></i>Payin
                        </h5>
                        <h3 class="currency-amount text-success" data-amount="${summary.total_payin}">${formatCurrency(summary.total_payin)}</h3>
                        <small class="text-muted">Total amount received</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card h-100 border-danger">
                    <div class="card-body">
                        <h5 class="card-title text-danger">
                            <i class="fas fa-arrow-down me-2"></i>Payout
                        </h5>
                        <h3 class="currency-amount text-danger" data-amount="${summary.total_payout}">${formatCurrency(summary.total_payout)}</h3>
                        <small class="text-muted">Total amount paid out</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card h-100 ${summary.net_profit >= 0 ? 'border-success' : 'border-danger'}">
                    <div class="card-body">
                        <h5 class="card-title ${summary.net_profit >= 0 ? 'text-success' : 'text-danger'}">
                            <i class="fas fa-${summary.net_profit >= 0 ? 'plus' : 'minus'} me-2"></i>Net Profit
                        </h5>
                        <h3 class="currency-amount ${summary.net_profit >= 0 ? 'text-success' : 'text-danger'}" data-amount="${summary.net_profit}">${formatCurrency(summary.net_profit)}</h3>
                        <small class="text-muted">Payin minus payout</small>
                    </div>
                </div>
            </div>
            <div class="col-md-3 mb-3">
                <div class="card h-100 border-info">
                    <div class="card-body">
                        <h5 class="card-title text-info">
                            <i class="fas fa-hashtag me-2"></i>Total Bets
                        </h5>
                        <h3 class="text-info">${summary.total_bets}</h3>
                        <small class="text-muted">Number of bets placed</small>
                    </div>
                </div>
            </div>
        </div>
    `;

    container.innerHTML = summaryHTML;
}

// Function to load match reports
function loadMatchReports(date) {
    const container = document.getElementById('match-reports-container');
    const countBadge = document.getElementById('matches-count');

    console.log('📡 Making API request to /api/reports/match-reports for date:', date);

    fetch(`/api/reports/match-reports?date=${date}`)
        .then(response => {
            console.log('📡 Match reports response status:', response.status);
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            console.log('📦 Match reports 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';

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

// Function to update match reports table
function updateMatchReportsTable(data, container) {
    if (data.total === 0) {
        container.innerHTML = `
            <div class="text-center text-muted">
                <i class="fas fa-info-circle me-2"></i>No matches found for the selected date
            </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>Match #</th>
                        <th><i class="fas fa-users me-1"></i>Fighters</th>
                        <th><i class="fas fa-map-marker-alt me-1"></i>Venue</th>
                        <th><i class="fas fa-hashtag me-1"></i>Bets Count</th>
                        <th><i class="fas fa-arrow-up me-1"></i>Payin</th>
                        <th><i class="fas fa-arrow-down me-1"></i>Payout</th>
                        <th><i class="fas fa-chart-line me-1"></i>Net</th>
                        <th><i class="fas fa-cogs me-1"></i>Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;

    data.matches.forEach(match => {
        const payin = parseFloat(match.payin || 0);
        const payout = parseFloat(match.payout || 0);
        const net = parseFloat(match.net || 0);

        tableHTML += `
            <tr>
                <td><strong>${match.match_number}</strong></td>
                <td>
                    <div class="small">
                        <strong>${match.fighter1_township}</strong><br>
                        <span class="text-muted">vs</span><br>
                        <strong>${match.fighter2_township}</strong>
                    </div>
                </td>
                <td><small>${match.venue_kampala_township}</small></td>
                <td><span class="badge bg-primary">${match.bets_count}</span></td>
                <td><strong class="currency-amount text-success" data-amount="${payin}">${formatCurrency(payin)}</strong></td>
                <td><strong class="currency-amount text-danger" data-amount="${payout}">${formatCurrency(payout)}</strong></td>
                <td><strong class="currency-amount ${net >= 0 ? 'text-success' : 'text-danger'}" data-amount="${net}">${formatCurrency(net)}</strong></td>
                <td>
                    <button class="btn btn-sm btn-outline-primary"
                            onclick="showMatchDetails('${match.match_id}', '${data.date}')"
                            title="View Detailed Bets">
                        <i class="fas fa-eye"></i> Details
                    </button>
                </td>
            </tr>
        `;
    });

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

    container.innerHTML = tableHTML;
}

// Function to show match details modal
function showMatchDetails(matchId, date) {
    const modal = new bootstrap.Modal(document.getElementById('matchDetailsModal'));
    const container = document.getElementById('match-details-container');
    const titleElement = document.getElementById('modal-match-title');

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

    // Load match details
    fetch(`/api/reports/match-details?match_id=${matchId}&date=${date}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('API request failed: ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                updateMatchDetailsModal(data, container, titleElement);
            } else {
                container.innerHTML = `
                    <div class="text-center text-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>Error loading match details: ${data.error || 'Unknown error'}
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('❌ Error loading match details:', error);
            container.innerHTML = `
                <div class="text-center text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>Error loading match details: ${error.message}
                </div>
            `;
        });

    modal.show();
}

// Function to update match details modal
function updateMatchDetailsModal(data, container, titleElement) {
    // Update title
    if (data.match) {
        titleElement.textContent = `Match #${data.match.match_number}: ${data.match.fighter1_township} vs ${data.match.fighter2_township}`;
    } else {
        titleElement.textContent = `Match Details`;
    }

    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 this match on the selected date
            </div>
        `;
        return;
    }

    let tableHTML = `
        <div class="table-responsive">
            <table class="table table-striped table-sm">
                <thead class="table-dark">
                    <tr>
                        <th><i class="fas fa-clock me-1"></i>Time</th>
                        <th><i class="fas fa-ticket-alt me-1"></i>Bet ID</th>
                        <th><i class="fas fa-target me-1"></i>Outcome</th>
                        <th><i class="fas fa-dollar-sign me-1"></i>Amount</th>
                        <th><i class="fas fa-chart-line me-1"></i>Result</th>
                        <th><i class="fas fa-trophy me-1"></i>Potential Win</th>
                    </tr>
                </thead>
                <tbody>
    `;

    data.bets.forEach(bet => {
        const amount = parseFloat(bet.amount || 0);
        const potentialWin = parseFloat(bet.potential_winning || 0);
        const betTime = new Date(bet.bet_datetime).toLocaleString();

        let resultBadge = '';
        if (bet.result === 'won') {
            resultBadge = '<span class="badge bg-success"><i class="fas fa-trophy me-1"></i>Won</span>';
        } else if (bet.result === 'lost') {
            resultBadge = '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Lost</span>';
        } else {
            resultBadge = '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
        }

        tableHTML += `
            <tr>
                <td><small>${betTime}</small></td>
                <td><small>${bet.bet_id.substring(0, 8)}...</small></td>
                <td><strong>${bet.outcome}</strong></td>
                <td><strong class="currency-amount" data-amount="${amount}">${formatCurrency(amount)}</strong></td>
                <td>${resultBadge}</td>
                <td><strong class="currency-amount text-success" data-amount="${potentialWin}">${formatCurrency(potentialWin)}</strong></td>
            </tr>
        `;
    });

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

    container.innerHTML = tableHTML;
}

// Function to download Excel report
function downloadReport() {
    const dateInput = document.getElementById('report-date-picker');
    const selectedDate = dateInput.value;

    if (!selectedDate) {
        alert('Please select a date for the report');
        return;
    }

    // Create download link
    const downloadUrl = `/api/reports/download-excel?date=${selectedDate}`;
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = `report_${selectedDate}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
</script>
{% endblock %}