@extends('layouts.admin')

@section('content')
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Revenue Report</h5>
                    <button type="button" class="btn btn-danger btn-sm" onclick="window.print()">
                        <i class="fas fa-print me-1"></i> Print
                    </button>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4 no-print">
                        <div class="col-md-5">
                            <label class="form-label">Start Date</label>
                            <input type="date" id="start_date" class="form-control">
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">End Date</label>
                            <input type="date" id="end_date" class="form-control">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" id="filter_btn" class="btn btn-primary w-100">Filter</button>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card bg-success text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Revenue</h6>
                                    <h2 class="mb-0" id="total_revenue">$0.00</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Profit</h6>
                                    <h2 class="mb-0" id="total_profit">$0.00</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-warning text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Profit Margin</h6>
                                    <h2 class="mb-0" id="profit_margin">0%</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card bg-primary text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Orders</h6>
                                    <h2 class="mb-0" id="total_orders">0</h2>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-4">
                        <div class="card-body">
                            <canvas id="revenueChart" height="300"></canvas>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-light">
                                <tr>
                                    <th>Date</th>
                                    <th class="text-end">Revenue</th>
                                    <th class="text-end">Cost</th>
                                    <th class="text-end">Profit</th>
                                    <th class="text-end">Orders</th>
                                    <th class="text-end">Margin</th>
                                </tr>
                            </thead>
                            <tbody id="revenue_data">
                                <tr>
                                    <td colspan="6" class="text-center">Select date range to view revenue data</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Then Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    let revenueChart = null;

    function initializeDates() {
        const today = new Date();
        const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        
        document.getElementById('start_date').value = firstDay.toISOString().split('T')[0];
        document.getElementById('end_date').value = lastDay.toISOString().split('T')[0];
        
        loadRevenueData();
    }

    function formatCurrency(amount) {
        return '$' + parseFloat(amount || 0).toFixed(2);
    }

    function loadRevenueData() {
        const startDate = document.getElementById('start_date').value;
        const endDate = document.getElementById('end_date').value;

        if (!startDate || !endDate) {
            alert('Please select both start and end dates');
            return;
        }

        $.ajax({
            url: '{{ route("admin.reports.revenue.data") }}',
            method: 'GET',
            data: { start_date: startDate, end_date: endDate },
            beforeSend: function() {
                document.getElementById('filter_btn').innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Loading...';
                document.getElementById('revenue_data').innerHTML = '<tr><td colspan="6" class="text-center">Loading data...</td></tr>';
            },
            success: function(response) {
                let html = '';
                let totalRevenue = 0;
                let totalProfit = 0;
                let totalOrders = response.length;

                response.forEach(data => {
                    const revenue = parseFloat(data.revenue || 0);
                    const profit = parseFloat(data.profit || 0);
                    const margin = revenue > 0 ? (profit / revenue * 100) : 0;
                    
                    totalRevenue += revenue;
                    totalProfit += profit;

                    html += `
                        <tr>
                            <td>${data.date}</td>
                            <td class="text-end">${formatCurrency(revenue)}</td>
                            <td class="text-end">${formatCurrency(revenue - profit)}</td>
                            <td class="text-end">${formatCurrency(profit)}</td>
                            <td class="text-end">1</td>
                            <td class="text-end">${margin.toFixed(1)}%</td>
                        </tr>
                    `;
                });

                // Update table data
                document.getElementById('revenue_data').innerHTML = html || '<tr><td colspan="6" class="text-center">No revenue data found</td></tr>';

                // Update summary cards
                document.getElementById('total_revenue').textContent = formatCurrency(totalRevenue);
                document.getElementById('total_profit').textContent = formatCurrency(totalProfit);
                document.getElementById('profit_margin').textContent = totalRevenue > 0 ? 
                    (totalProfit / totalRevenue * 100).toFixed(1) + '%' : '0%';
                document.getElementById('total_orders').textContent = totalOrders;

                // Update chart
                updateChart(response);
            },
            error: function(xhr, status, error) {
                let errorMessage = 'Error loading data';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage += ': ' + xhr.responseJSON.message;
                }
                alert(errorMessage);
                document.getElementById('revenue_data').innerHTML = '<tr><td colspan="6" class="text-center text-danger">Error loading data</td></tr>';
            },
            complete: function() {
                document.getElementById('filter_btn').innerHTML = 'Filter';
            }
        });
    }

    function updateChart(data) {
        const ctx = document.getElementById('revenueChart').getContext('2d');
        
        if (revenueChart) {
            revenueChart.destroy();
        }

        revenueChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(item => item.date),
                datasets: [{
                    label: 'Revenue',
                    data: data.map(item => item.revenue),
                    borderColor: 'rgb(40, 167, 69)',
                    tension: 0.1
                }, {
                    label: 'Profit',
                    data: data.map(item => item.profit),
                    borderColor: 'rgb(23, 162, 184)',
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function(value) {
                                return '$' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });
    }

    // Event Handlers
    document.getElementById('filter_btn').addEventListener('click', loadRevenueData);

    // Initialize the report
    initializeDates();
});
</script>
@endsection