@extends('layouts.master')
@section('title', 'Supplier Statement')

@section('styles')
<style>
.btn-back {
    text-decoration: none;
    color: #1AB9D9;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    padding: 5px 15px;
    border-radius: 6px;
    transition: all 0.3s ease;
}
.btn-back:hover { background-color: rgba(26, 185, 217, 0.1); }
.metric-card {
    padding: 1.1rem;
    border-radius: 0.9rem;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}
.metric-title {
    font-size: 0.78rem;
    font-weight: 700;
    letter-spacing: 0.04em;
    color: #6b7280;
    text-transform: uppercase;
}
.metric-value {
    font-size: 1.35rem;
    font-weight: 700;
    color: #111827;
}
.status-badge {
    padding: 0.2rem 0.65rem;
    border-radius: 9999px;
    font-size: 0.72rem;
    font-weight: 700;
    text-transform: capitalize;
}
.status-pending { background: rgba(251,191,36,0.2); color: #b45309; }
.status-approved { background: rgba(59,130,246,0.15); color: #1d4ed8; }
.status-paid { background: rgba(34,197,94,0.18); color: #15803d; }
.status-rejected { background: rgba(239,68,68,0.15); color: #b91c1c; }
.table thead th {
    font-size: 0.83rem;
    white-space: nowrap;
}
.table td {
    font-size: 0.9rem;
    vertical-align: middle;
}
@media print {
    .no-print, .btn-back, form, .accordion-button::after { display: none !important; }
    .card, .metric-card { box-shadow: none !important; }
    .accordion-button { background: #fff !important; }
}
</style>
@endsection

@section('content')
<div class="container-fluid py-3">
    <div class="d-flex justify-content-end mb-3">
        <a href="{{ route('modules.reports') }}" class="btn-back">
            <i class="fas fa-arrow-left me-2"></i> Back to Reports
        </a>
    </div>

    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white py-3">
            <h5 class="mb-0"><i class="fas fa-file-invoice-dollar me-2"></i> Supplier Statement</h5>
        </div>

        <div class="card-body">
            @if($errors->any())
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            <form action="{{ route('supplierStatement.generate') }}" method="POST" class="row g-3 align-items-end no-print mb-4">
                @csrf
                <div class="col-md-3">
                    <label class="form-label"><strong>Supplier Account</strong></label>
                    <select class="form-control" name="supplier_account" required>
                        <option value="all" {{ (string)$supplierId === 'all' ? 'selected' : '' }}>All Suppliers</option>
                        @foreach($suppliers as $supplier)
                            <option value="{{ $supplier->supplier_id }}" {{ (string)$supplierId === (string)$supplier->supplier_id ? 'selected' : '' }}>
                                {{ $supplier->supplier_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label"><strong>From Date</strong></label>
                    <input type="date" class="form-control" name="date_from" value="{{ $dateFrom }}" required>
                </div>
                <div class="col-md-2">
                    <label class="form-label"><strong>To Date</strong></label>
                    <input type="date" class="form-control" name="date_to" value="{{ $dateTo }}" required>
                </div>
                <div class="col-md-3">
                    <label class="form-label"><strong>Select Currency</strong></label>
                    <select class="form-control" name="currency" required>
                        <option value="" disabled {{ $currencyId ? '' : 'selected' }}>Select Currency</option>
                        @foreach($currencies as $currency)
                            <option value="{{ $currency->currency_id }}" {{ (string)$currencyId === (string)$currency->currency_id ? 'selected' : '' }}>
                                {{ $currency->currency_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 d-grid">
                    <button type="submit" class="btn btn-primary">Generate</button>
                </div>
            </form>

            @if(count($allStatements) > 0)
                <div class="d-flex justify-content-end gap-2 no-print mb-3">
                    <button type="button" class="btn btn-outline-primary" onclick="window.print()">
                        <i class="fas fa-print me-2"></i>Print
                    </button>
                    <form action="{{ route('supplierStatement.downloadPdf') }}" method="POST">
                        @csrf
                        <input type="hidden" name="supplier_account" value="{{ $supplierId }}">
                        <input type="hidden" name="date_from" value="{{ $dateFrom }}">
                        <input type="hidden" name="date_to" value="{{ $dateTo }}">
                        <input type="hidden" name="currency" value="{{ $currencyId }}">
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-file-pdf me-2"></i>Download PDF
                        </button>
                    </form>
                </div>

                <div class="accordion" id="supplierStatementAccordion">
                    @foreach($allStatements as $idx => $statement)
                        @php
                            $supplier = $statement['supplier'];
                            $metrics = $statement['metrics'];
                            $register = $statement['invoiceRegister'];
                            $payments = $statement['paymentHistory'];
                            $aged = $statement['agedBalances'];
                        @endphp

                        <div class="accordion-item mb-3 border rounded-3 overflow-hidden">
                            <h2 class="accordion-header" id="heading{{ $idx }}">
                                <button class="accordion-button {{ $idx === 0 ? '' : 'collapsed' }}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ $idx }}" aria-expanded="{{ $idx === 0 ? 'true' : 'false' }}" aria-controls="collapse{{ $idx }}">
                                    <div class="d-flex flex-column">
                                        <span class="fw-bold">{{ $supplier->supplier_name }}</span>
                                        <small class="text-muted">Code: {{ $supplier->supplier_code ?? 'N/A' }}</small>
                                    </div>
                                </button>
                            </h2>
                            <div id="collapse{{ $idx }}" class="accordion-collapse collapse {{ $idx === 0 ? 'show' : '' }}" aria-labelledby="heading{{ $idx }}" data-bs-parent="#supplierStatementAccordion">
                                <div class="accordion-body">
                                    <div class="row g-3 mb-4">
                                        <div class="col-md-3"><div class="metric-card"><div class="metric-title">Current Balance</div><div class="metric-value">${{ number_format($metrics['currentBalance'], 2) }}</div></div></div>
                                        <div class="col-md-3"><div class="metric-card"><div class="metric-title">Total Invoices</div><div class="metric-value">${{ number_format($metrics['totalInvoicesAmount'], 2) }}</div></div></div>
                                        <div class="col-md-3"><div class="metric-card"><div class="metric-title">Total Payments</div><div class="metric-value">${{ number_format($metrics['totalPayments'], 2) }}</div></div></div>
                                        <div class="col-md-3"><div class="metric-card"><div class="metric-title">Status Counts</div><div class="metric-value">{{ $metrics['countPending'] }}/{{ $metrics['countApproved'] }}/{{ $metrics['countPaid'] }}/{{ $metrics['countRejected'] }}</div></div></div>
                                    </div>

                                    <h6 class="fw-bold mb-2">Invoice Register</h6>
                                    <div class="table-responsive mb-4">
                                        <table class="table table-bordered table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Date</th>
                                                    <th>Description</th>
                                                    <th>Status</th>
                                                    <th class="text-end">Total</th>
                                                    <th class="text-end">Paid</th>
                                                    <th class="text-end">Balance</th>
                                                    <th class="text-end">Days</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @forelse($register as $row)
                                                    <tr>
                                                        <td>{{ $row['invoice_number'] }}</td>
                                                        <td>{{ $row['invoice_date'] }}</td>
                                                        <td>{{ $row['description'] ?: 'N/A' }}</td>
                                                        <td><span class="status-badge status-{{ $row['status'] }}">{{ $row['status'] }}</span></td>
                                                        <td class="text-end">{{ number_format($row['total'], 2) }}</td>
                                                        <td class="text-end">{{ number_format($row['paid'], 2) }}</td>
                                                        <td class="text-end fw-bold {{ $row['balance'] > 0 ? 'text-danger' : 'text-success' }}">{{ number_format($row['balance'], 2) }}</td>
                                                        <td class="text-end">{{ $row['days_outstanding'] }}</td>
                                                    </tr>
                                                @empty
                                                    <tr>
                                                        <td colspan="8" class="text-center text-muted">No invoices found for this supplier and date range.</td>
                                                    </tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>

                                    <div class="row g-3 mb-4">
                                        <div class="col-md-4"><div class="metric-card"><div class="metric-title">Aged 0-30 Days</div><div class="metric-value">${{ number_format($aged['0_30'], 2) }}</div></div></div>
                                        <div class="col-md-4"><div class="metric-card"><div class="metric-title">Aged 31-60 Days</div><div class="metric-value">${{ number_format($aged['31_60'], 2) }}</div></div></div>
                                        <div class="col-md-4"><div class="metric-card"><div class="metric-title">Aged 61+ Days</div><div class="metric-value">${{ number_format($aged['61_plus'], 2) }}</div></div></div>
                                    </div>

                                    <h6 class="fw-bold mb-2">Payment History</h6>
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Reference</th>
                                                    <th>Description</th>
                                                    <th>Applied To Invoice(s)</th>
                                                    <th class="text-end">Amount</th>
                                                    <th class="text-end">Unapplied</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @forelse($payments as $payment)
                                                    <tr>
                                                        <td>{{ $payment['date'] }}</td>
                                                        <td>{{ $payment['reference'] }}</td>
                                                        <td>{{ $payment['description'] }}</td>
                                                        <td>{{ count($payment['applied_to']) > 0 ? implode(', ', $payment['applied_to']) : 'Unallocated' }}</td>
                                                        <td class="text-end">{{ number_format($payment['amount'], 2) }}</td>
                                                        <td class="text-end {{ $payment['unapplied'] > 0 ? 'text-warning fw-bold' : '' }}">{{ number_format($payment['unapplied'], 2) }}</td>
                                                    </tr>
                                                @empty
                                                    <tr>
                                                        <td colspan="6" class="text-center text-muted">No payments found in this period.</td>
                                                    </tr>
                                                @endforelse
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>
            @else
                <div class="alert alert-info mb-0">
                    Generate the report to view supplier invoice register, statuses, aged balances, current balance, and payment history.
                </div>
            @endif
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
(() => {
    const supplierSelect = document.querySelector('select[name="supplier_account"]');
    const currencySelect = document.querySelector('select[name="currency"]');
    const toDateInput = document.querySelector('input[name="date_to"]');
    const fromDateInput = document.querySelector('input[name="date_from"]');

    if (fromDateInput && toDateInput) {
        fromDateInput.addEventListener('change', () => {
            if (toDateInput.value && fromDateInput.value > toDateInput.value) {
                toDateInput.value = fromDateInput.value;
            }
        });
    }

    // Keep selected values explicit for browsers that cache form state aggressively.
    if (supplierSelect) supplierSelect.value = "{{ $supplierId }}";
    if (currencySelect && "{{ $currencyId }}" !== "") currencySelect.value = "{{ $currencyId }}";
})();
</script>
@endsection
