@extends('layouts.admin')

@section('title', 'Operational Reports')

@section('content')
<div class="container mx-auto px-2 sm:px-4 lg:px-6 py-3 sm:py-4 lg:py-6">
    <div class="mb-6 flex items-center justify-between">
        <div>
            <h1 class="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900">Operational Reports</h1>
            <p class="text-xs sm:text-sm text-gray-600 mt-1">Monitor parcel operations and delivery performance</p>
        </div>
        <div>
            <a href="{{ route('admin.finance.reports.export') }}" class="inline-flex items-center px-3 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md">
                Export Center
            </a>
        </div>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-4 mb-6">
        <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4">
            <div>
                <label for="startDate" class="block text-xs font-medium text-gray-700 mb-1">Start Date</label>
                <input type="date" id="startDate" class="w-full border-gray-300 rounded-md text-sm" />
            </div>
            <div>
                <label for="endDate" class="block text-xs font-medium text-gray-700 mb-1">End Date</label>
                <input type="date" id="endDate" class="w-full border-gray-300 rounded-md text-sm" />
            </div>
            <div class="flex items-end gap-2 sm:gap-3">
                <button id="applyFilters" class="px-3 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md">Apply Filters</button>
                <button id="resetFilters" class="px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md">Reset</button>
            </div>
        </div>
    </div>

    <!-- Metric Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
        <div class="bg-white border border-gray-200 rounded-lg p-4">
            <p class="text-xs text-gray-500">Total Parcels</p>
            <p id="totalParcelsCount" class="mt-1 text-2xl font-semibold text-gray-900">0</p>
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4">
            <p class="text-xs text-gray-500">Delivered</p>
            <p id="deliveredCount" class="mt-1 text-2xl font-semibold text-emerald-700">0</p>
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4">
            <p class="text-xs text-gray-500">In Transit</p>
            <p id="inTransitCount" class="mt-1 text-2xl font-semibold text-blue-700">0</p>
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4">
            <p class="text-xs text-gray-500">Pending</p>
            <p id="pendingCount" class="mt-1 text-2xl font-semibold text-yellow-700">0</p>
        </div>
        <div class="bg-white border border-gray-200 rounded-lg p-4">
            <p class="text-xs text-gray-500">Returned</p>
            <p id="returnedCount" class="mt-1 text-2xl font-semibold text-red-700">0</p>
        </div>
    </div>

    <!-- Daily Deliveries -->
    <div class="bg-white rounded-lg border border-gray-200">
        <div class="p-4 border-b border-gray-200">
            <h2 class="text-sm font-semibold text-gray-800">Daily Deliveries (last 14 days)</h2>
            <p class="text-xs text-gray-500">Counts derived from `updated_at` for parcels with status Delivered</p>
        </div>
        <div class="p-4 overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead>
                    <tr class="text-left text-xs text-gray-500">
                        <th class="py-2 pr-4">Date</th>
                        <th class="py-2">Deliveries</th>
                    </tr>
                </thead>
                <tbody id="deliveriesTableBody">
                    <tr>
                        <td class="py-2 pr-4 text-gray-600">—</td>
                        <td class="py-2 text-gray-600">—</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const startInput = document.getElementById('startDate');
    const endInput = document.getElementById('endDate');
    const applyBtn = document.getElementById('applyFilters');
    const resetBtn = document.getElementById('resetFilters');

    const totalParcelsEl = document.getElementById('totalParcelsCount');
    const deliveredEl = document.getElementById('deliveredCount');
    const inTransitEl = document.getElementById('inTransitCount');
    const pendingEl = document.getElementById('pendingCount');
    const returnedEl = document.getElementById('returnedCount');
    const deliveriesBody = document.getElementById('deliveriesTableBody');

    const dataUrl = `{{ route('admin.finance.reports.operational.data') }}`;

    function formatDate(dateStr) {
        try {
            const d = new Date(dateStr);
            return d.toLocaleDateString();
        } catch(e) {
            return dateStr;
        }
    }

    async function loadOperationalData() {
        const params = new URLSearchParams();
        if (startInput.value) params.set('start_date', startInput.value);
        if (endInput.value) params.set('end_date', endInput.value);

        const url = params.toString() ? `${dataUrl}?${params.toString()}` : dataUrl;
        try {
            const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await res.json();

            totalParcelsEl.textContent = data.total_parcels ?? 0;
            deliveredEl.textContent = data.delivered ?? 0;
            inTransitEl.textContent = data.in_transit ?? 0;
            pendingEl.textContent = data.pending ?? 0;
            returnedEl.textContent = data.returned ?? 0;

            // Daily deliveries table
            const rows = (data.daily_deliveries || []).map(item => {
                const day = item.day || item.date || item.updated_at || '';
                const count = item.count ?? 0;
                return `<tr>
                    <td class="py-2 pr-4 text-gray-700">${formatDate(day)}</td>
                    <td class="py-2 text-gray-900 font-medium">${count}</td>
                </tr>`;
            });
            deliveriesBody.innerHTML = rows.length ? rows.join('') : '<tr><td class="py-2 pr-4 text-gray-500">No data</td><td class="py-2 text-gray-500">0</td></tr>';
        } catch (error) {
            console.error('Failed to load operational data', error);
        }
    }

    applyBtn.addEventListener('click', loadOperationalData);
    resetBtn.addEventListener('click', () => {
        startInput.value = '';
        endInput.value = '';
        loadOperationalData();
    });

    // Initial load
    loadOperationalData();
});
</script>
@endsection


