@extends('layouts.master')

@section('content')
<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">Home</h1>
            <div class="small text-muted">{{ $rangeLabel }} ({{ $fromDate }} to {{ $toDate }})</div>
        </div>

        <form method="GET" action="{{ route('home') }}" class="form-inline align-items-end flex-wrap no-print">
            <div class="mr-2 mb-2">
                <label class="small text-muted mb-1 d-block">Date Range</label>
                <select name="range" id="rangeSelect" class="form-control form-control-sm">
                    <option value="today"       @selected($range === 'today')>Today</option>
                    <option value="this_week"   @selected($range === 'this_week')>This Week</option>
                    <option value="this_month"  @selected($range === 'this_month')>This Month</option>
                    <option value="this_quarter"@selected($range === 'this_quarter')>This Quarter</option>
                    <option value="this_year"   @selected($range === 'this_year')>This Year</option>
                    <option value="custom"      @selected($range === 'custom')>Custom</option>
                </select>
            </div>

            <div id="customDates" class="d-flex align-items-end" style="{{ $range === 'custom' ? '' : 'display:none;' }}">
                <div class="mr-2 mb-2">
                    <label class="small text-muted mb-1 d-block">From</label>
                    <input type="date" name="from_date" value="{{ request('from_date', $fromDate) }}" class="form-control form-control-sm">
                </div>
                <div class="mr-2 mb-2">
                    <label class="small text-muted mb-1 d-block">To</label>
                    <input type="date" name="to_date" value="{{ request('to_date', $toDate) }}" class="form-control form-control-sm">
                </div>
            </div>

            <button class="btn btn-primary btn-sm mb-2">Apply</button>
        </form>
    </div>

    {{-- CASH & LIQUIDITY (above the fold) --}}
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Cash & Bank Balance</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($cashAndBankBalance, 2) }}</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Net Cash Position</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($netCashPosition, 2) }}</div>
                    <div class="small text-muted">Cash less supplier payments due (7 days)</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Cash Flow This Month</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($cashFlowDeltaThisMonth, 2) }}</div>
                    <div class="small text-muted">In: {{ number_format($cashInflowsThisMonth, 2) }} &nbsp; Out: {{ number_format($cashOutflowsThisMonth, 2) }}</div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Net Tax Liability (Range)</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($netTaxLiability, 2) }}</div>
                    <div class="small text-muted">Collected: {{ number_format($vatCollected, 2) }} &nbsp; Paid: {{ number_format($vatPaid, 2) }}</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-xl-8 col-lg-7">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Cash Flow Trend (Last 12 Months)</h6>
                </div>
                <div class="card-body">
                    <div class="chart-area">
                        <canvas id="cashFlowTrendChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-lg-5">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Quick Actions</h6>
                </div>
                <div class="card-body">
                    <div class="d-flex flex-column">
                        <a class="btn btn-primary btn-sm mb-2" href="{{ route('customer.invoice') }}">New Invoice</a>
                        <a class="btn btn-primary btn-sm mb-2" href="{{ route('receipts.create') }}">New Receipt</a>
                        <a class="btn btn-primary btn-sm mb-2" href="{{ route('supplier.purchase-order') }}">New Purchase Order</a>
                        <a class="btn btn-primary btn-sm" href="{{ route('customer.quotation') }}">New Quotation</a>
                    </div>
                </div>
            </div>
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Bank Account Breakdown</h6>
                </div>
                <div class="card-body">
                    <div class="chart-pie pt-2 pb-2">
                        <canvas id="bankBreakdownChart"></canvas>
                    </div>
                    <div class="small text-muted">Balances as at {{ $toDate }}</div>
                </div>
            </div>
        </div>
    </div>

    {{-- RECEIVABLES + PAYABLES --}}
    <div class="row">
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Receivables</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Outstanding</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($totalOutstandingReceivables, 2) }}</div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Overdue</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($overdueReceivables, 2) }}</div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Collected This Month</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($collectedThisMonth, 2) }}</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-7">
                            <div class="chart-bar" style="height:260px;">
                                <canvas id="arAgeingChart"></canvas>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <div class="chart-bar" style="height:260px;">
                                <canvas id="topCustomersChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Payables</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Outstanding</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($totalOutstandingPayables, 2) }}</div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Overdue</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($overduePayables, 2) }}</div>
                        </div>
                        <div class="col-md-4 mb-3">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Paid This Month</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($paidToSuppliersThisMonth, 2) }}</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-7">
                            <div class="chart-bar" style="height:260px;">
                                <canvas id="apAgeingChart"></canvas>
                            </div>
                        </div>
                        <div class="col-md-5">
                            <div class="chart-bar" style="height:260px;">
                                <canvas id="topSuppliersChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- REVENUE & EXPENSES --}}
    <div class="row">
        <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Revenue & Expenses</h6>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-xl-3 col-md-6 mb-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Revenue (Range)</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($revenueThisRange, 2) }}</div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Expenses (Range)</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($expensesThisRange, 2) }}</div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Gross Profit (Range)</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($grossProfitThisRange, 2) }}</div>
                        </div>
                        <div class="col-xl-3 col-md-6 mb-2">
                            <div class="text-xs font-weight-bold {{ $netProfitThisRange >= 0 ? 'text-success' : 'text-danger' }} text-uppercase mb-1">Net Profit / (Loss)</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($netProfitThisRange, 2) }}</div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-8">
                            <div class="chart-area">
                                <canvas id="revenueExpenseChart"></canvas>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="chart-pie pt-2 pb-2">
                                <canvas id="expenseBreakdownChart"></canvas>
                            </div>
                            <div class="small text-muted text-center">Expense Breakdown (Top Accounts)</div>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-lg-6">
                            <div class="chart-area">
                                <canvas id="revenueTrendChart"></canvas>
                            </div>
                        </div>
                        <div class="col-lg-6">
                            <div class="chart-area">
                                <canvas id="profitMarginChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- DOCUMENT / TRANSACTION PIPELINE + ALERTS --}}
    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Document Pipeline</h6>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Open Quotations</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($openQuotations) }}</div>
                            <div class="small text-muted">Value: {{ number_format($openQuotationsValue, 2) }}</div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Open Sales Orders</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($openSalesOrders) }}</div>
                            <div class="small text-muted">Value: {{ number_format($openSalesOrdersValue, 2) }}</div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Unprocessed Invoices</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($unprocessedInvoicesCount) }}</div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending POs</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($pendingPurchaseOrders) }}</div>
                        </div>
                        <div class="col-md-2 mb-3">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending GRVs</div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">{{ number_format($pendingGrvs) }}</div>
                        </div>
                    </div>

                    <div class="mt-3">
                        <div class="small text-muted mb-2">Funnel: Quotation → Sales Order → Invoice → Receipt</div>
                        @php
                            $maxFunnel = max(1, max($funnel));
                        @endphp
                        @foreach($funnel as $label => $count)
                            <div class="d-flex align-items-center mb-2">
                                <div class="me-2" style="width:110px;">{{ $label }}</div>
                                <div class="progress flex-grow-1 me-2" style="height:12px;">
                                    <div class="progress-bar bg-primary" role="progressbar" style="width: {{ ($count / $maxFunnel) * 100 }}%"></div>
                                </div>
                                <div class="text-muted small" style="width:50px; text-align:right;">{{ $count }}</div>
                            </div>
                        @endforeach
                    </div>

                    <hr>

                    <h6 class="font-weight-bold text-primary mb-2">Recent Documents</h6>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Type</th>
                                    <th>Reference</th>
                                    <th>Customer / Supplier</th>
                                    <th>Date</th>
                                    <th>Status</th>
                                    <th class="text-end">Total</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($recentDocuments as $doc)
                                    <tr>
                                        <td>{{ $doc['type'] }}</td>
                                        <td>{{ $doc['document_number'] }}</td>
                                        <td>
                                            @if($doc['side'] === 'customer')
                                                {{ $customerAccountNames[$doc['party_id']] ?? ('Customer #'.$doc['party_id']) }}
                                            @else
                                                {{ $supplierAccountNames[$doc['party_id']] ?? ('Supplier #'.$doc['party_id']) }}
                                            @endif
                                        </td>
                                        <td>{{ $doc['document_date'] }}</td>
                                        <td>{{ $doc['status'] }}</td>
                                        <td class="text-end">{{ number_format((float) $doc['inclusive_total'], 2) }}</td>
                                    </tr>
                                @empty
                                    <tr><td colspan="6">No recent documents found.</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Alerts</h6>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="font-weight-bold text-gray-800 mb-2">Invoices overdue (30+ days)</div>
                        @if($overdueInvoices30->isEmpty())
                            <div class="text-muted small">No overdue invoices.</div>
                        @else
                            <ul class="mb-0 ps-3">
                                @foreach($overdueInvoices30 as $inv)
                                    <li class="small">
                                        {{ $customerAccountNames[$inv['customer_account_id']] ?? ('Customer #'.$inv['customer_account_id']) }}
                                        — {{ $inv['document_number'] }} ({{ number_format($inv['outstanding'], 2) }})
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>

                    <div class="mb-3">
                        <div class="font-weight-bold text-gray-800 mb-2">Quotations expiring (7 days)</div>
                        @if($quotationsExpiring->isEmpty())
                            <div class="text-muted small">No expiring quotations.</div>
                        @else
                            <ul class="mb-0 ps-3">
                                @foreach($quotationsExpiring as $q)
                                    <li class="small">
                                        {{ $q->document_number }} — {{ $customerAccountNames[$q->customer_account_id] ?? ('Customer #'.$q->customer_account_id) }}
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>

                    <div>
                        <div class="font-weight-bold text-gray-800 mb-2">Supplier payments due (7 days)</div>
                        @if($supplierPaymentsDue->isEmpty())
                            <div class="text-muted small">No supplier payments due.</div>
                        @else
                            <ul class="mb-0 ps-3">
                                @foreach($supplierPaymentsDue as $p)
                                    <li class="small">
                                        {{ $supplierAccountNames[$p['supplier_account_id']] ?? ('Supplier #'.$p['supplier_account_id']) }}
                                        — {{ $p['document_number'] }} ({{ number_format($p['outstanding'], 2) }})
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>
                </div>
            </div>

            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Activity</h6>
                </div>
                <div class="card-body">
                    @if($activityLog->isEmpty())
                        <div class="text-muted small">No activity yet.</div>
                    @else
                        <ul class="mb-0 ps-3">
                            @foreach($activityLog as $a)
                                <li class="small mb-1">
                                    <span class="text-muted">{{ \Carbon\Carbon::parse($a->created_at)->format('Y-m-d H:i') }}</span>
                                    — {{ $a->user_name ?? 'System' }} {{ $a->action }} {{ $a->document_type }} #{{ $a->document_id }}
                                    <span class="text-muted">({{ $a->from_status ?? '-' }} → {{ $a->to_status }})</span>
                                </li>
                            @endforeach
                        </ul>
                    @endif
                </div>
            </div>
        </div>
    </div>

    {{-- PERIOD COMPARISON --}}
    <div class="row">
        <div class="col-lg-12 mb-4">
            <div class="card shadow">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Period Comparison</h6>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Metric</th>
                                    <th class="text-end">This Month</th>
                                    <th class="text-end">Last Month</th>
                                    <th class="text-end">This Year</th>
                                    <th class="text-end">Last Year</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <th>Revenue</th>
                                    <td class="text-end">{{ number_format($periodSummary['this_month']['revenue'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_month']['revenue'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['this_year']['revenue'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_year']['revenue'] ?? 0, 2) }}</td>
                                </tr>
                                <tr>
                                    <th>Expenses</th>
                                    <td class="text-end">{{ number_format($periodSummary['this_month']['expenses'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_month']['expenses'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['this_year']['expenses'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_year']['expenses'] ?? 0, 2) }}</td>
                                </tr>
                                <tr>
                                    <th>Net Profit</th>
                                    <td class="text-end">{{ number_format($periodSummary['this_month']['net_profit'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_month']['net_profit'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['this_year']['net_profit'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_year']['net_profit'] ?? 0, 2) }}</td>
                                </tr>
                                <tr>
                                    <th>Receivables (Outstanding)</th>
                                    <td class="text-end">{{ number_format($periodSummary['this_month']['receivables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_month']['receivables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['this_year']['receivables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_year']['receivables'] ?? 0, 2) }}</td>
                                </tr>
                                <tr>
                                    <th>Payables (Outstanding)</th>
                                    <td class="text-end">{{ number_format($periodSummary['this_month']['payables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_month']['payables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['this_year']['payables'] ?? 0, 2) }}</td>
                                    <td class="text-end">{{ number_format($periodSummary['last_year']['payables'] ?? 0, 2) }}</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const rangeSelect = document.getElementById('rangeSelect');
    const customDates = document.getElementById('customDates');
    if (rangeSelect && customDates) {
        rangeSelect.addEventListener('change', function () {
            customDates.style.display = this.value === 'custom' ? '' : 'none';
        });
    }

    function safeChart(ctxId, config) {
        const el = document.getElementById(ctxId);
        if (!el || typeof Chart === 'undefined') return;
        new Chart(el, config);
    }

    // Cash flow trend
    safeChart('cashFlowTrendChart', {
        type: 'line',
        data: {
            labels: @json($months12Labels),
            datasets: [
                { label: 'Inflows', data: @json($cashInByMonth), borderColor: 'rgba(28, 200, 138, 1)', backgroundColor: 'rgba(28, 200, 138, 0.1)', fill: true, lineTension: 0.3 },
                { label: 'Outflows', data: @json($cashOutByMonth), borderColor: 'rgba(231, 74, 59, 1)', backgroundColor: 'rgba(231, 74, 59, 0.1)', fill: true, lineTension: 0.3 },
            ]
        },
        options: { maintainAspectRatio: false, legend: { display: true }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Bank breakdown
    safeChart('bankBreakdownChart', {
        type: 'doughnut',
        data: { labels: @json($bankBreakdownLabels), datasets: [{ data: @json($bankBreakdownBalances), backgroundColor: ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796'] }] },
        options: { maintainAspectRatio: false, legend: { display: true, position: 'bottom' }, cutoutPercentage: 60 }
    });

    // AR ageing
    safeChart('arAgeingChart', {
        type: 'horizontalBar',
        data: {
            labels: ['Current', '1-30', '31-60', '61-90', '90+'],
            datasets: [{ label: 'Receivables', data: [@json($arAgeing['Current']), @json($arAgeing['1-30']), @json($arAgeing['31-60']), @json($arAgeing['61-90']), @json($arAgeing['90+'])], backgroundColor: ['#1cc88a', '#36b9cc', '#f6c23e', '#fd7e14', '#e74a3b'] }]
        },
        options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Top customers
    safeChart('topCustomersChart', {
        type: 'bar',
        data: { labels: @json($topCustomerChartLabels), datasets: [{ label: 'Outstanding', data: @json($topCustomerChartValues), backgroundColor: 'rgba(78, 115, 223, 0.8)' }] },
        options: { maintainAspectRatio: false, legend: { display: false }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // AP ageing
    safeChart('apAgeingChart', {
        type: 'horizontalBar',
        data: {
            labels: ['Current', '1-30', '31-60', '61-90', '90+'],
            datasets: [{ label: 'Payables', data: [@json($apAgeing['Current']), @json($apAgeing['1-30']), @json($apAgeing['31-60']), @json($apAgeing['61-90']), @json($apAgeing['90+'])], backgroundColor: ['#1cc88a', '#36b9cc', '#f6c23e', '#fd7e14', '#e74a3b'] }]
        },
        options: { maintainAspectRatio: false, legend: { display: false }, scales: { xAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Top suppliers
    safeChart('topSuppliersChart', {
        type: 'bar',
        data: { labels: @json($topSupplierChartLabels), datasets: [{ label: 'Outstanding', data: @json($topSupplierChartValues), backgroundColor: 'rgba(28, 200, 138, 0.8)' }] },
        options: { maintainAspectRatio: false, legend: { display: false }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Revenue vs expenses
    safeChart('revenueExpenseChart', {
        type: 'bar',
        data: {
            labels: @json($revExpLabels),
            datasets: [
                { label: 'Revenue', backgroundColor: 'rgba(78, 115, 223, 0.8)', borderColor: 'rgba(78, 115, 223, 1)', data: @json($revByMonth) },
                { label: 'Expenses', backgroundColor: 'rgba(231, 74, 59, 0.7)', borderColor: 'rgba(231, 74, 59, 1)', data: @json($expByMonth) }
            ]
        },
        options: { maintainAspectRatio: false, legend: { display: true }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Revenue trend
    safeChart('revenueTrendChart', {
        type: 'line',
        data: { labels: @json($revExpLabels), datasets: [{ label: 'Revenue', data: @json($revByMonth), borderColor: 'rgba(78, 115, 223, 1)', backgroundColor: 'rgba(78, 115, 223, 0.1)', fill: true, lineTension: 0.3 }] },
        options: { maintainAspectRatio: false, legend: { display: true }, scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }
    });

    // Profit margin trend
    safeChart('profitMarginChart', {
        type: 'line',
        data: { labels: @json($revExpLabels), datasets: [{ label: 'Profit Margin %', data: @json($profitMarginByMonth), borderColor: 'rgba(28, 200, 138, 1)', backgroundColor: 'rgba(28, 200, 138, 0.1)', fill: true, lineTension: 0.3 }] },
        options: { maintainAspectRatio: false, legend: { display: true }, scales: { yAxes: [{ ticks: { beginAtZero: true, callback: function(v){ return v + '%'; } } }] } }
    });

    // Expense breakdown donut
    safeChart('expenseBreakdownChart', {
        type: 'doughnut',
        data: { labels: @json($expenseBreakdownLabels), datasets: [{ data: @json($expenseBreakdownValues), backgroundColor: ['#e74a3b', '#f6c23e', '#36b9cc', '#4e73df', '#1cc88a', '#858796'] }] },
        options: { maintainAspectRatio: false, legend: { display: true, position: 'bottom' }, cutoutPercentage: 60 }
    });
});
</script>
@endsection
