@extends('layouts.user')

@section('title', __('profit_loss.title'))
@section('page_title', __('profit_loss.page_title'))
@section('breadcrumb', __('profit_loss.breadcrumb'))

@section('content')
@php
    $fmt = fn ($v) => number_format((float) $v, 2);

    $isProfit = (float) $netProfitLoss >= 0;

    $periodLabel = $from->format('M Y') . ' - ' . $to->format('M Y');

    $pdfUrl = url('/user/reports/profit-loss/pdf') . (request()->query() ? ('?' . http_build_query(request()->query())) : '');
    $resetUrl = url('/user/reports/profit-loss');

    $chartLabelsJson  = json_encode($chartLabels ?? []);
    $chartIncomeJson  = json_encode($chartIncome ?? []);
    $chartExpenseJson = json_encode($chartExpense ?? []);
    $chartNetJson     = json_encode($chartNet ?? []);
@endphp

<div class="w-full px-1 sm:px-2 lg:px-2 space-y-2">

    {{-- Header + Filter --}}
    <div class="overflow-hidden border border-slate-300 bg-white shadow-sm">
        <div class="bg-gradient-to-r from-slate-950 via-slate-900 to-indigo-950 px-3 py-3 md:px-4">
            <div class="flex flex-col gap-2 lg:flex-row lg:items-end lg:justify-between">
                <div>
                    <p class="text-[9px] font-semibold uppercase tracking-[0.22em] text-indigo-200/80">
                        {{ __('profit_loss.financial_report') }}
                    </p>

                    <h2 class="mt-0.5 text-sm md:text-base font-bold text-white leading-tight">
                        {{ __('profit_loss.statement_title') }}
                    </h2>

                    <div class="mt-1.5 flex flex-wrap items-center gap-1 text-[10px]">
                        <span class="inline-flex items-center border border-white/10 bg-white/10 px-2 py-0.5 font-semibold text-white">
                            {{ $periodLabel }}
                        </span>

                        <span class="inline-flex items-center border border-white/10 bg-white/10 px-2 py-0.5 font-semibold text-slate-200">
                            {{ $from->format('d M Y') }} - {{ $to->format('d M Y') }}
                        </span>
                    </div>
                </div>

                <div class="flex flex-wrap gap-1.5">
                    <a href="{{ $pdfUrl }}"
                       class="inline-flex items-center justify-center border border-white bg-white px-2.5 py-1.5 text-[10px] font-bold text-slate-900 shadow-sm transition hover:bg-slate-100">
                        {{ __('profit_loss.download_pdf') }}
                    </a>
                </div>
            </div>
        </div>

        <div class="border-t border-slate-200 bg-slate-50 px-2 py-2 md:px-3">
            <form method="GET" class="grid grid-cols-2 md:grid-cols-12 gap-1.5 items-end">

                <div class="md:col-span-2">
                    <label class="mb-1 block text-[10px] font-semibold text-slate-600">
                        {{ __('profit_loss.from_month') }}
                    </label>
                    <select name="from_month"
                            class="w-full border border-slate-300 bg-white px-2 py-1.5 text-[11px] font-medium text-slate-700 shadow-sm outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100">
                        @for($m = 1; $m <= 12; $m++)
                            <option value="{{ $m }}" {{ (int) ($fromMonth ?? 0) === $m ? 'selected' : '' }}>
                                {{ \Carbon\Carbon::create()->month($m)->format('M') }}
                            </option>
                        @endfor
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="mb-1 block text-[10px] font-semibold text-slate-600">
                        {{ __('profit_loss.from_year') }}
                    </label>
                    <select name="from_year"
                            class="w-full border border-slate-300 bg-white px-2 py-1.5 text-[11px] font-medium text-slate-700 shadow-sm outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100">
                        @for($y = now()->year; $y >= 2020; $y--)
                            <option value="{{ $y }}" {{ (int) ($fromYear ?? 0) === $y ? 'selected' : '' }}>
                                {{ $y }}
                            </option>
                        @endfor
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="mb-1 block text-[10px] font-semibold text-slate-600">
                        {{ __('profit_loss.to_month') }}
                    </label>
                    <select name="to_month"
                            class="w-full border border-slate-300 bg-white px-2 py-1.5 text-[11px] font-medium text-slate-700 shadow-sm outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100">
                        @for($m = 1; $m <= 12; $m++)
                            <option value="{{ $m }}" {{ (int) ($toMonth ?? 0) === $m ? 'selected' : '' }}>
                                {{ \Carbon\Carbon::create()->month($m)->format('M') }}
                            </option>
                        @endfor
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="mb-1 block text-[10px] font-semibold text-slate-600">
                        {{ __('profit_loss.to_year') }}
                    </label>
                    <select name="to_year"
                            class="w-full border border-slate-300 bg-white px-2 py-1.5 text-[11px] font-medium text-slate-700 shadow-sm outline-none focus:border-indigo-400 focus:ring-2 focus:ring-indigo-100">
                        @for($y = now()->year; $y >= 2020; $y--)
                            <option value="{{ $y }}" {{ (int) ($toYear ?? 0) === $y ? 'selected' : '' }}>
                                {{ $y }}
                            </option>
                        @endfor
                    </select>
                </div>

                <div class="md:col-span-4 flex gap-1.5">
                    <button type="submit"
                            class="flex-1 border border-slate-900 bg-slate-900 px-2.5 py-1.5 text-[10px] font-bold text-white shadow-sm transition hover:bg-slate-800">
                        {{ __('profit_loss.apply_filter') }}
                    </button>

                    <a href="{{ $resetUrl }}"
                       class="border border-slate-300 bg-white px-2.5 py-1.5 text-[10px] font-bold text-slate-700 shadow-sm transition hover:bg-slate-50">
                        {{ __('profit_loss.reset') }}
                    </a>
                </div>
            </form>
        </div>
    </div>

    {{-- Main Summary --}}
    <div class="grid grid-cols-2 xl:grid-cols-4 gap-2">
        <div class="border border-emerald-200 bg-gradient-to-br from-emerald-50 to-white p-2.5 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.14em] text-emerald-700">
                {{ __('profit_loss.total_income') }}
            </p>
            <h3 class="mt-1 text-sm font-bold text-slate-900">{{ $fmt($totalIncome) }}</h3>
            <p class="mt-0.5 text-[10px] text-slate-500">{{ __('profit_loss.total_income_hint') }}</p>
        </div>

        <div class="border border-rose-200 bg-gradient-to-br from-rose-50 to-white p-2.5 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.14em] text-rose-700">
                {{ __('profit_loss.total_expense') }}
            </p>
            <h3 class="mt-1 text-sm font-bold text-slate-900">{{ $fmt($totalExpense) }}</h3>
            <p class="mt-0.5 text-[10px] text-slate-500">{{ __('profit_loss.total_expense_hint') }}</p>
        </div>

        <div class="border {{ $isProfit ? 'border-cyan-200 bg-gradient-to-br from-cyan-50 to-white' : 'border-amber-200 bg-gradient-to-br from-amber-50 to-white' }} p-2.5 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.14em] {{ $isProfit ? 'text-cyan-700' : 'text-amber-700' }}">
                {{ $isProfit ? __('profit_loss.net_profit') : __('profit_loss.net_loss') }}
            </p>
            <h3 class="mt-1 text-sm font-bold text-slate-900">{{ $fmt(abs($netProfitLoss)) }}</h3>
            <p class="mt-0.5 text-[10px] text-slate-500">
                {{ $isProfit ? __('profit_loss.profit_hint') : __('profit_loss.loss_hint') }}
            </p>
        </div>

        <div class="border border-slate-300 bg-white p-2.5 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.14em] text-slate-500">
                {{ __('profit_loss.selected_period') }}
            </p>
            <h3 class="mt-1 text-[11px] font-bold text-slate-900">{{ $periodLabel }}</h3>
            <p class="mt-0.5 text-[10px] text-slate-500">{{ $from->format('d M Y') }} - {{ $to->format('d M Y') }}</p>
        </div>
    </div>

    {{-- Mini Summary --}}
    <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-2">
        <div class="border border-slate-300 bg-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                {{ __('profit_loss.customer_bill_income') }}
            </p>
            <div class="mt-1 text-xs font-bold text-emerald-600">{{ $fmt($customerBillIncome) }}</div>
        </div>

        <div class="border border-slate-300 bg-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                {{ __('profit_loss.daily_expense') }}
            </p>
            <div class="mt-1 text-xs font-bold text-rose-600">{{ $fmt($dailyExpenseTotal) }}</div>
        </div>

        <div class="border border-slate-300 bg-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                {{ __('profit_loss.supplier_expense') }}
            </p>
            <div class="mt-1 text-xs font-bold text-rose-600">{{ $fmt($supplierExpenseTotal) }}</div>
        </div>

        <div class="border border-slate-300 bg-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                {{ __('profit_loss.salary_expense') }}
            </p>
            <div class="mt-1 text-xs font-bold text-rose-600">{{ $fmt($salaryExpenseTotal) }}</div>
        </div>

        <div class="border border-slate-300 bg-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                {{ __('profit_loss.bonus_bank_charge') }}
            </p>
            <div class="mt-1 text-xs font-bold text-rose-600">
                {{ $fmt((float) $paidBonusExpenseTotal + (float) $bankChargeExpenseTotal) }}
            </div>
        </div>

        <div class="border border-amber-200 bg-gradient-to-br from-amber-50 to-white p-2 shadow-sm">
            <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-amber-700">
                {{ __('profit_loss.loan_finance_cost') }}
            </p>
            <div class="mt-1 text-xs font-bold text-amber-600">
                {{ $fmt($loanFinanceCostTotal ?? 0) }}
            </div>
        </div>
    </div>

    {{-- Chart --}}
    <div class="border border-slate-300 bg-white shadow-sm overflow-hidden">
        <div class="flex items-center justify-between px-3 py-2 border-b border-slate-200">
            <div>
                <h3 class="text-xs font-bold text-slate-900">{{ __('profit_loss.chart_title') }}</h3>
                <p class="mt-0.5 text-[10px] text-slate-500">
                    {{ ($chartMode ?? 'monthly') === 'yearly' ? __('profit_loss.chart_yearly') : __('profit_loss.chart_monthly') }}
                </p>
            </div>
        </div>

        <div class="p-2 md:p-3">
            <div class="h-[220px] md:h-[260px]">
                <canvas id="profitLossChart"></canvas>
            </div>
        </div>
    </div>

    {{-- Breakdown Tables --}}
    <div class="grid grid-cols-1 xl:grid-cols-2 gap-2">
        <div class="border border-slate-300 bg-white shadow-sm overflow-hidden">
            <div class="px-3 py-2 border-b border-slate-200">
                <h3 class="text-xs font-bold text-slate-900">{{ __('profit_loss.income_breakdown') }}</h3>
                <p class="mt-0.5 text-[10px] text-slate-500">{{ __('profit_loss.income_sources') }}</p>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-3 py-2 text-left text-[9px] font-bold uppercase tracking-[0.12em] text-slate-500">
                                {{ __('profit_loss.particulars') }}
                            </th>
                            <th class="px-3 py-2 text-right text-[9px] font-bold uppercase tracking-[0.12em] text-slate-500">
                                {{ __('profit_loss.amount') }}
                            </th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-200">
                        @forelse($statementIncomeRows as $row)
                            <tr class="hover:bg-slate-50/70">
                                <td class="px-3 py-2 text-[11px] font-semibold text-slate-800">{{ $row['label'] }}</td>
                                <td class="px-3 py-2 text-right text-[11px] font-bold text-emerald-600">{{ $fmt($row['amount']) }}</td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="2" class="px-3 py-5 text-center text-[11px] text-slate-500">
                                    {{ __('profit_loss.no_income_data') }}
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                    <tfoot class="bg-emerald-50">
                        <tr>
                            <th class="px-3 py-2.5 text-left text-[11px] font-bold text-slate-900">
                                {{ __('profit_loss.total_income') }}
                            </th>
                            <th class="px-3 py-2.5 text-right text-[11px] font-bold text-emerald-700">
                                {{ $fmt($totalIncome) }}
                            </th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>

        <div class="border border-slate-300 bg-white shadow-sm overflow-hidden">
            <div class="px-3 py-2 border-b border-slate-200">
                <h3 class="text-xs font-bold text-slate-900">{{ __('profit_loss.expense_breakdown') }}</h3>
                <p class="mt-0.5 text-[10px] text-slate-500">{{ __('profit_loss.expense_details') }}</p>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead class="bg-slate-50">
                        <tr>
                            <th class="px-3 py-2 text-left text-[9px] font-bold uppercase tracking-[0.12em] text-slate-500">
                                {{ __('profit_loss.particulars') }}
                            </th>
                            <th class="px-3 py-2 text-right text-[9px] font-bold uppercase tracking-[0.12em] text-slate-500">
                                {{ __('profit_loss.amount') }}
                            </th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-200">
                        @forelse($statementExpenseRows as $row)
                            @php
                                $isLoanRow = str_contains(strtolower($row['label']), 'loan finance cost');
                            @endphp
                            <tr class="{{ $isLoanRow ? 'bg-amber-50/60 hover:bg-amber-50' : 'hover:bg-slate-50/70' }}">
                                <td class="px-3 py-2 text-[11px] font-semibold text-slate-800">{{ $row['label'] }}</td>
                                <td class="px-3 py-2 text-right text-[11px] font-bold {{ $isLoanRow ? 'text-amber-600' : 'text-rose-600' }}">
                                    {{ $fmt($row['amount']) }}
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="2" class="px-3 py-5 text-center text-[11px] text-slate-500">
                                    {{ __('profit_loss.no_expense_data') }}
                                </td>
                            </tr>
                        @endforelse

                        @if(($loanFinanceCostTotal ?? 0) > 0 && collect($statementExpenseRows)->where('label', 'Loan Finance Cost')->count() === 0)
                            <tr class="bg-amber-50/60 hover:bg-amber-50">
                                <td class="px-3 py-2 text-[11px] font-semibold text-slate-800">
                                    {{ __('profit_loss.loan_finance_cost') }}
                                </td>
                                <td class="px-3 py-2 text-right text-[11px] font-bold text-amber-600">
                                    {{ $fmt($loanFinanceCostTotal) }}
                                </td>
                            </tr>
                        @endif
                    </tbody>
                    <tfoot class="bg-rose-50">
                        <tr>
                            <th class="px-3 py-2.5 text-left text-[11px] font-bold text-slate-900">
                                {{ __('profit_loss.total_expense') }}
                            </th>
                            <th class="px-3 py-2.5 text-right text-[11px] font-bold text-rose-700">
                                {{ $fmt($totalExpense) }}
                            </th>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

    {{-- Final Summary --}}
    <div class="border border-slate-300 bg-white shadow-sm overflow-hidden">
        <div class="px-3 py-2 border-b border-slate-200">
            <h3 class="text-xs font-bold text-slate-900">{{ __('profit_loss.final_summary') }}</h3>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-0">
            <div class="p-3 border-b md:border-b-0 md:border-r border-slate-200">
                <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                    {{ __('profit_loss.total_income') }}
                </p>
                <div class="mt-1 text-sm font-bold text-emerald-600">{{ $fmt($totalIncome) }}</div>
            </div>

            <div class="p-3 border-b md:border-b-0 md:border-r border-slate-200">
                <p class="text-[9px] font-semibold uppercase tracking-[0.12em] text-slate-500">
                    {{ __('profit_loss.total_expense') }}
                </p>
                <div class="mt-1 text-sm font-bold text-rose-600">{{ $fmt($totalExpense) }}</div>
            </div>

            <div class="p-3">
                <p class="text-[9px] font-semibold uppercase tracking-[0.12em] {{ $isProfit ? 'text-cyan-700' : 'text-amber-700' }}">
                    {{ $isProfit ? __('profit_loss.net_profit') : __('profit_loss.net_loss') }}
                </p>
                <div class="mt-1 text-sm font-bold {{ $isProfit ? 'text-cyan-700' : 'text-amber-700' }}">
                    {{ $fmt(abs($netProfitLoss)) }}
                </div>
            </div>
        </div>
    </div>

</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const canvas = document.getElementById('profitLossChart');
    if (!canvas) return;

    const labels = {!! $chartLabelsJson !!};
    const income = {!! $chartIncomeJson !!};
    const expense = {!! $chartExpenseJson !!};
    const net = {!! $chartNetJson !!};

    new Chart(canvas, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: @json(__('profit_loss.chart_income')),
                    data: income,
                    borderWidth: 1,
                    borderRadius: 0
                },
                {
                    label: @json(__('profit_loss.chart_expense')),
                    data: expense,
                    borderWidth: 1,
                    borderRadius: 0
                },
                {
                    label: @json(__('profit_loss.chart_net')),
                    data: net,
                    type: 'line',
                    tension: 0.35,
                    borderWidth: 2,
                    fill: false
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        boxWidth: 10,
                        boxHeight: 10,
                        font: {
                            size: 10
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    },
                    ticks: {
                        font: {
                            size: 9
                        }
                    }
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        font: {
                            size: 9
                        },
                        callback: function(value) {
                            return Number(value).toLocaleString();
                        }
                    }
                }
            }
        }
    });
});
</script>
@endpush