@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';
    $isClosed = ($overview['status'] ?? 'open') === 'closed';
@endphp

<div class="admin-page-header d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
    <div>
        <h1>Day Ledger</h1>
        <p class="admin-page-subtitle mb-0">Daily financial reconciliation for collections, expenses and refunds.</p>
    </div>
    <div class="d-flex gap-2">
        <a href="{{ route('admin.reports.day-ledger.export-pdf', request()->query()) }}" class="admin-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="btn btn-outline-secondary">
            Monthly Summary
        </a>
        <a href="{{ route('admin.reports.day-ledger.payment-mode-summary', ['date' => $activeDate, 'order_type' => $activeOrderType]) }}" class="btn btn-outline-secondary">
            Payment Mode Summary
        </a>
    </div>
</div>

<div class="admin-card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="admin-form-label">Date</label>
                <input type="date" name="date" class="admin-form-control form-control" value="{{ $activeDate }}" required>
            </div>
            <div class="col-md-3">
                <label class="admin-form-label">Payment Mode</label>
                <select name="payment_mode" class="admin-form-control form-select">
                    <option value="">All</option>
                    @foreach($paymentModes as $mode)
                        <option value="{{ $mode }}" @selected($activePaymentMode === $mode)>{{ $paymentModeLabels[$mode] ?? $mode }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3">
                <label class="admin-form-label">Order Type</label>
                <select name="order_type" class="admin-form-control form-select">
                    @foreach($orderTypes as $value => $label)
                        <option value="{{ $value }}" @selected($activeOrderType === $value)>{{ $label }}</option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
                <button type="submit" class="admin-btn-primary flex-grow-1">
                    <i class="bi bi-funnel"></i> Apply
                </button>
                <a href="{{ route('admin.reports.day-ledger') }}" class="btn btn-outline-secondary" title="Reset">
                    <i class="bi bi-arrow-clockwise"></i>
                </a>
            </div>
        </form>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['opening_balance'], 2) }}</div>
                <div class="kpi-card-label">Opening (Cash in Counter)</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['total_sales'], 2) }}</div>
                <div class="kpi-card-label">Sales (Gross)</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['total_collection'], 2) }}</div>
                <div class="kpi-card-label">Collection</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['total_expense'], 2) }}</div>
                <div class="kpi-card-label">Expense</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['total_refund'], 2) }}</div>
                <div class="kpi-card-label">Refund</div>
            </div>
        </div>
    </div>
    <div class="col-6 col-md-4 col-lg-2">
        <div class="kpi-card">
            <div class="kpi-card-content-wrapper">
                <div class="kpi-card-value">Rs {{ number_format($overview['closing_balance'], 2) }}</div>
                <div class="kpi-card-label">Closing (Cash in Counter)</div>
            </div>
        </div>
    </div>
</div>

<div class="row g-4">
    <div class="col-lg-7">
        <div class="admin-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Payment Mode Breakdown</h5>
                <span class="badge {{ $isClosed ? 'bg-danger' : 'bg-success' }}">{{ strtoupper($overview['status']) }}</span>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="admin-table table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>Mode</th>
                                <th class="text-end text-nowrap">Collection</th>
                                <th class="text-end text-nowrap">Expense</th>
                                <th class="text-end text-nowrap">Refund</th>
                                <th class="text-end text-nowrap">Cash to Bank</th>
                                <th class="text-end text-nowrap">Net</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($overview['payment_breakdown'] as $row)
                                <tr>
                                    <td>{{ $paymentModeLabels[$row['payment_mode']] ?? $row['payment_mode'] }}</td>
                                    <td class="text-end text-nowrap">Rs {{ number_format($row['collection'], 2) }}</td>
                                    <td class="text-end text-nowrap">Rs {{ number_format($row['expense'], 2) }}</td>
                                    <td class="text-end text-nowrap">Rs {{ number_format($row['refund'], 2) }}</td>
                                    <td class="text-end text-nowrap">Rs {{ number_format($row['transfer'], 2) }}</td>
                                    <td class="text-end fw-semibold text-nowrap">Rs {{ number_format($row['net'], 2) }}</td>
                                </tr>
                            @empty
                                <tr><td colspan="6" class="text-center text-muted py-3">No rows found</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="admin-card h-100">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Manual Entries & Day Closing</h5>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-primary btn-sm" 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 }}">
                            <button type="submit" class="btn btn-warning btn-sm">
                                <i class="bi bi-unlock"></i> Reopen Day
                            </button>
                        </form>
                    @endif
                </div>
            </div>
            <div class="card-body">
                <p class="text-muted mb-0">
                    Cash Formula: Closing = Opening + Cash Collection - Cash Expense - Cash Refund - Cash to Bank
                </p>
                <p class="text-muted mb-0 mt-1">
                    Card/UPI and Offline collections are bank-direct and not carried as next-day opening.
                </p>
                <p class="text-muted mb-0 mt-1">
                    Cash to Bank: Rs {{ number_format($overview['cash_to_bank_transfer'] ?? 0, 2) }}
                </p>
                @if(!$isClosed)
                    <form method="POST" action="{{ route('admin.reports.day-ledger.close') }}" class="mt-3 row g-2 align-items-end">
                        @csrf
                        <input type="hidden" name="date" value="{{ $activeDate }}">
                        @if($overview['requires_opening_balance_input'])
                            <div class="col-sm-6">
                                <label class="form-label mb-1">Opening Balance (first day)</label>
                                <input
                                    type="number"
                                    name="opening_balance"
                                    class="form-control"
                                    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
                        <div class="col-sm-6">
                            <button type="submit" class="btn btn-danger w-100">
                                <i class="bi bi-lock"></i> Close Day
                            </button>
                        </div>
                    </form>
                @endif
            </div>
        </div>
    </div>
</div>

<div class="admin-card mt-4">
    <div class="card-header">
        <h5 class="mb-0">Detailed Transactions</h5>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="admin-table table table-hover">
                <thead>
                    <tr>
                        <th>Date/Time</th>
                        <th>Ref</th>
                        <th>Type</th>
                        <th>Payment Mode</th>
                        <th>Order Type</th>
                        <th class="text-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="text-end">Rs {{ number_format($row['amount'], 2) }}</td>
                            <td>{{ $row['notes'] ?? '-' }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="7" class="text-center text-muted py-3">No transactions found</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<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="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="admin-btn-primary">Save Entry</button>
            </div>
        </form>
    </div>
</div>
@endsection
