@extends('admin.layouts.app')

@section('content')

@push('styles')
<link rel="stylesheet" href="{{ asset('admin/css/loans.css') }}">
@endpush

<div class="loan-page">
<div class="loan-container">

@if(session('success'))
<div class="loan-alert loan-alert-success">{{ session('success') }}</div>
@endif

@if(session('error'))
<div class="loan-alert loan-alert-error">{{ session('error') }}</div>
@endif

<div class="loan-header">
    <div class="loan-title">
        <h1>Loan Management</h1>
        <p>Review applications, manage approvals and monitor active loans.</p>
    </div>
    <div class="loan-actions">
        <a href="{{ route('admin.loans.create') }}" class="loan-btn loan-btn-dark">
            + Create Loan
        </a>
    </div>
</div>

<div class="loan-stats">
    <div class="loan-stat"><div class="loan-stat-label">Total Loans</div><div class="loan-stat-value loan-blue">{{ number_format($totalLoans) }}</div><div class="loan-stat-meta">All applications</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Pending</div><div class="loan-stat-value loan-orange">{{ number_format($pendingLoans) }}</div><div class="loan-stat-meta">Awaiting review</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Approved</div><div class="loan-stat-value loan-blue">{{ number_format($approvedLoans) }}</div><div class="loan-stat-meta">Ready to disburse</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Active</div><div class="loan-stat-value loan-green">{{ number_format($activeLoans) }}</div><div class="loan-stat-meta">Currently running</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Overdue</div><div class="loan-stat-value loan-red">{{ number_format($overdueLoans) }}</div><div class="loan-stat-meta">Needs attention</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Completed</div><div class="loan-stat-value loan-purple">{{ number_format($completedLoans) }}</div><div class="loan-stat-meta">Successfully closed</div></div>
</div>

<div class="loan-stats" style="grid-template-columns:repeat(2,1fr);margin-bottom:20px">
    <div class="loan-stat"><div class="loan-stat-label">Total Disbursed</div><div class="loan-stat-value loan-green">{{ money((float)$totalDisbursed) }}</div><div class="loan-stat-meta">Disbursed, active and completed loans</div></div>
    <div class="loan-stat"><div class="loan-stat-label">Total Outstanding</div><div class="loan-stat-value loan-orange">{{ money((float)$totalOutstanding) }}</div><div class="loan-stat-meta">Current outstanding balance</div></div>
</div>

<div class="loan-main-card">

<form method="GET" action="{{ route('admin.loans') }}" class="loan-toolbar">
    <div class="loan-search">
        <input type="search" name="search" value="{{ request('search') }}" placeholder="Search loan number, client name, mobile or email...">
    </div>
    <div class="loan-filter">
        <select name="status" onchange="this.form.submit()">
            <option value="">All Status</option>
            @foreach(['pending'=>'Pending','approved'=>'Approved','disbursed'=>'Disbursed','active'=>'Active','overdue'=>'Overdue','completed'=>'Completed','rejected'=>'Rejected','cancelled'=>'Cancelled'] as $value=>$label)
                <option value="{{ $value }}" @selected(request('status') === $value)>{{ $label }}</option>
            @endforeach
        </select>
    </div>
    <button type="submit" class="loan-btn loan-btn-dark">Search</button>
    @if(request()->filled('search') || request()->filled('status'))
        <a href="{{ route('admin.loans') }}" class="loan-btn loan-btn-light">Clear</a>
    @endif
</form>

@if($loans->count())

<div class="loan-table-wrap">
<table class="loan-table">
<thead>
<tr>
<th>Loan</th><th>Client</th><th>Loan Amount</th><th>Charges</th><th>EMI</th><th>Tenure</th><th>Outstanding</th><th>Status</th><th>Applied</th><th>Action</th>
</tr>
</thead>
<tbody>

@foreach($loans as $loan)
@php
    $clientName = $loan->user->name ?? 'Unknown Client';
    $initial = strtoupper(substr($clientName,0,1));
    $statusClass = match($loan->status) {
        'pending'=>'status-pending','approved'=>'status-approved','disbursed'=>'status-disbursed','active'=>'status-active',
        'overdue'=>'status-overdue','completed'=>'status-completed','rejected'=>'status-rejected','cancelled'=>'status-cancelled',
        default=>'status-pending'
    };
@endphp

<tr>
<td>
    <div class="loan-number">{{ $loan->loan_number }}</div>
    <div class="loan-client-sub">Card: {{ $loan->emiCard->card_number ?? '—' }}</div>
</td>

<td>
    <div class="loan-client">
        <div class="loan-avatar">{{ $initial }}</div>
        <div>
            <div class="loan-client-name">{{ $clientName }}</div>
            <div class="loan-client-sub">{{ $loan->user->mobile ?? $loan->user->email ?? '—' }}</div>
        </div>
    </div>
</td>

<td>
    <div class="loan-money">{{ money((float)$loan->loan_amount) }}</div>
    <div class="loan-submoney">Total: {{ money((float)$loan->total_payable) }}</div>
</td>

<td>
    <span class="loan-zero">{{ number_format((float)$loan->interest_rate,2) }}% Interest</span>
    <div class="loan-submoney">Fee: {{ money((float)$loan->processing_fee) }}</div>
</td>

<td>
    <div class="loan-money">{{ money((float)$loan->emi_amount) }}</div>
    <div class="loan-submoney">Monthly</div>
</td>

<td>
    <div class="loan-money">{{ $loan->tenure_months }}</div>
    <div class="loan-submoney">months</div>
</td>

<td>
    <div class="loan-money">
        {{ money($loan->status === 'rejected' ? 0 : (float)$loan->outstanding_amount) }}
    </div>
</td>

<td><span class="loan-status {{ $statusClass }}">{{ ucfirst($loan->status) }}</span></td>

<td>
    <div class="loan-money">{{ optional($loan->applied_at)->format('d M Y') ?? optional($loan->created_at)->format('d M Y') }}</div>
    <div class="loan-submoney">{{ optional($loan->created_at)->format('h:i A') }}</div>
</td>

<td>
<div class="loan-row-actions">

<a href="{{ route('admin.loans.show',$loan) }}" class="loan-icon-btn" title="View Loan">↗</a>

@if($loan->status === 'pending')
<form method="POST" action="{{ route('admin.loans.approve',$loan) }}" class="loan-mini-form" onsubmit="return confirm('Approve this loan?')">
@csrf
<button type="submit" class="loan-icon-btn" title="Approve">✓</button>
</form>

<form method="POST" action="{{ route('admin.loans.reject',$loan) }}" class="loan-mini-form" onsubmit="return rejectLoan(this)">
@csrf
<input type="hidden" name="rejection_reason" value="">
<button type="submit" class="loan-icon-btn" title="Reject">×</button>
</form>

@elseif($loan->status === 'approved')
<form method="POST" action="{{ route('admin.loans.disburse',$loan) }}" class="loan-mini-form" onsubmit="return confirm('Disburse this loan and generate the EMI schedule?')">
@csrf
<button type="submit" class="loan-icon-btn" title="Disburse">₹</button>
</form>
@endif

</div>
</td>
</tr>
@endforeach

</tbody>
</table>
</div>

@if($loans->hasPages())
<div class="loan-pagination">

    <div class="loan-pagination-info">
        Showing
        <strong>{{ $loans->firstItem() ?? 0 }}</strong>
        -
        <strong>{{ $loans->lastItem() ?? 0 }}</strong>
        of
        <strong>{{ $loans->total() }}</strong>
    </div>

    <div class="loan-pagination-controls">

        {{-- Previous --}}
        @if($loans->onFirstPage())
            <span class="loan-page-btn loan-page-disabled">
                ‹
            </span>
        @else
            <a
                href="{{ $loans->previousPageUrl() }}"
                class="loan-page-btn"
                aria-label="Previous page"
            >
                ‹
            </a>
        @endif


        {{-- Page Numbers --}}
        @foreach($loans->getUrlRange(
            max(1, $loans->currentPage() - 2),
            min($loans->lastPage(), $loans->currentPage() + 2)
        ) as $page => $url)

            @if($page == $loans->currentPage())

                <span class="loan-page-btn loan-page-active">
                    {{ $page }}
                </span>

            @else

                <a
                    href="{{ $url }}"
                    class="loan-page-btn"
                >
                    {{ $page }}
                </a>

            @endif

        @endforeach


        {{-- Next --}}
        @if($loans->hasMorePages())

            <a
                href="{{ $loans->nextPageUrl() }}"
                class="loan-page-btn"
                aria-label="Next page"
            >
                ›
            </a>

        @else

            <span class="loan-page-btn loan-page-disabled">
                ›
            </span>

        @endif

    </div>

</div>
@endif

@else
<div class="loan-empty">
    <div class="loan-empty-icon">₹</div>
    <strong>No loans found</strong>
    <span>There are no loan records matching your current filters.</span>
</div>
@endif

</div>
</div>
</div>

<script>
function rejectLoan(form) {
    const reason = prompt('Enter rejection reason:');
    if (reason === null) return false;
    if (!reason.trim()) {
        alert('Rejection reason is required.');
        return false;
    }
    form.querySelector('input[name="rejection_reason"]').value = reason.trim();
    return true;
}
</script>

@endsection