@extends('layouts.app')

@section('content')

<x-common.page-breadcrumb pageTitle="{{ $title ?? 'Laporan Buku Besar' }}" />

@php
    $today = now()->toDateString();

    $hasStart = request()->filled('start_date');
    $hasEnd   = request()->filled('end_date');

    $startDate = request('start_date', $startDate ?? $today);
    $endDate   = request('end_date', $endDate ?? $today);

    $resolveText = function ($trx, array $keys, $default = '-') {
        foreach ($keys as $key) {
            $value = data_get($trx, $key);

            if (is_array($value) || is_object($value)) {
                $value =
                    data_get($value, 'name')
                    ?? data_get($value, 'customer_name')
                    ?? data_get($value, 'label')
                    ?? data_get($value, 'title');
            }

            if (is_string($value)) {
                $value = trim($value);
            }

            if ($value !== null && $value !== '') {
                return (string) $value;
            }
        }

        return $default;
    };

    $transactionsCol = collect($transactions ?? $ledger ?? [])->map(function ($trx) use ($resolveText) {
        return [
            'tanggal' => data_get($trx, 'tanggal')
                ?? data_get($trx, 'date')
                ?? data_get($trx, 'created_at')
                ?? data_get($trx, 'transaction_date'),

            'keterangan' => $resolveText($trx, [
                'keterangan',
                'description',
                'notes',
                'note',
                'title',
            ], '-'),

            'customer' => $resolveText($trx, [
                'customer',
                'customer_name',
                'pelanggan',
                'buyer_name',
                'client_name',
                'order.customer_name',
                'order.customer.name',
                'order.customerRelation.name',
                'order.customer_relation.name',
                'payment.order.customer_name',
                'payment.order.customer.name',
                'payment.order.customerRelation.name',
                'payment.order.customer_relation.name',
            ], '-'),

            'rekening' => $resolveText($trx, [
                'rekening',
                'account_name',
                'payment_account_name',
                'paymentAccount.name',
                'payment_account.name',
                'account.name',
            ], '-'),

            'debit'  => (float) data_get($trx, 'debit', 0),
            'kredit' => (float) data_get($trx, 'kredit', data_get($trx, 'credit', 0)),
            'saldo'  => (float) data_get($trx, 'saldo', data_get($trx, 'balance', 0)),
            'source' => data_get($trx, 'source', '-'),
        ];
    });

    $accountsCol = collect($accounts ?? []);

    $totalDebit  = $transactionsCol->sum('debit');
    $totalKredit = $transactionsCol->sum('kredit');
    $saldoAkhir  = data_get($transactionsCol->last(), 'saldo', $saldoAwal ?? 0);

    $selectedAccount = request('payment_account_id');
    $selectedAccountLabel = 'Semua Rekening';

    if ($selectedAccount !== null && $selectedAccount !== '') {
        $selectedAccountLabel = $accountsCol->first(function ($acc) use ($selectedAccount) {
            return (string) data_get($acc, 'id') === (string) $selectedAccount;
        })->name ?? 'Rekening Terpilih';
    }

    $isSingleDay = ($startDate === $endDate);

    $netFlow = ($totalDebit ?? 0) - ($totalKredit ?? 0);
    $trendText = $netFlow >= 0 ? 'surplus' : 'defisit';

    $isMinus = ($saldoAkhir ?? 0) < 0;

    $periodLabel = $isSingleDay
        ? ('Tanggal: ' . \Carbon\Carbon::parse($startDate)->format('d M Y'))
        : ('Periode: ' . \Carbon\Carbon::parse($startDate)->format('d M Y') . ' s/d ' . \Carbon\Carbon::parse($endDate)->format('d M Y'));
@endphp

@if(!$hasStart && !$hasEnd)
    <script>
        (function () {
            const base = @json(url()->current());
            const today = @json($today);
            const acc = @json(request('payment_account_id'));
            const qs = new URLSearchParams();
            qs.set('start_date', today);
            qs.set('end_date', today);
            if (acc !== null && acc !== '') qs.set('payment_account_id', acc);
            window.location.replace(base + '?' + qs.toString());
        })();
    </script>
@endif

@if(empty($isPrint))
<div class="mb-4 flex items-center justify-end gap-2">
    <form method="GET" action="{{ route('reports.cash-ledger.export') }}" class="inline">
        <input type="hidden" name="start_date" value="{{ $startDate }}">
        <input type="hidden" name="end_date" value="{{ $endDate }}">
        @if(request('payment_account_id') !== null && request('payment_account_id') !== '')
            <input type="hidden" name="payment_account_id" value="{{ request('payment_account_id') }}">
        @endif

        <button type="submit"
            class="inline-flex items-center gap-2 rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300">
            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M12 3v12m0 0l3-3m-3 3l-3-3M4 17v3a1 1 0 001 1h14a1 1 0 001-1v-3"/>
            </svg>
            Export Excel
        </button>
    </form>

    <form method="GET" action="{{ route('reports.cash-ledger.print') }}" target="_blank" class="inline">
        <input type="hidden" name="start_date" value="{{ $startDate }}">
        <input type="hidden" name="end_date" value="{{ $endDate }}">
        @if(request('payment_account_id') !== null && request('payment_account_id') !== '')
            <input type="hidden" name="payment_account_id" value="{{ request('payment_account_id') }}">
        @endif

        <button type="submit"
            class="inline-flex items-center gap-2 rounded-lg bg-brand-500 px-4 py-2 text-sm font-medium text-white hover:bg-brand-600">
            <svg class="size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"/>
            </svg>
            Cetak
        </button>
    </form>
</div>
@endif

<div class="mb-6 grid grid-cols-2 gap-3 md:grid-cols-4 md:gap-4">
    <x-posgraf.stat-card
        title="{{ $isSingleDay ? 'Saldo Awal (Hari Ini)' : 'Saldo Awal (Periode)' }}"
        value="Rp {{ number_format($saldoAwal ?? 0, 0, ',', '.') }}"
        color="brand"
    />
    <x-posgraf.stat-card
        title="{{ $isSingleDay ? 'Pemasukan (Debit) Hari Ini' : 'Total Debit (Periode)' }}"
        value="Rp {{ number_format($totalDebit ?? 0, 0, ',', '.') }}"
        color="success"
    />
    <x-posgraf.stat-card
        title="{{ $isSingleDay ? 'Pengeluaran (Kredit) Hari Ini' : 'Total Kredit (Periode)' }}"
        value="Rp {{ number_format($totalKredit ?? 0, 0, ',', '.') }}"
        color="error"
    />
    <x-posgraf.stat-card
        title="{{ $isSingleDay ? 'Saldo Akhir (Hari Ini)' : 'Saldo Akhir (Periode)' }}"
        value="Rp {{ number_format($saldoAkhir ?? 0, 0, ',', '.') }}"
        color="warning"
    />
</div>

<div class="mb-6 rounded-2xl border border-brand-200 bg-brand-50 p-5 dark:border-brand-900/40 dark:bg-brand-900/10">
    <div class="flex items-start gap-4">
        <div class="flex h-10 w-10 items-center justify-center rounded-xl bg-brand-500 text-white">
            <svg class="size-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
            </svg>
        </div>

        <div class="flex-1">
            <div class="flex flex-wrap items-center gap-2">
                <h4 class="text-sm font-semibold text-gray-900 dark:text-white/90">Ringkasan Buku Besar</h4>
                <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                    {{ $periodLabel }}
                </span>
                <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                    Rekening: {{ $selectedAccountLabel }}
                </span>
                <span class="rounded-full bg-white/80 px-2 py-0.5 text-xs font-medium text-gray-700 dark:bg-white/10 dark:text-white/70">
                    Arus Bersih: <span class="font-semibold">{{ $trendText }}</span>
                </span>
            </div>

            <p class="mt-2 text-sm text-gray-700 dark:text-white/70">
                Buku besar ini sudah sinkron dengan modul kas:
                <span class="font-semibold">Kas Tunai</span>,
                <span class="font-semibold">Kas Kecil</span>,
                <span class="font-semibold">Kas Bank</span>,
                termasuk <span class="font-semibold">modal</span>, <span class="font-semibold">mutasi</span>, 
                <span class="font-semibold">setoran</span>, <span class="font-semibold">penjualan</span>,
                <span class="font-semibold">expense</span>, dan <span class="font-semibold">pembayaran supplier</span>.
            </p>

            <div class="mt-3 grid grid-cols-1 gap-2 md:grid-cols-2">
                <div class="rounded-xl bg-white/70 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                    <div class="mb-1 font-semibold">Cara baca cepat</div>
                    <ul class="space-y-1">
                        <li>• <span class="font-semibold">Debit</span> = uang masuk ke rekening yang dipilih.</li>
                        <li>• <span class="font-semibold">Kredit</span> = uang keluar dari rekening yang dipilih.</li>
                        <li>• <span class="font-semibold">Mutasi</span> akan tampil masuk/keluar sesuai rekening filter.</li>
                    </ul>
                </div>

                <div class="rounded-xl bg-white/70 p-3 text-xs text-gray-700 ring-1 ring-gray-200 dark:bg-white/10 dark:text-white/70 dark:ring-white/10">
                    <div class="mb-1 font-semibold">Catatan penting</div>
                    <ul class="space-y-1">
                        <li>• Filter <span class="font-semibold">Semua Rekening</span> menampilkan gabungan tanpa double count mutasi internal.</li>
                        <li>• Filter <span class="font-semibold">Kas Kecil</span> fokus ke modal dan mutasi kas kecil.</li>
                        <li>• Filter <span class="font-semibold">Kas Bank</span> menampilkan bank gabungan.</li>
                    </ul>
                </div>
            </div>

            @if($isMinus)
                <div class="mt-3 inline-flex items-start gap-2 rounded-xl bg-error-50 px-3 py-2 text-xs font-medium text-error-700 ring-1 ring-error-200 dark:bg-error-500/10 dark:text-error-200 dark:ring-error-900/30">
                    <svg class="mt-0.5 size-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"/>
                    </svg>
                    <div>
                        <div class="font-semibold">Saldo akhir sedang minus.</div>
                        <div class="font-normal">
                            Artinya pada filter aktif, arus keluar lebih besar daripada arus masuk.
                        </div>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>

@if(empty($isPrint))
<div class="mb-6 rounded-2xl border border-gray-200 bg-white p-5 dark:border-gray-800 dark:bg-white/[0.03]">
    <form method="GET" class="grid grid-cols-1 items-end gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <div class="w-full">
            <x-form.date-picker name="start_date" label="Dari Tanggal" placeholder="Pilih tanggal" :defaultDate="$startDate" />
        </div>

        <div class="w-full">
            <x-form.date-picker name="end_date" label="Sampai Tanggal" placeholder="Pilih tanggal" :defaultDate="$endDate" />
        </div>

        <div class="w-full">
            <label class="mb-1.5 block text-sm font-medium text-gray-700 dark:text-gray-400">Rekening</label>
            <select name="payment_account_id"
                class="h-10 w-full rounded-lg border border-gray-300 bg-transparent px-3 py-2 text-sm text-gray-800 focus:border-brand-300 focus:outline-none focus:ring focus:ring-brand-200 focus:ring-opacity-40 dark:border-gray-700 dark:bg-gray-900 dark:text-white/90 dark:focus:border-brand-800">
                <option value="">Semua Rekening</option>
                @foreach($accountsCol as $acc)
                    <option value="{{ data_get($acc, 'id') }}" {{ (string) request('payment_account_id') === (string) data_get($acc, 'id') ? 'selected' : '' }}>
                        {{ data_get($acc, 'name') }}
                    </option>
                @endforeach
            </select>
        </div>

        <div class="flex w-full gap-2">
            <button type="submit" class="h-11 flex-1 rounded-lg bg-brand-500 px-5 text-sm font-medium text-white hover:bg-brand-600">
                Filter
            </button>
            <a href="{{ url()->current() }}" class="h-11 flex items-center justify-center rounded-lg border border-gray-300 px-4 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-300">
                Reset
            </a>
        </div>
    </form>
</div>
@endif

<div class="overflow-x-auto rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
    <table class="w-full">
        <thead>
            <tr class="border-b border-gray-200 bg-gray-50 dark:border-gray-800 dark:bg-gray-900/50">
                <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Tanggal</th>
                <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Keterangan</th>
                <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Customer</th>
                <th class="px-5 py-3 text-left text-xs font-semibold uppercase text-gray-500">Rekening</th>
                <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Debit</th>
                <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Kredit</th>
                <th class="px-5 py-3 text-right text-xs font-semibold uppercase text-gray-500">Saldo</th>
            </tr>
        </thead>

        <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
            <tr class="bg-gray-100 font-semibold dark:bg-gray-800/60">
                <td colspan="6" class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">Saldo Awal</td>
                <td class="px-5 py-4 text-right text-sm font-bold text-brand-600 dark:text-brand-400">
                    Rp {{ number_format($saldoAwal ?? 0, 0, ',', '.') }}
                </td>
            </tr>

            @forelse($transactionsCol as $trx)
                @php
                    $debit = (float) ($trx['debit'] ?? 0);
                    $kredit = (float) ($trx['kredit'] ?? 0);
                    $saldo = (float) ($trx['saldo'] ?? 0);
                    $tanggal = $trx['tanggal'] ?? null;
                @endphp
                <tr class="hover:bg-gray-50 dark:hover:bg-white/[0.02]">
                    <td class="px-5 py-4 text-sm text-gray-500">
                        {{ $tanggal ? \Carbon\Carbon::parse($tanggal)->format('d/m/Y H:i') : '-' }}
                    </td>
                    <td class="px-5 py-4 text-sm text-gray-800 dark:text-white/90">
                        {{ $trx['keterangan'] ?? '-' }}
                    </td>
                    <td class="px-5 py-4 text-sm text-gray-600 dark:text-gray-400">
                        {{ $trx['customer'] ?? '-' }}
                    </td>
                    <td class="px-5 py-4 text-sm text-gray-600 dark:text-gray-400">
                        {{ $trx['rekening'] ?? '-' }}
                    </td>
                    <td class="px-5 py-4 text-right text-sm font-semibold text-success-600 dark:text-success-400">
                        {{ $debit > 0 ? 'Rp ' . number_format($debit, 0, ',', '.') : '-' }}
                    </td>
                    <td class="px-5 py-4 text-right text-sm font-semibold text-error-600 dark:text-error-400">
                        {{ $kredit > 0 ? 'Rp ' . number_format($kredit, 0, ',', '.') : '-' }}
                    </td>
                    <td class="px-5 py-4 text-right text-sm font-bold {{ $saldo < 0 ? 'text-error-600 dark:text-error-400' : 'text-gray-800 dark:text-white/90' }}">
                        Rp {{ number_format($saldo, 0, ',', '.') }}
                    </td>
                </tr>
            @empty
                <tr>
                    <td colspan="7" class="px-5 py-12 text-center text-sm text-gray-500">
                        Tidak ada data pada filter ini.
                    </td>
                </tr>
            @endforelse
        </tbody>

        <tfoot class="border-t-2 border-gray-300 bg-gray-50 dark:border-gray-700 dark:bg-gray-900/50">
            <tr>
                <td colspan="4" class="px-5 py-4 text-sm font-semibold text-gray-800 dark:text-white/90">
                    {{ $isSingleDay ? 'Total Hari Ini' : 'Total Periode' }}
                </td>
                <td class="px-5 py-4 text-right text-sm font-bold text-success-600 dark:text-success-400">
                    Rp {{ number_format($totalDebit ?? 0, 0, ',', '.') }}
                </td>
                <td class="px-5 py-4 text-right text-sm font-bold text-error-600 dark:text-error-400">
                    Rp {{ number_format($totalKredit ?? 0, 0, ',', '.') }}
                </td>
                <td class="px-5 py-4 text-right text-base font-bold {{ ($saldoAkhir ?? 0) < 0 ? 'text-error-600 dark:text-error-400' : 'text-brand-600 dark:text-brand-400' }}">
                    Rp {{ number_format($saldoAkhir ?? 0, 0, ',', '.') }}
                </td>
            </tr>
        </tfoot>
    </table>
</div>

<div class="mt-12 border-t border-gray-200 pt-6 text-center text-xs text-gray-500 dark:border-gray-800 dark:text-gray-400">
    <p>
        © {{ date('Y') }} <span class="font-semibold text-gray-700 dark:text-gray-300">Rio Ardiansyah - aplikasipercetakan.com</span>.
        All rights reserved.
    </p>
</div>

@if(!empty($isPrint))
<script>
    window.addEventListener('load', function () {
        window.print();
    });
</script>
@endif

@endsection