@extends('layouts.admin')

@section('title', 'Custom 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">Custom Reports</h1>
            <p class="text-xs sm:text-sm text-gray-600 mt-1">Create ad-hoc reports across invoices, payments, parcels, and expenses</p>
        </div>
        <a href="{{ url('finance/reports.export') }}" class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-semibold hover:bg-blue-700 transition">Go to Export Center</a>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-lg shadow-md p-3 sm:p-4 mb-4">
        <div class="grid grid-cols-1 md:grid-cols-5 gap-4 items-end">
            <div>
                <label class="block text-xs text-gray-600 mb-1">Entity</label>
                <select id="entitySelect" class="border rounded-md px-3 py-2 w-full text-sm">
                    <option value="invoices">Invoices</option>
                    <option value="payments">Payments</option>
                    <option value="parcels">Parcels</option>
                    <option value="expenses">Expenses</option>
                </select>
            </div>
            <div>
                <label class="block text-xs text-gray-600 mb-1">Limit</label>
                <input type="number" id="limitInput" class="border rounded-md px-3 py-2 w-full text-sm" min="5" max="100" value="10" />
            </div>
            <div class="md:col-span-2">
                <p class="text-[11px] text-gray-500">Choose the entity and number of records to fetch.</p>
            </div>
            <div class="flex md:justify-end">
                <button id="applyBtn" class="bg-green-600 text-white px-3 py-2 rounded-md hover:bg-green-700 text-sm">Apply</button>
                <button id="resetBtn" class="ml-2 bg-gray-100 text-gray-800 px-3 py-2 rounded-md hover:bg-gray-200 text-sm">Reset</button>
            </div>
        </div>
    </div>

    <!-- Results Table -->
    <div class="bg-white rounded-lg border border-gray-200">
        <div class="p-4 border-b border-gray-200">
            <h2 id="tableTitle" class="text-sm font-semibold text-gray-800">Items</h2>
            <p class="text-xs text-gray-500">Showing latest items for the selected entity</p>
        </div>
        <div class="p-4 overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead>
                    <tr id="tableHead" class="text-left text-xs text-gray-500"></tr>
                </thead>
                <tbody id="tableBody"></tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const entitySelect = document.getElementById('entitySelect');
    const limitInput = document.getElementById('limitInput');
    const applyBtn = document.getElementById('applyBtn');
    const resetBtn = document.getElementById('resetBtn');
    const tableTitle = document.getElementById('tableTitle');
    const tableHead = document.getElementById('tableHead');
    const tableBody = document.getElementById('tableBody');

    const dataUrl = `{{ url('finance/reports.custom.data') }}`;

    function setHeaders(entity) {
        let headers = [];
        switch(entity) {
            case 'invoices':
                headers = ['ID', 'Seller', 'Status', 'Total', 'Created'];
                break;
            case 'payments':
                headers = ['ID', 'Seller', 'Amount', 'Status', 'Created'];
                break;
            case 'parcels':
                headers = ['Tracking', 'Seller', 'Rider', 'Status', 'COD', 'Created'];
                break;
            case 'expenses':
            default:
                headers = ['ID', 'Category', 'Amount', 'Status', 'Created'];
                break;
        }
        tableHead.innerHTML = headers.map(h => `<th class="py-2 pr-4">${h}</th>`).join('');
        tableTitle.textContent = `${entity.charAt(0).toUpperCase() + entity.slice(1)} Items`;
    }

    function renderRows(entity, items) {
        const rows = items.map(item => {
            switch(entity) {
                case 'invoices':
                    return `<tr>
                        <td class="py-2 pr-4 text-gray-700">${item.id}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.seller_id ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.status ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-900 font-medium">${Number(item.total_amount ?? 0).toFixed(2)}</td>
                        <td class="py-2 pr-4 text-gray-500">${new Date(item.created_at).toLocaleString()}</td>
                    </tr>`;
                case 'payments':
                    return `<tr>
                        <td class="py-2 pr-4 text-gray-700">${item.id}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.seller_id ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-900 font-medium">${Number(item.amount ?? 0).toFixed(2)}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.status ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-500">${new Date(item.created_at).toLocaleString()}</td>
                    </tr>`;
                case 'parcels':
                    return `<tr>
                        <td class="py-2 pr-4 text-gray-700">${item.tracking_id ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.seller_id ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.assigned_rider_id ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.status ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-900 font-medium">${Number(item.cod_amount ?? 0).toFixed(2)}</td>
                        <td class="py-2 pr-4 text-gray-500">${new Date(item.created_at).toLocaleString()}</td>
                    </tr>`;
                case 'expenses':
                default:
                    return `<tr>
                        <td class="py-2 pr-4 text-gray-700">${item.id}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.category ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-900 font-medium">${Number(item.amount ?? 0).toFixed(2)}</td>
                        <td class="py-2 pr-4 text-gray-700">${item.status ?? '-'}</td>
                        <td class="py-2 pr-4 text-gray-500">${new Date(item.created_at).toLocaleString()}</td>
                    </tr>`;
            }
        });
        tableBody.innerHTML = rows.length ? rows.join('') : `<tr><td class="py-2 pr-4 text-gray-500">No items found</td></tr>`;
    }

    async function loadData() {
        const entity = entitySelect.value;
        const limit = parseInt(limitInput.value || '10', 10);
        const params = new URLSearchParams({ entity, limit });
        const url = `${dataUrl}?${params.toString()}`;
        try {
            const res = await fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const payload = await res.json();
            setHeaders(entity);
            renderRows(entity, payload.items || []);
        } catch (error) {
            console.error('Failed to load custom data', error);
        }
    }

    applyBtn.addEventListener('click', loadData);
    resetBtn.addEventListener('click', () => {
        entitySelect.value = 'invoices';
        limitInput.value = 10;
        loadData();
    });

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



