@extends('layouts.app')
@section('title','Cash Closing')

@push('styles')
<style>
.cash-closing-filter-row {
    display: grid;
    grid-template-columns: minmax(220px, 1fr) minmax(170px, 220px) auto;
    align-items: end;
    gap: 10px;
}

.cash-closing-dialog {
    position: fixed;
    top: 50%;
    left: 50%;
    width: min(480px, calc(100vw - 24px));
    max-width: 480px;
    max-height: calc(100dvh - 24px);
    margin: 0;
    padding: 0;
    overflow: auto;
    transform: translate(-50%, -50%);
}

.cash-closing-dialog .mf-input,
.cash-closing-dialog .mf-textarea {
    width: 100%;
    border: 1px solid var(--border);
    border-radius: calc(var(--radius) - 2px);
    background: var(--background);
    color: var(--foreground);
    outline: none;
    transition: border-color .15s ease, box-shadow .15s ease;
}

.cash-closing-dialog .mf-textarea {
    min-height: 88px;
    padding: 9px 12px;
    font-size: .875rem;
    line-height: 1.4;
    resize: vertical;
}

.cash-closing-dialog .mf-input:focus,
.cash-closing-dialog .mf-textarea:focus {
    border-color: var(--ring);
    box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 18%, transparent);
}

.cash-closing-dialog::backdrop {
    background: rgb(15 23 42 / .48);
    backdrop-filter: blur(2px);
}

@media (max-width: 720px) {
    .cash-closing-filter-row {
        grid-template-columns: 1fr;
    }

    .cash-closing-filter-row .mf-btn {
        width: 100%;
    }
}
</style>
@endpush

@section('content')
<x-ui.page-toolbar
    title="Cash Closing"
    description="Reconcile every branch money account, prepare the branch day and review previous closings."
    :breadcrumbs="[['label'=>'Dashboard','url'=>route('dashboard')],['label'=>'Cash Closing']]"
>
    @if($preview['closing'])
        <x-slot:actions>
            <a class="mf-btn" href="{{ route('cash-closing.show',$preview['closing']) }}">Open closing</a>
        </x-slot:actions>
    @endif
</x-ui.page-toolbar>

<form method="GET" class="mf-card mf-card-body mb-6">
    <div class="cash-closing-filter-row">
        <div>
            <label class="mf-field-label" for="cash_closing_branch">Branch</label>
            <select id="cash_closing_branch" class="mf-select w-full" name="branch_id">
                @foreach($branches as $item)
                    <option value="{{ $item->id }}" @selected($branch->id===$item->id)>{{ $item->name }}</option>
                @endforeach
            </select>
        </div>

        <div>
            <label class="mf-field-label" for="cash_closing_date">Closing date</label>
            <input id="cash_closing_date" class="mf-input w-full" type="date" name="date" value="{{ $preview['date']->toDateString() }}">
        </div>

        <button class="mf-btn mf-btn-primary" type="submit">Load branch day</button>
    </div>
</form>

<div class="grid gap-3 md:grid-cols-2 xl:grid-cols-4 mb-6">
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Opening funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$preview['summary']['opening_funds'],2) }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Closing funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$preview['summary']['closing_funds'],2) }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Expected account funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$preview['summary']['expected_cash'],2) }}</div>
    </div>
    <div class="mf-card mf-card-body">
        <div class="text-xs text-muted-foreground">Reconciled account funds</div>
        <div class="mt-1 text-xl font-semibold">{{ number_format((float)$preview['summary']['actual_cash'],2) }}</div>
        <div class="mt-1 text-xs {{ (float)$preview['summary']['variance']===0.0?'text-muted-foreground':'text-destructive font-medium' }}">
            Variance {{ number_format((float)$preview['summary']['variance'],2) }}
        </div>
    </div>
</div>

<div class="mf-card mb-6">
    <div class="mf-card-body flex flex-wrap items-start justify-between gap-3 border-b">
        <div>
            <h2 class="text-sm font-semibold">Branch money accounts</h2>
            <p class="mt-1 text-xs text-muted-foreground">Reconcile every financial account that can hold branch funds, including cash, safes, bank, mobile money, collection and other configured accounts.</p>
        </div>
        @if($preview['closing'])
            <span class="mf-badge {{ $preview['closing']->status==='confirmed'?'mf-badge-success':'mf-badge-warning' }}">{{ ucfirst($preview['closing']->status) }}</span>
        @endif
    </div>

    <div class="mf-table-frame border-0">
        <table class="mf-table" data-standard-table>
            <thead>
                <tr>
                    <th>Account</th>
                    <th>Opening</th>
                    <th>Money in</th>
                    <th>Money out</th>
                    <th>Expected balance</th>
                    <th>Last reconciliation</th>
                    <th>Variance</th>
                    <th class="text-right">Action</th>
                </tr>
            </thead>
            <tbody>
            @forelse($preview['accounts'] as $row)
                @php($rec=$row['reconciliation'])
                <tr>
                    <td>
                        <div class="font-medium">{{ $row['account']->name }}</div>
                        <div class="text-xs text-muted-foreground">{{ str($row['account']->account_type)->replace('_',' ')->title() }}</div>
                    </td>
                    <td>{{ number_format((float)$row['opening_cash'],2) }}</td>
                    <td>{{ number_format((float)$row['cash_in'],2) }}</td>
                    <td>{{ number_format((float)$row['cash_out'],2) }}</td>
                    <td class="font-medium">{{ number_format((float)$row['expected_cash'],2) }}</td>
                    <td>
                        @if($rec)
                            <div>{{ number_format((float)$rec->physical_cash,2) }}</div>
                            <div class="text-xs text-muted-foreground">v{{ $rec->version }} · {{ $rec->reconciler?->name ?? '—' }}</div>
                        @else
                            <span class="text-muted-foreground">Not reconciled</span>
                        @endif
                    </td>
                    <td>
                        @if($rec)
                            <div class="{{ (float)$rec->variance!==0.0?'text-destructive font-semibold':'' }}">{{ number_format((float)$rec->variance,2) }}</div>
                            <span class="mf-badge {{ $row['stale']?'mf-badge-danger':'mf-badge-success' }} mt-1">{{ $row['stale']?'Reconciliation required':'Current' }}</span>
                        @else
                            <span class="text-muted-foreground">—</span>
                        @endif
                    </td>
                    <td class="text-right whitespace-nowrap">
                        @if(auth()->user()->can('cash-reconciliation.perform') && (!$preview['closing'] || $preview['closing']->status!=='confirmed'))
                            <button
                                type="button"
                                class="mf-btn mf-btn-sm {{ $rec ? '' : 'mf-btn-primary' }}"
                                onclick="document.getElementById('reconcile-{{ $row['account']->id }}').showModal()"
                            >{{ $rec?'Reconcile again':'Reconcile' }}</button>
                        @else
                            <span class="text-xs text-muted-foreground">{{ $preview['closing']?->status==='confirmed'?'Books closed':'Read only' }}</span>
                        @endif
                    </td>
                </tr>
            @empty
                <tr><td colspan="8" class="text-center text-muted-foreground">No branch financial accounts exist for this day.</td></tr>
            @endforelse
            </tbody>
        </table>
    </div>
</div>

@foreach($preview['accounts'] as $row)
    @php($rec=$row['reconciliation'])
    @php($accountType=$row['account']->account_type)
    @php($actualLabel=in_array($accountType,['cash','petty_cash','safe'],true)?'Physical cash counted':($accountType==='bank'?'Bank balance':($accountType==='mobile_money'?'Mobile money balance':'Actual account balance')))
    @if(auth()->user()->can('cash-reconciliation.perform') && (!$preview['closing'] || $preview['closing']->status!=='confirmed'))
        <dialog id="reconcile-{{ $row['account']->id }}" class="cash-closing-dialog mf-card">
            <div class="mf-card-body flex items-start justify-between gap-3 border-b">
                <div>
                    <h2 class="text-sm font-semibold">{{ $rec ? 'Reconcile account again' : 'Reconcile account' }}</h2>
                    <p class="mt-1 text-xs text-muted-foreground">{{ $row['account']->name }} · {{ str($accountType)->replace('_',' ')->title() }} · Expected {{ number_format((float)$row['expected_cash'],2) }}</p>
                </div>
                <button type="button" class="mf-btn mf-btn-sm" onclick="this.closest('dialog').close()" aria-label="Close">Close</button>
            </div>

            <form method="POST" action="{{ route('cash-closing.reconcile') }}" class="mf-card-body space-y-3">
                @csrf
                <input type="hidden" name="branch_id" value="{{ $branch->id }}">
                <input type="hidden" name="financial_account_id" value="{{ $row['account']->id }}">
                <input type="hidden" name="date" value="{{ $preview['date']->toDateString() }}">

                <div>
                    <label class="mf-field-label" for="actual_balance_{{ $row['account']->id }}">{{ $actualLabel }}</label>
                    <input
                        id="actual_balance_{{ $row['account']->id }}"
                        class="mf-input w-full"
                        name="actual_balance"
                        inputmode="decimal"
                        value="{{ old('financial_account_id')==$row['account']->id?old('actual_balance'):($rec?number_format((float)$rec->physical_cash,2,'.',''):'') }}"
                        placeholder="0.00"
                        required
                    >
                    <p class="mf-field-help">Enter the independently verified balance for this account as of the selected closing date.</p>
                </div>

                <div>
                    <label class="mf-field-label" for="variance_explanation_{{ $row['account']->id }}">Variance explanation</label>
                    <textarea
                        id="variance_explanation_{{ $row['account']->id }}"
                        class="mf-textarea w-full"
                        name="variance_explanation"
                        rows="3"
                        placeholder="Required when the reconciled balance differs from the expected balance"
                    >{{ old('financial_account_id')==$row['account']->id?old('variance_explanation'):($rec?->variance_explanation ?? '') }}</textarea>
                </div>

                <div class="flex justify-end gap-2 border-t pt-3">
                    <button type="button" class="mf-btn" onclick="this.closest('dialog').close()">Cancel</button>
                    <button class="mf-btn mf-btn-primary" type="submit">{{ $rec?'Save new version':'Save reconciliation' }}</button>
                </div>
            </form>
        </dialog>
    @endif
@endforeach

<div class="mf-card mb-6">
    <div class="mf-card-body flex flex-wrap items-center justify-between gap-3">
        <div>
            <h2 class="text-sm font-semibold">End-of-day closing</h2>
            <p class="mt-1 text-xs text-muted-foreground">All branch money accounts must be reconciled and current before the ledger snapshot can be prepared for manager confirmation.</p>
        </div>
        <div class="flex flex-wrap gap-2">
            @if($preview['closing'])
                <a class="mf-btn" href="{{ route('cash-closing.show',$preview['closing']) }}">Review closing</a>
            @endif
            @if(auth()->user()->can('daily-closing.prepare') && (!$preview['closing'] || $preview['closing']->status!=='confirmed'))
                <form method="POST" action="{{ route('cash-closing.prepare') }}">
                    @csrf
                    <input type="hidden" name="branch_id" value="{{ $branch->id }}">
                    <input type="hidden" name="date" value="{{ $preview['date']->toDateString() }}">
                    <button class="mf-btn mf-btn-primary">{{ $preview['closing']?'Refresh closing':'Prepare closing' }}</button>
                </form>
            @endif
        </div>
    </div>
</div>

<div class="mf-card mb-6">
    <div class="mf-card-body border-b">
        <h2 class="text-sm font-semibold">Closing history</h2>
        <p class="mt-1 text-xs text-muted-foreground">Prepared and manager-confirmed branch snapshots.</p>
    </div>

    <div class="mf-table-frame border-0">
        <table id="closing-history-table" class="mf-table" data-standard-table>
            <thead>
                <tr>
                    <th>Closing</th>
                    <th>Date</th>
                    <th>Branch</th>
                    <th>Opening funds</th>
                    <th>Closing funds</th>
                    <th>Expected funds</th>
                    <th>Reconciled funds</th>
                    <th>Variance</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            @forelse($history as $item)
                <tr>
                    <td class="font-medium">{{ $item->closing_number }}</td>
                    <td>{{ $item->closing_date->format('d M Y') }}</td>
                    <td>{{ $item->branch->name }}</td>
                    <td>{{ number_format((float)$item->opening_funds,2) }}</td>
                    <td>{{ number_format((float)$item->closing_funds,2) }}</td>
                    <td>{{ number_format((float)$item->expected_cash,2) }}</td>
                    <td>{{ number_format((float)$item->actual_cash,2) }}</td>
                    <td class="{{ (float)$item->variance!==0.0?'text-destructive font-semibold':'' }}">{{ number_format((float)$item->variance,2) }}</td>
                    <td><span class="mf-badge {{ $item->status==='confirmed'?'mf-badge-success':'mf-badge-warning' }}">{{ ucfirst($item->status) }}</span></td>
                    <td class="text-right"><a class="mf-btn mf-btn-sm" href="{{ route('cash-closing.show',$item) }}">Open</a></td>
                </tr>
            @empty
                <tr><td colspan="10" class="text-center text-muted-foreground">No daily closings have been prepared yet.</td></tr>
            @endforelse
            </tbody>
        </table>
    </div>
</div>
<div>{{ $history->links() }}</div>
@endsection
