<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>{{ $data['broker']->name }} Ledger</title>
    <style>
        body {
            font-family: 'Noto Nastaliq Urdu', 'Jameel Noori Nastaleeq', 'Arial', sans-serif;
            direction: rtl;
        }
        .table, .tcell, .thead {
            text-align: center;
            border: 1px solid black;
        }
        .table {
            width: 100%;
            border-collapse: collapse;
        }
        .clickable-particular {
            cursor: pointer;
            color: blue;
            text-decoration: underline;
        }
        .details-row {
            display: none;
            background-color: #f9f9f9;
        }
        .details-cell {
            text-align: left;
            padding: 10px;
            font-style: italic;
        }
        .positive-balance {
            color: green;
            font-weight: bold;
        }
        .zero-balance {
            color: goldenrod;
            font-weight: bold;
        }
        .negative-balance {
            color: red;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div>
        <table style="width: 100%; margin-bottom: 10px;">
            <tr>
                <td style="width:33.33%; text-align: left"><h4>{{ $business_name->name }}</h4></td>
                <td style="width:33.33%; text-align: center"><strong>Broker Ledger</strong></td>
                <td style="width:33.33%; text-align: right"></td>
            </tr>
        </table>

        <table style="width: 100%; margin-bottom: 10px;">
            <tr>
                <td style="width:33.33%; text-align: left"><h4>{{ $data['broker']->name }}</h4></td>
                <td style="width:33.33%; text-align: center"></td>
                <td style="width:33.33%; text-align: right">
                    <strong>From:</strong> <u>{{ $data['form_date'] }}</u><br />
                    <strong>To:</strong> <u>{{ $data['to_date'] }}</u>
                </td>
            </tr>
        </table>
    </div>

    @php
        $groupedLedgers = [];
        foreach ($data['ledgers'] as $ledger) {
            $tripId = null;
            if (in_array($ledger->ref_type, ['trip_oil', 'broker_reach'])) {
                $tripPayable = \App\Models\TripPayable::find($ledger->ref_id);
                $tripId = $tripPayable->trip_id ?? null;
            } elseif (in_array($ledger->ref_type, ['commission_party','labor','fine','excise_expenditure','dehari','bility_commission', 'b_freight'])) {
                $tripDetail = \App\Models\TripDetail::find($ledger->ref_id);
                $tripId = $tripDetail->trip_id ?? null;
            }
            $groupedLedgers[$tripId ?? 'no_trip'][] = $ledger;
        }

        $total_debit = 0;
        $total_credit = 0;
    @endphp

    <table class="table">
        <thead>
            <tr>
                <th class="thead">Date</th>
                <th class="thead">Particular</th>
                <th class="thead">Vehicle No</th>
                <th class="thead">Debit</th>
                <th class="thead">Credit</th>
                <th class="thead">Balance</th>
            </tr>
        </thead>
        <tbody>
            @foreach ($groupedLedgers as $tripId => $ledgersGroup)
                @php
                    $tripModel = $tripId !== 'no_trip' ? \App\Models\Trip::find($tripId) : null;
                    $tripNo = $tripModel->trip_no ?? $tripId;
                    $vehicleNo = $tripModel && $tripModel->vehicle ? $tripModel->vehicle->vehicle_no : '---';

                    $trip_debit = 0;
                    $trip_credit = 0;
                    $trip_balance = 0;
                @endphp

                @if($tripNo)
                <tr style="background:#ddd;">
                    <td colspan="6" style="text-align:center; font-weight:bold;">
                        Trip No: {{ $tripNo }} | Vehicle: {{ $vehicleNo }}
                    </td>
                </tr>
                @endif

                @foreach ($ledgersGroup as $index => $ledger)
                    @php
                        $trip_balance = ($trip_balance + $ledger->credit) - $ledger->debit;
                        $trip_debit += $ledger->debit;
                        $trip_credit += $ledger->credit;

                        $total_debit += $ledger->debit;
                        $total_credit += $ledger->credit;

                        $tripNoForDesc = null;
                        if (in_array($ledger->ref_type, ['trip_oil', 'broker_reach'])) {
                            $tp = \App\Models\TripPayable::find($ledger->ref_id);
                            $tripTmp = $tp && $tp->trip_id ? \App\Models\Trip::find($tp->trip_id) : null;
                            $tripNoForDesc = $tripTmp->trip_no ?? $tripTmp->id ?? null;
                        } elseif (in_array($ledger->ref_type, ['commission_party', 'b_freight'])) {
                            $td = \App\Models\TripDetail::find($ledger->ref_id);
                            $tripTmp = $td && $td->trip_id ? \App\Models\Trip::find($td->trip_id) : null;
                            $tripNoForDesc = $tripTmp->trip_no ?? $tripTmp->id ?? null;
                        }

                        $rowId = 'details-' . $tripId . '-' . $index;
                    @endphp

                    <tr>
                        <td class="tcell">{{ date('M d, Y', strtotime($ledger->date)) }}</td>
                        <td class="tcell" data-id="{{ $rowId }}" title="Click for more details">
                            {{ $ledger->description }}
                            @if ($tripNoForDesc) (Trip #{{ $tripNoForDesc }}) @endif
                        </td>
                        <td class="tcell">{{ $vehicleNo }}</td>
                        <td class="tcell">{{ number_format($ledger->debit, 0) }}</td>
                        <td class="tcell">{{ number_format($ledger->credit, 0) }}</td>
                        <td class="tcell">{{ number_format($trip_balance, 0) }}</td>
                    </tr>

                    <tr class="details-row" id="{{ $rowId }}">
                        <td colspan="6" class="details-cell">
                            <strong>Description:</strong> {{ $ledger->description }}<br />
                            <strong>Date:</strong> {{ date('d-m-Y', strtotime($ledger->date)) }}<br />
                            <strong>Debit:</strong> {{ number_format($ledger->debit, 2) }} |
                            <strong>Credit:</strong> {{ number_format($ledger->credit, 2) }}<br />
                            <strong>Trip No:</strong> {{ $tripNoForDesc ?? 'N/A' }}<br />
                            <strong>Vehicle:</strong> {{ $vehicleNo }}
                        </td>
                    </tr>
                @endforeach
            @endforeach

            @php
                $overall_balance = $total_credit - $total_debit;
            @endphp
            <tr>
                <th class="tcell" colspan="3" style="text-align: right;">Total:</th>
                <td class="tcell">{{ number_format($total_debit, 0) }}</td>
                <td class="tcell">{{ number_format($total_credit, 0) }}</td>
                <td class="tcell
                    @if($overall_balance == 0) positive-balance
                    @elseif($overall_balance < 0) zero-balance
                    @else negative-balance
                    @endif
                ">
                    {{ number_format($overall_balance, 0) }}
                </td>
            </tr>
        </tbody>
    </table>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            document.querySelectorAll('.clickable-particular').forEach(cell => {
                cell.addEventListener('click', () => {
                    const rowId = cell.getAttribute('data-id');
                    const detailRow = document.getElementById(rowId);
                    detailRow.style.display = detailRow.style.display === 'table-row' ? 'none' : 'table-row';
                });
            });
        });
    </script>
</body>
</html>
