@extends('layouts.admin')

@section('title', 'Day Ledger')

@section('content')
@php
    $filters = $overview['filters'] ?? [];
    $activeDate = $overview['date'];
    $activePaymentMode = $filters['payment_mode'] ?? null;
    $activeOrderType = $filters['order_type'] ?? 'all';
    $activeLocationId = $filters['location_id'] ?? null;
    $isClosed = ($overview['status'] ?? 'open') === 'closed';
@endphp

<x-admin.report-page title="Day Ledger" subtitle="Daily financial reconciliation for collections, expenses and refunds.">
    <x-slot:actions>
        <a href="{{ route('admin.reports.day-ledger.export-pdf', request()->query()) }}" class="ci-btn ci-btn--primary">
            <i class="bi bi-file-earmark-pdf"></i> Export PDF
        </a>
        <a href="{{ route('admin.reports.day-ledger.monthly-summary', ['month' => \Carbon\Carbon::parse($activeDate)->format('Y-m')]) }}" class="ci-btn ci-btn--ghost">
            Monthly Summary
        </a>
        <a href="{{ route('admin.reports.day-ledger.payment-mode-summary', ['date' => $activeDate, 'order_type' => $activeOrderType]) }}" class="ci-btn ci-btn--ghost">
            Payment Mode Summary
        </a>
    </x-slot:actions>

    <form method="GET" class="ci-filters ci-filters--report">
        <div class="ci-filters__field">
            <label for="date">Date</label>
            <input type="date" name="date" id="date" value="{{ $activeDate }}" required>
        </div>
        <div class="ci-filters__field">
            <label for="payment_mode">Payment Mode</label>
            <select name="payment_mode" id="payment_mode">
                <option value="">All</option>
                @foreach($paymentModes as $mode)
                    <option value="{{ $mode }}" @selected($activePaymentMode === $mode)>{{ $paymentModeLabels[$mode] ?? $mode }}</option>
                @endforeach
            </select>
        </div>
        <div class="ci-filters__field">
            <label for="order_type">Order Type</label>
            <select name="order_type" id="order_type">
                @foreach($orderTypes as $value => $label)
                    <option value="{{ $value }}" @selected($activeOrderType === $value)>{{ $label }}</option>
                @endforeach
            </select>
        </div>
        <div class="ci-filters__field">
            <label for="location_id">Location</label>
            <select name="location_id" id="location_id">
                @if(!empty($canViewAllShops))
                    <option value="">All / Company</option>
                @endif
                @foreach(($locations ?? []) as $loc)
                    <option value="{{ $loc->id }}" @selected((string)($activeLocationId ?? $locationId ?? '') === (string)$loc->id)>{{ $loc->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="ci-filters__actions">
            <button type="submit" class="ci-btn ci-btn--primary">
                <i class="bi bi-funnel"></i> Apply
            </button>
            <a href="{{ route('admin.reports.day-ledger') }}" class="ci-btn ci-btn--ghost ci-btn--icon" title="Reset">
                <i class="bi bi-arrow-clockwise"></i>
            </a>
        </div>
    </form>

    <div class="ci-stats">
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Opening (Cash in Counter)</p>
                <p class="ci-stat__value ci-stat__value--sm"><span class="ci-money">Rs {{ number_format($overview['opening_balance'], 2) }}</span></p>
            </div>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Sales (Gross)</p>
                <p class="ci-stat__value ci-stat__value--sm"><span class="ci-money">Rs {{ number_format($overview['total_sales'], 2) }}</span></p>
            </div>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Collection</p>
                <p class="ci-stat__value ci-stat__value--sm ci-stat__value--success"><span class="ci-money">Rs {{ number_format($overview['total_collection'], 2) }}</span></p>
            </div>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Expense</p>
                <p class="ci-stat__value ci-stat__value--sm ci-stat__value--warning"><span class="ci-money">Rs {{ number_format($overview['total_expense'], 2) }}</span></p>
            </div>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Refund</p>
                <p class="ci-stat__value ci-stat__value--sm ci-stat__value--danger"><span class="ci-money">Rs {{ number_format($overview['total_refund'], 2) }}</span></p>
            </div>
        </div>
        <div class="ci-stat">
            <div>
                <p class="ci-stat__label">Closing (Cash in Counter)</p>
                <p class="ci-stat__value ci-stat__value--sm"><span class="ci-money">Rs {{ number_format($overview['closing_balance'], 2) }}</span></p>
            </div>
        </div>
    </div>

    <div class="ci-grid-2">
        <div class="ci-section">
            <div class="ci-section__head">
                <h2>Payment Mode Breakdown</h2>
                <span class="ci-pill {{ $isClosed ? 'ci-pill--danger' : 'ci-pill--success' }}">{{ strtoupper($overview['status']) }}</span>
            </div>
            <div class="ci-section__body--flush">
                <div class="ci-table-wrap">
                    <table class="ci-table">
                        <thead>
                            <tr>
                                <th>Mode</th>
                                <th class="ci-end">Collection</th>
                                <th class="ci-end">Expense</th>
                                <th class="ci-end">Refund</th>
                                <th class="ci-end">Cash to Bank</th>
                                <th class="ci-end">Net</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($overview['payment_breakdown'] as $row)
                                <tr>
                                    <td>{{ $paymentModeLabels[$row['payment_mode']] ?? $row['payment_mode'] }}</td>
                                    <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['collection'], 2) }}</span></td>
                                    <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['expense'], 2) }}</span></td>
                                    <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['refund'], 2) }}</span></td>
                                    <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['transfer'], 2) }}</span></td>
                                    <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['net'], 2) }}</span></td>
                                </tr>
                            @empty
                                <tr><td colspan="6" class="text-center ci-muted py-3">No rows found</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="ci-section">
            <div class="ci-section__head">
                <h2>Manual Entries & Day Closing</h2>
                <div class="d-flex gap-2 flex-wrap">
                    <button type="button" class="ci-btn ci-btn--ghost" data-bs-toggle="modal" data-bs-target="#addEntryModal" @disabled($isClosed)>
                        <i class="bi bi-plus-circle"></i> Add Entry
                    </button>
                    @if($isClosed && (auth()->user()->hasRole('super_admin') || auth()->user()->can('reports.day-ledger.reopen')))
                        <form method="POST" action="{{ route('admin.reports.day-ledger.reopen') }}">
                            @csrf
                            <input type="hidden" name="date" value="{{ $activeDate }}">
                            @if($activeLocationId)<input type="hidden" name="location_id" value="{{ $activeLocationId }}">@endif
                            <button type="submit" class="ci-btn ci-btn--ghost" style="border-color:#f59e0b;color:#b45309;">
                                <i class="bi bi-unlock"></i> Reopen Day
                            </button>
                        </form>
                    @endif
                </div>
            </div>
            <div class="ci-section__body">
                <p class="ci-muted" style="margin:0;">
                    Cash Formula: Closing = Opening + Cash Collection - Cash Expense - Cash Refund - Cash to Bank
                </p>
                <p class="ci-muted" style="margin:0.35rem 0 0;">
                    Card/UPI and Offline collections are bank-direct and not carried as next-day opening.
                </p>
                <p class="ci-muted" style="margin:0.35rem 0 0;">
                    Cash to Bank: <span class="ci-money">Rs {{ number_format($overview['cash_to_bank_transfer'] ?? 0, 2) }}</span>
                </p>
                @if(!$isClosed)
                    <form method="POST" action="{{ route('admin.reports.day-ledger.close') }}" class="mt-3" style="display:flex;flex-wrap:wrap;gap:0.75rem;align-items:flex-end;">
                        @csrf
                        <input type="hidden" name="date" value="{{ $activeDate }}">
                        @if($activeLocationId)<input type="hidden" name="location_id" value="{{ $activeLocationId }}">@endif
                        @if($overview['requires_opening_balance_input'])
                            <div class="ci-filters__field" style="flex:1 1 180px;">
                                <label for="opening_balance">Opening Balance (first day)</label>
                                <input
                                    type="number"
                                    name="opening_balance"
                                    id="opening_balance"
                                    min="0"
                                    step="0.01"
                                    value="{{ old('opening_balance', $overview['opening_balance']) }}"
                                    required
                                >
                            </div>
                        @else
                            <input type="hidden" name="opening_balance" value="{{ $overview['opening_balance'] }}">
                        @endif
                        <button type="submit" class="ci-btn ci-btn--danger-outline">
                            <i class="bi bi-lock"></i> Close Day
                        </button>
                    </form>
                @endif
            </div>
        </div>
    </div>

    <div class="ci-table-card" style="margin-top:1rem;">
        <div class="ci-section__head">
            <h2>Detailed Transactions</h2>
        </div>
        <div class="ci-table-wrap">
            <table class="ci-table">
                <thead>
                    <tr>
                        <th>Date/Time</th>
                        <th>Ref</th>
                        <th>Type</th>
                        <th>Payment Mode</th>
                        <th>Order Type</th>
                        <th class="ci-end">Amount</th>
                        <th>Notes</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($overview['transactions'] as $row)
                        <tr>
                            <td>{{ $row['datetime'] }}</td>
                            <td>{{ $row['reference'] }}</td>
                            <td>{{ ucwords(str_replace('_', ' ', $row['entry_type'])) }}</td>
                            <td>{{ $paymentModeLabels[$row['payment_mode']] ?? $row['payment_mode'] }}</td>
                            <td>{{ strtoupper($row['order_type']) }}</td>
                            <td class="ci-end"><span class="ci-money">Rs {{ number_format($row['amount'], 2) }}</span></td>
                            <td>{{ $row['notes'] ?? '-' }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="7" class="text-center ci-muted py-3">No transactions found</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</x-admin.report-page>

<div class="modal fade mt-5" id="addEntryModal" tabindex="-1" aria-labelledby="addEntryModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" action="{{ route('admin.reports.day-ledger.entries.store') }}" class="modal-content">
            @csrf
            <div class="modal-header">
                <h5 class="modal-title" id="addEntryModalLabel">Add Manual Entry</h5>
                <button type="button" class="btn p-0 text-white" data-bs-dismiss="modal" aria-label="Close"><i class="bi-x-lg"></i></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="ledger_date" value="{{ $activeDate }}">
                <div class="mb-3">
                    <label class="form-label">Entry Type</label>
                    <select name="entry_type" class="form-select" required>
                        <option value="expense">Expense</option>
                        <option value="refund">Refund</option>
                        <option value="advance">Advance Received</option>
                        <option value="adjustment">Adjustment</option>
                        <option value="cash_to_bank">Cash to Bank</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Payment Mode</label>
                    <select name="payment_mode" class="form-select" required>
                        @foreach($paymentModes as $mode)
                            <option value="{{ $mode }}">{{ $paymentModeLabels[$mode] ?? $mode }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Amount</label>
                    <input type="number" name="amount" class="form-control" min="0" step="0.01" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">Remarks</label>
                    <textarea name="remarks" class="form-control" rows="3" placeholder="Optional notes"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="ci-btn ci-btn--ghost" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="ci-btn ci-btn--primary">Save Entry</button>
            </div>
        </form>
    </div>
</div>
@endsection
