@extends('layouts.app')
@section('title', 'Dashboard')

@section('breadcrumb')
    <li class="breadcrumb-item active">Dashboard</li>
@endsection

@section('content')
@php
    $fp = $reports['fundPosition'];
    $wc = $reports['workingCapital'];
    $ms = $reports['monthlySeries'];
    $pr = $reports['profitRatio'];
    $eb = $reports['expenseBreakdown'];
    $topCustomers = $reports['topCustomerOutstanding'];
    $topVendors = $reports['topVendorOutstanding'];
    $fmt = fn ($v) => \App\Helpers\NumberHelper::formatAmount((float) $v, $companyId, true);
@endphp

<div class="page-header">
    <div>
        <h1 class="page-title">{{ $company->name }}</h1>
    </div>
</div>

<!-- ── Fund Position & Working Capital ──────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-12 col-xl-6">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <div class="dash-report-header">
                    <div class="dash-report-icon" style="background:#DCFCE7;color:#15803D">
                        <i class="bi bi-cash-stack"></i>
                    </div>
                    <div>
                        <h2 class="dash-report-title">Fund Position</h2>
                        <p class="dash-report-subtitle">Cash and bank balances</p>
                    </div>
                </div>
                <div class="dash-wc-rows mt-3">
                    <div class="dash-wc-row">
                        <span class="dash-wc-label">Cash</span>
                        <span class="dash-wc-value">{{ $fmt($fp['cash']) }}</span>
                    </div>
                    <div class="dash-wc-row">
                        <span class="dash-wc-label text-primary">Bank</span>
                        <span class="dash-wc-value">{{ $fmt($fp['bank']) }}</span>
                    </div>
                    <div class="dash-wc-row dash-wc-total">
                        <span class="dash-wc-label">Total funds</span>
                        <span class="dash-wc-value text-success fw-bold">{{ $fmt($fp['total']) }}</span>
                    </div>
                </div>
                <div id="fundPositionChart" class="dash-donut-chart mt-3"></div>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-6">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <div class="dash-report-header">
                    <div class="dash-report-icon" style="background:#EDE9FE;color:#5B21B6">
                        <i class="bi bi-wallet2"></i>
                    </div>
                    <div>
                        <h2 class="dash-report-title">Working Capital</h2>
                        <p class="dash-report-subtitle">Current assets &minus; liabilities</p>
                    </div>
                </div>
                <div class="dash-wc-rows mt-3">
                    <div class="dash-wc-row">
                        <span class="dash-wc-label">CA</span>
                        <span class="dash-wc-value">{{ $fmt($wc['current_assets']) }}</span>
                    </div>
                    <div class="dash-wc-row">
                        <span class="dash-wc-label text-primary">CL</span>
                        <span class="dash-wc-value">{{ $fmt($wc['current_liabilities']) }}</span>
                    </div>
                    <div class="dash-wc-row dash-wc-total">
                        <span class="dash-wc-label">Net working capital</span>
                        <span class="dash-wc-value text-success fw-bold">{{ $fmt($wc['net']) }}</span>
                    </div>
                </div>
                <div id="workingCapitalChart" class="dash-donut-chart mt-3"></div>
            </div>
        </div>
    </div>
</div>

<!-- ── Top Customer & Vendor Outstanding ─────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-12 col-xl-6">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <div class="dash-report-header">
                    <div class="dash-report-icon" style="background:#DCFCE7;color:#15803D">
                        <i class="bi bi-person-check"></i>
                    </div>
                    <div>
                        <h2 class="dash-report-title">Top 5 Customer Outstanding</h2>
                        <p class="dash-report-subtitle">Largest receivable balances</p>
                    </div>
                </div>
                <div class="dash-overdue-list mt-3">
                    @forelse($topCustomers as $i => $customer)
                    <div class="dash-overdue-item">
                        <span class="dash-overdue-rank">{{ $i + 1 }}</span>
                        <div class="dash-overdue-info">
                            <div class="dash-overdue-name">{{ $customer['name'] }}</div>
                            <div class="dash-overdue-days">Open {{ $customer['days_open'] }} days</div>
                        </div>
                        <div class="dash-overdue-amount">{{ $fmt($customer['amount_due']) }}</div>
                    </div>
                    @empty
                    <div class="text-center py-4 text-muted">
                        <i class="bi bi-check-circle display-6 d-block mb-2 text-success"></i>
                        No customer outstanding balances
                    </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>

    <div class="col-12 col-xl-6">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <div class="dash-report-header">
                    <div class="dash-report-icon" style="background:#FFEDD5;color:#C2410C">
                        <i class="bi bi-truck"></i>
                    </div>
                    <div>
                        <h2 class="dash-report-title">Top 5 Vendor Outstanding</h2>
                        <p class="dash-report-subtitle">Largest payable balances</p>
                    </div>
                </div>
                <div class="dash-overdue-list mt-3">
                    @forelse($topVendors as $i => $vendor)
                    <div class="dash-overdue-item">
                        <span class="dash-overdue-rank">{{ $i + 1 }}</span>
                        <div class="dash-overdue-info">
                            <div class="dash-overdue-name">{{ $vendor['name'] }}</div>
                            <div class="dash-overdue-days">Open {{ $vendor['days_open'] }} days</div>
                        </div>
                        <div class="dash-overdue-amount">{{ $fmt($vendor['amount_due']) }}</div>
                    </div>
                    @empty
                    <div class="text-center py-4 text-muted">
                        <i class="bi bi-check-circle display-6 d-block mb-2 text-success"></i>
                        No vendor outstanding balances
                    </div>
                    @endforelse
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ── Income vs Expense & Profit Ratio ─────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-12 col-xl-7">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <h2 class="dash-report-title mb-0">Income vs Expense</h2>
                <p class="dash-report-subtitle mb-3">Last 6 months</p>
                <div id="incomeExpenseChart"></div>
            </div>
        </div>
    </div>
    <div class="col-12 col-xl-5">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <h2 class="dash-report-title mb-0">Month-Wise Profit Ratio</h2>
                <p class="dash-report-subtitle mb-3">Net profit as % of income</p>
                <div id="profitRatioChart"></div>
            </div>
        </div>
    </div>
</div>

<!-- ── Expense Breakdown ──────────────────────────────────────────────────── -->
<div class="row g-3 mb-4">
    <div class="col-12 col-xl-6">
        <div class="card dash-report-card h-100">
            <div class="card-body">
                <div class="dash-report-header">
                    <div class="dash-report-icon" style="background:#FCE7F3;color:#BE185D">
                        <i class="bi bi-pie-chart"></i>
                    </div>
                    <div>
                        <h2 class="dash-report-title">Expense Breakdown</h2>
                        <p class="dash-report-subtitle">By expense account</p>
                    </div>
                </div>
                <div id="expenseBreakdownChart" class="mt-2"></div>
            </div>
        </div>
    </div>
</div>

<!-- ── Active Users ─────────────────────────────────────────────────────── -->
<div class="row g-3">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="bi bi-people me-2 text-primary"></i>Active Users Online</span>
                <span class="badge" style="background:#d1e7dd;color:#0a3622">
                    {{ $kpis['online_users'] }} online
                </span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Last Active</th>
                                <th>IP</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($onlineSessions as $session)
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center gap-2">
                                        <img src="{{ $session->user?->avatar_url }}"
                                             style="width:28px;height:28px;border-radius:50%;object-fit:cover" alt="">
                                        <span>{{ $session->user?->name ?? 'Unknown' }}</span>
                                        @if($session->user_id === auth()->id())
                                            <span class="badge bg-primary" style="font-size:10px">You</span>
                                        @endif
                                    </div>
                                </td>
                                <td class="text-muted" style="font-size:12px">
                                    {{ \Carbon\Carbon::createFromTimestamp($session->last_activity)->diffForHumans() }}
                                </td>
                                <td><code style="font-size:11px">{{ $session->ip_address }}</code></td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="3" class="text-center text-muted py-3">No active sessions</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const currency = @json($currencySymbol);
    const usesBdFormat = @json(\App\Helpers\NumberHelper::usesBangladeshiGrouping($companyId));
    const amountDecimals = @json((int) \App\Models\Setting::get($companyId, 'amount_decimals', 2));

    function formatBdAmount(value, decimals) {
        const negative = value < 0;
        let amount = Math.abs(value);
        const factor = 10 ** decimals;
        amount = Math.round(amount * factor) / factor;

        let intPart = Math.floor(amount);
        let fraction = decimals > 0 ? Math.round((amount - intPart) * factor) : 0;
        let digits = String(intPart);
        let formatted;

        if (digits.length <= 3) {
            formatted = digits;
        } else {
            const lastThree = digits.slice(-3);
            let leading = digits.slice(0, -3);
            const groups = [];

            while (leading.length > 0) {
                if (leading.length <= 2) {
                    groups.unshift(leading);
                    break;
                }
                groups.unshift(leading.slice(-2));
                leading = leading.slice(0, -2);
            }

            formatted = groups.join(',') + ',' + lastThree;
        }

        if (decimals > 0) {
            formatted += '.' + String(fraction).padStart(decimals, '0');
        }

        return (negative ? '-' : '') + formatted;
    }

    const fmtMoney = (value) => currency + (
        usesBdFormat
            ? formatBdAmount(value, amountDecimals)
            : Number(value).toLocaleString(undefined, { minimumFractionDigits: amountDecimals, maximumFractionDigits: amountDecimals })
    );
    const fmtK = v => {
        if (Math.abs(v) >= 1000) return (v / 1000).toFixed(0) + 'k';
        return v.toFixed(0);
    };

    const donutDefaults = {
        chart: { type: 'donut', fontFamily: 'Segoe UI, sans-serif' },
        dataLabels: { enabled: false },
        legend: { show: false },
        stroke: { width: 2, colors: ['#fff'] },
        plotOptions: {
            pie: {
                donut: {
                    size: '72%',
                    labels: { show: false },
                },
            },
        },
    };

    // Fund Position
    new ApexCharts(document.getElementById('fundPositionChart'), {
        ...donutDefaults,
        series: @json([$fp['bank'], $fp['cash']]),
        chart: { ...donutDefaults.chart, height: 200 },
        colors: ['#3B82F6', '#22C55E'],
        labels: ['Bank {{ $fp['bank_pct'] }}%', 'Cash {{ $fp['cash_pct'] }}%'],
    }).render();

    // Working Capital
    new ApexCharts(document.getElementById('workingCapitalChart'), {
        ...donutDefaults,
        series: @json([$wc['current_assets'], $wc['current_liabilities']]),
        chart: { ...donutDefaults.chart, height: 200 },
        colors: ['#14B8A6', '#EF4444'],
        labels: ['CA {{ $wc['ca_pct'] }}%', 'CL {{ $wc['cl_pct'] }}%'],
    }).render();

    // Income vs Expense
    new ApexCharts(document.getElementById('incomeExpenseChart'), {
        series: [
            { name: 'income', data: @json($ms['income']) },
            { name: 'expense', data: @json($ms['expense']) },
        ],
        chart: { type: 'bar', height: 280, toolbar: { show: false }, fontFamily: 'Segoe UI, sans-serif' },
        colors: ['#22C55E', '#EF4444'],
        plotOptions: { bar: { borderRadius: 6, columnWidth: '45%', dataLabels: { position: 'top' } } },
        dataLabels: { enabled: false },
        xaxis: { categories: @json($ms['labels']), labels: { style: { fontSize: '12px', colors: '#64748B' } } },
        yaxis: {
            labels: {
                formatter: fmtK,
                style: { fontSize: '11px', colors: '#94A3B8' },
            },
        },
        legend: { position: 'bottom', fontSize: '12px', markers: { radius: 2 } },
        grid: { borderColor: '#f1f5f9', strokeDashArray: 4 },
        tooltip: { y: { formatter: fmtMoney } },
    }).render();

    // Profit Ratio
    const profitRatios = @json($pr['ratios']);
    new ApexCharts(document.getElementById('profitRatioChart'), {
        series: [{ name: 'Profit %', data: profitRatios.map(v => v === null ? 0 : v) }],
        chart: { type: 'bar', height: 280, toolbar: { show: false }, fontFamily: 'Segoe UI, sans-serif' },
        colors: ['#3B82F6'],
        plotOptions: { bar: { borderRadius: 6, columnWidth: '40%' } },
        dataLabels: { enabled: false },
        xaxis: { categories: @json($pr['labels']), labels: { style: { fontSize: '12px', colors: '#64748B' } } },
        yaxis: {
            labels: {
                formatter: v => v + '%',
                style: { fontSize: '11px', colors: '#94A3B8' },
            },
        },
        grid: { borderColor: '#f1f5f9', strokeDashArray: 4 },
        tooltip: {
            y: {
                formatter: (v, opts) => {
                    const raw = profitRatios[opts.dataPointIndex];
                    return raw === null ? 'N/A' : raw + '%';
                },
            },
        },
    }).render();

    // Expense Breakdown
    const expenseLabels = @json($eb['labels']);
    const expenseAmounts = @json($eb['amounts']);
    if (expenseLabels.length > 0) {
        new ApexCharts(document.getElementById('expenseBreakdownChart'), {
            series: expenseAmounts,
            chart: { type: 'donut', height: 300, fontFamily: 'Segoe UI, sans-serif' },
            labels: expenseLabels,
            colors: ['#3B82F6', '#86EFAC', '#A78BFA', '#FB923C', '#EF4444', '#22D3EE', '#FACC15', '#F472B6', '#15803D'],
            dataLabels: { enabled: false },
            stroke: { width: 2, colors: ['#fff'] },
            legend: {
                position: 'bottom',
                fontSize: '11px',
                markers: { width: 8, height: 8, radius: 12 },
                itemMargin: { horizontal: 8, vertical: 4 },
            },
            plotOptions: { pie: { donut: { size: '60%' } } },
            tooltip: { y: { formatter: fmtMoney } },
        }).render();
    } else {
        document.getElementById('expenseBreakdownChart').innerHTML =
            '<div class="text-center py-4 text-muted"><i class="bi bi-pie-chart display-6 d-block mb-2"></i>No expense data for this period</div>';
    }
});
</script>
@endpush
