@extends('layouts.master')

@push('css')
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        /* ── Ledger Table Styles ── */
        .ledger-wrap {
            direction: rtl;
            font-family: 'Noto Nastaliq Urdu', 'Cairo', serif;
        }
        .ledger-company {
            text-align: center;
            margin-bottom: 10px;
        }
        .ledger-company .co-name {
            font-size: 22px;
            font-weight: 700;
            letter-spacing: 2px;
        }
        .ledger-company .co-sub {
            font-size: 15px;
            color: #333;
        }
        .ledger-khata-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            font-size: 14px;
            font-weight: 600;
        }
        .ledger-table {
            width: 100%;
            border-collapse: collapse;
            direction: rtl;
            font-size: 13.5px;
        }
        .ledger-table thead th {
            border: 1px solid #999;
            padding: 9px 12px;
            text-align: center;
            background: #fff;
            font-weight: 700;
            font-size: 14px;
            color: #000;
            white-space: nowrap;
        }
        .ledger-table tbody td {
            border-left: 1px solid #bbb;
            border-right: 1px solid #bbb;
            border-top: none;
            border-bottom: 1px dashed #aaa;
            padding: 9px 12px;
            vertical-align: middle;
        }
        .ledger-table td.col-date    { text-align: center; white-space: nowrap; width: 90px; }
        .ledger-table td.col-detail  { text-align: right; font-weight: 600; font-size: 14px; }
        .ledger-table td.col-amount  { text-align: center; white-space: nowrap; width: 120px; }
        .ledger-table td.col-balance { text-align: center; font-weight: 700; white-space: nowrap; width: 130px; }
        .ledger-table td.col-drcr    { text-align: center; font-weight: 700; font-size: 12px; width: 40px; }
        .ledger-table tr.opening-row td {
            text-align: center !important;
            font-weight: 700;
            font-size: 14px;
            background: #fafafa;
        }
        .ledger-table tr.total-row td {
            border-top: 2px solid #888 !important;
            background: #f0f0f0;
            font-weight: 700;
            text-align: center;
            font-size: 13px;
            padding: 8px 12px;
        }
        /* Badge colours for type indicator */
        .badge-supplier { background: #6c757d; }
        .badge-customer { background: #0d6efd; }
    </style>
@endpush

@section('content')

    {{-- ════════ FILTER CARD ════════ --}}
    <div class="card">
        <div class="card-header">
            <h3>General Ledger</h3>
        </div>
        <div class="card-body">

            @if ($errors->any())
                <div style="border:1px solid red; padding:10px; margin-bottom:20px; background-color:#fdd;">
                    <strong>Errors:</strong>
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form id="filterForm" class="row" method="GET" action="{{ route('general-ledger.index') }}">

                <div class="row">

                    {{-- From Date --}}
                    <div class="col-md-3">
                        <div class="form-group mt-3">
                            <label for="from_date">از تاریخ (From Date)</label>
                            <input type="date" name="from_date" id="from_date"
                                   class="date form-control"
                                   value="{{ request('from_date') }}">
                        </div>
                    </div>

                    {{-- To Date --}}
                    <div class="col-md-3">
                        <div class="form-group mt-3">
                            <label for="to_date">تا تاریخ (To Date)</label>
                            <input type="date" name="to_date" id="to_date"
                                   class="date form-control"
                                   value="{{ request('to_date') }}">
                        </div>
                    </div>

                    {{-- Khata Select (Suppliers + Customers) --}}
                    <div class="col-md-6">
                        <div class="form-group mt-3">
                            <label for="khata">
                                کھاتہ منتخب کریں
                                <small class="text-muted">&nbsp;(S) = سپلائر &nbsp;|&nbsp; (C) = کسٹمر</small>
                            </label>
                            <select id="khata" name="khata" class="form-control select2" required>
                                <option value="">— کھاتہ منتخب کریں —</option>

                                <optgroup label="━━ سپلائرز (Suppliers) ━━">
                                    @foreach($khataList as $kid => $kname)
                                        @if(str_starts_with($kid, 'S_'))
                                            <option value="{{ $kid }}"
                                                {{ $selectedKhata === $kid ? 'selected' : '' }}>
                                                {{ $kname }}
                                            </option>
                                        @endif
                                    @endforeach
                                </optgroup>

                                <optgroup label="━━ کسٹمرز (Customers) ━━">
                                    @foreach($khataList as $kid => $kname)
                                        @if(str_starts_with($kid, 'C_'))
                                            <option value="{{ $kid }}"
                                                {{ $selectedKhata === $kid ? 'selected' : '' }}>
                                                {{ $kname }}
                                            </option>
                                        @endif
                                    @endforeach
                                </optgroup>

                            </select>
                        </div>
                    </div>

                </div>{{-- .row --}}

                <div class="row mt-4">
                    <div class="col-md-12 text-center">
                        <button type="submit" class="btn btn-primary">
                            <i class="fa fa-search"></i> دیکھیں
                        </button>
                        @if($ledgerData !== null)
                            &nbsp;
                            <a href="{{ route('general-ledger.print', ['khata' => $selectedKhata, 'from_date' => $fromDate, 'to_date' => $toDate]) }}"
                               target="_blank" class="btn btn-warning">
                                <i class="fa fa-print"></i> پرنٹ
                            </a>
                        @endif
                    </div>
                </div>

            </form>

            <hr />

            {{-- ════════ LEDGER RESULT ════════ --}}
            @if($ledgerData !== null)

                @if(count($ledgerData) <= 1)
                    <div class="alert alert-info text-center">
                        اس کھاتے کے لیے کوئی اندراج نہیں ملا۔
                    </div>
                @else

                    {{-- Khata type indicator --}}
                    <div class="mb-2 text-center">
                        @if($khataType === 'customer')
                            <span class="badge bg-primary px-3 py-2" style="font-size:13px">
                                <i class="fa fa-user"></i> کسٹمر کھاتہ (Customer Ledger)
                            </span>
                        @else
                            <span class="badge bg-secondary px-3 py-2" style="font-size:13px">
                                <i class="fa fa-truck"></i> سپلائر کھاتہ (Supplier Ledger)
                            </span>
                        @endif
                    </div>

                    {{-- Summary row --}}
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <div class="card border-danger">
                                <div class="card-body py-2 text-center">
                                    <small class="text-muted d-block">کل ڈیبٹ (Total Debit)</small>
                                    <strong class="text-danger fs-5">{{ number_format($totalDebit, 0) }}</strong>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card border-success">
                                <div class="card-body py-2 text-center">
                                    <small class="text-muted d-block">کل کریڈٹ (Total Credit)</small>
                                    <strong class="text-success fs-5">{{ number_format($totalCredit, 0) }}</strong>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card border-primary">
                                <div class="card-body py-2 text-center">
                                    <small class="text-muted d-block">بقایا (Balance)</small>
                                    <strong class="text-primary fs-5">
                                        {{ number_format(abs($totalCredit - $totalDebit), 0) }}
                                        @if($totalCredit != $totalDebit)
                                            <span class="badge {{ ($totalCredit - $totalDebit) > 0 ? 'bg-success' : 'bg-danger' }} ms-1" style="font-size:11px">
                                                {{ ($totalCredit - $totalDebit) > 0 ? 'Cr' : 'Dr' }}
                                            </span>
                                        @endif
                                    </strong>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Ledger Table --}}
                    <div class="ledger-wrap">

                        <div class="ledger-company">
                            <div class="co-name">M.D.S</div>
                            <div class="co-sub">
                                {{ $khataType === 'customer' ? 'Customer Ledger' : 'Supplier Ledger' }}
                            </div>
                        </div>

                        <div class="ledger-khata-row">
                            <div>کھاتہ &nbsp; {{ $khataList[$selectedKhata] ?? $selectedKhata }}</div>
                            <div>کھا تہ رجسٹر</div>
                            <div>کھاتہ کوڈ &nbsp; {{ $selectedKhata }}</div>
                        </div>

                        <table class="ledger-table">
                            <thead>
                                <tr>
                                    <th>تاریخ</th>
                                    <th>تفصیل</th>
                                    <th>ڈ یبٹ رقم</th>
                                    <th>کریڈٹ رقم</th>
                                    <th colspan="2">میزان</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($ledgerData as $row)
                                    @if($row['is_opening'])
                                        {{-- Opening row hidden per original design --}}
                                    @else
                                        <tr>
                                            <td class="col-date">{{ $row['date'] }}</td>
                                            <td class="col-detail">{{ $row['detail'] }}</td>
                                            <td class="col-amount">
                                                {{ $row['debit'] ? number_format($row['debit'], 0) : '' }}
                                            </td>
                                            <td class="col-amount">
                                                {{ $row['credit'] ? number_format($row['credit'], 0) : '' }}
                                            </td>
                                            <td class="col-balance">
                                                {{ number_format($row['balance'], 0) }}
                                            </td>
                                            <td class="col-drcr">{{ $row['dr_cr'] }}</td>
                                        </tr>
                                    @endif
                                @endforeach

                                <tr class="total-row">
                                    <td colspan="2">کُل</td>
                                    <td>{{ number_format($totalDebit,  0) }}</td>
                                    <td>{{ number_format($totalCredit, 0) }}</td>
                                    <td colspan="2"></td>
                                </tr>
                            </tbody>
                        </table>

                    </div>{{-- .ledger-wrap --}}

                @endif

            @endif

        </div>{{-- .card-body --}}
    </div>{{-- .card --}}

@endsection

@push('scripts')
    <script>
        $(document).ready(function () {
            $('.select2').select2();
            $(".date").datepicker({ dateFormat: "yy-mm-dd" });
        });
    </script>
@endpush