@extends('member.layout')

@section('title', 'My Loans')

@section('content')
<div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <!-- Header Section -->
        <div class="mb-6">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-money-bill-wave text-green-600 text-base"></i>
                        </div>
                        <div>
                            <h1 class="text-xl lg:text-2xl font-bold text-gray-900">
                                My Loans
                            </h1>
                            <p class="mt-1 text-gray-600 text-sm">Manage your loan applications and payments</p>
                        </div>
                    </div>
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div class="flex items-center space-x-3">
                            <a href="{{ route('member.loans.create') }}" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors shadow-sm">
                                <i class="fas fa-plus mr-2"></i>Apply for Loan
                            </a>
                        </div>
                        @if($loans->count() > 0)
                        <div class="flex items-center space-x-3">
                            <button onclick="exportToPDF()" id="exportBtn" class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors shadow-sm">
                                <i class="fas fa-file-pdf mr-2"></i>Export PDF
                            </button>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-list text-blue-600 text-base"></i>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Total Loans</p>
                        <p class="text-lg font-semibold text-gray-900">{{ $loans->count() }}</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-check-circle text-green-600 text-base"></i>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Active Loans</p>
                        <p class="text-lg font-semibold text-gray-900">{{ $loans->whereIn('status', ['approved', 'active'])->count() }}</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-yellow-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-clock text-yellow-600 text-base"></i>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Pending</p>
                        <p class="text-lg font-semibold text-gray-900">{{ $loans->where('status', 'pending')->count() }}</p>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                        <i class="fas fa-coins text-purple-600 text-base"></i>
                    </div>
                    <div>
                        <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Total Amount</p>
                        <p class="text-lg font-semibold text-gray-900">KSh {{ number_format($loans->sum('amount'), 0) }}</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loan Widgets -->
        @if($loans->count() > 0)
            <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                @foreach($loans as $loan)
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
                    <!-- Header -->
                    <div class="px-4 py-3 border-b border-gray-200 bg-gray-50">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center space-x-2">
                                <div class="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                                    <i class="fas fa-hand-holding-usd text-green-600 text-sm"></i>
                                </div>
                                <div>
                                    <h3 class="text-sm font-semibold text-gray-900">Loan #{{ $loan->id }}</h3>
                                    <p class="text-xs text-gray-500">{{ $loan->created_at->format('M d, Y') }}</p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium
                                @if($loan->status === 'approved') bg-green-100 text-green-800
                                @elseif($loan->status === 'pending') bg-yellow-100 text-yellow-800
                                @elseif($loan->status === 'rejected') bg-red-100 text-red-800
                                @elseif($loan->status === 'active') bg-blue-100 text-blue-800
                                @elseif($loan->status === 'paid') bg-gray-100 text-gray-800
                                @else bg-gray-100 text-gray-800 @endif">
                                {{ ucfirst($loan->status) }}
                            </span>
                        </div>
                    </div>

                    <!-- Content -->
                    <div class="p-4 space-y-3">
                        <!-- Amount Details -->
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Principal</p>
                                <p class="text-sm font-semibold text-gray-900">KSh {{ number_format($loan->amount, 0) }}</p>
                            </div>
                            <div>
                                <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Interest</p>
                                <p class="text-sm font-semibold text-gray-900">{{ $loan->interest_rate }}%</p>
                            </div>
                        </div>

                        <!-- Payment Details -->
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Monthly</p>
                                <p class="text-sm font-semibold text-gray-900">KSh {{ number_format($loan->monthly_payment, 0) }}</p>
                            </div>
                            <div>
                                <p class="text-xs font-medium text-gray-500 uppercase tracking-wide">Term</p>
                                <p class="text-sm font-semibold text-gray-900">{{ $loan->term_months }}m</p>
                            </div>
                        </div>

                        <!-- Balance Info (for active loans) -->
                        @if(in_array($loan->status, ['approved', 'active']))
                        <div class="pt-2 border-t border-gray-100">
                            <div class="flex justify-between items-center">
                                <span class="text-xs font-medium text-gray-500">Outstanding Balance</span>
                                <span class="text-sm font-semibold text-gray-900">KSh {{ number_format($loan->balance, 0) }}</span>
                            </div>
                            <div class="mt-2 bg-gray-200 rounded-full h-2">
                                <div class="bg-green-600 h-2 rounded-full" style="width: {{ $loan->total_amount > 0 ? min(100, ($loan->paid_amount / $loan->total_amount) * 100) : 0 }}%"></div>
                            </div>
                            <p class="text-xs text-gray-500 mt-1">Paid: KSh {{ number_format($loan->paid_amount, 0) }} of KSh {{ number_format($loan->total_amount, 0) }}</p>
                        </div>
                        @endif
                    </div>

                    <!-- Actions -->
                    <div class="px-4 py-3 bg-gray-50 border-t border-gray-200">
                        <div class="grid grid-cols-2 gap-2">
                            <a href="{{ route('member.loans.show', $loan) }}" class="inline-flex items-center justify-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-colors">
                                <i class="fas fa-eye mr-1"></i><span class="hidden sm:inline">View</span>
                            </a>
                            @if($loan->status === 'pending')
                            <a href="{{ route('member.loans.edit', $loan) }}" class="inline-flex items-center justify-center px-3 py-2 border border-yellow-300 text-sm font-medium rounded-md text-yellow-700 bg-yellow-50 hover:bg-yellow-100 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 transition-colors">
                                <i class="fas fa-edit mr-1"></i><span class="hidden sm:inline">Edit</span>
                            </a>
                            @elseif(in_array($loan->status, ['approved', 'active']))
                            <button onclick="payLoan({{ $loan->id }})" class="inline-flex items-center justify-center px-3 py-2 border border-green-300 text-sm font-medium rounded-md text-green-700 bg-green-50 hover:bg-green-100 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors">
                                <i class="fas fa-credit-card mr-1"></i><span class="hidden sm:inline">Pay</span>
                            </button>
                            @else
                            <div class="inline-flex items-center justify-center px-3 py-2 text-sm font-medium text-gray-500 bg-gray-100 rounded-md cursor-not-allowed">
                                <i class="fas fa-lock mr-1"></i><span class="hidden sm:inline">Locked</span>
                            </div>
                            @endif
                        </div>
                        @if($loan->status === 'pending')
                        <div class="mt-2">
                            <button onclick="deleteLoan({{ $loan->id }})" class="w-full inline-flex items-center justify-center px-3 py-2 border border-red-300 text-sm font-medium rounded-md text-red-700 bg-red-50 hover:bg-red-100 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-offset-2 transition-colors">
                                <i class="fas fa-trash mr-1"></i>Delete Application
                            </button>
                        </div>
                        @endif
                    </div>
                </div>
                @endforeach
            </div>

            <!-- Pagination -->
            @if($loans->hasPages())
            <div class="mt-6 flex justify-center">
                {{ $loans->links() }}
            </div>
            @endif
        @else
            <!-- Empty State -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
                <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fas fa-money-bill-wave text-gray-400 text-2xl"></i>
                </div>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">No Loan Applications Yet</h3>
                <p class="text-gray-600 mb-6">You haven't applied for any loans yet. Start your financial journey with us!</p>
                <a href="{{ route('member.loans.create') }}" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 transition-colors">
                    <i class="fas fa-plus mr-2"></i>Apply for Your First Loan
                </a>
            </div>
        @endif
    </div>
</div>

<!-- Payment Modal -->
<div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden" id="paymentModal" style="z-index: 1050;">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white" style="max-width: 400px;">
        <div class="mt-3">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-gray-900 flex items-center">
                    <i class="fas fa-credit-card mr-2 text-green-600"></i>
                    Make Loan Payment
                </h3>
                <button onclick="closePaymentModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <form id="paymentForm" onsubmit="submitPayment(event)">
                @csrf
                <div class="mb-4">
                    <label for="payment_amount" class="block text-sm font-medium text-gray-700 mb-2">Payment Amount (KSh)</label>
                    <input type="number" id="payment_amount" name="amount" min="1" step="0.01"
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-green-500"
                            placeholder="Enter payment amount" required>
                    <p class="text-xs text-gray-500 mt-1">Enter the amount you want to pay towards your loan</p>
                </div>

                <div class="flex justify-end space-x-3">
                    <button type="button" onclick="closePaymentModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 border border-gray-300 rounded-md hover:bg-gray-200 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-green-600 border border-transparent rounded-md hover:bg-green-700 transition-colors">
                        <i class="fas fa-paper-plane mr-1"></i>Send M-Pesa Request
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('js')
<script>
let currentLoanId = null;

function payLoan(loanId) {
    currentLoanId = loanId;
    document.getElementById('payment_amount').value = ''; // Clear previous value
    document.getElementById('paymentModal').classList.remove('hidden');
}

function closePaymentModal() {
    document.getElementById('paymentModal').classList.add('hidden');
    document.getElementById('paymentForm').reset();
    currentLoanId = null;
}

function submitPayment(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    formData.append('loan_id', currentLoanId);

    // Show loading state
    const submitBtn = event.target.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Processing...';
    submitBtn.disabled = true;

    fetch(`{{ url('member/loans') }}/${currentLoanId}/pay`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Payment Initiated!',
                text: 'Please check your phone and complete the M-Pesa payment.',
                timer: 3000,
                showConfirmButton: false
            });
            closePaymentModal();
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Payment Failed',
                text: data.message
            });
        }
    })
    .catch(error => {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred while processing your payment.'
        });
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
}

// Close modal when clicking outside
document.getElementById('paymentModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closePaymentModal();
    }
});

function deleteLoan(loanId) {
    Swal.fire({
        title: 'Are you sure?',
        text: 'This will permanently delete your loan application. This action cannot be undone.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: 'Deleting...',
                text: 'Please wait while we delete your application.',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => {
                    Swal.showLoading();
                }
            });

            // Create form for DELETE request
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = `{{ url('member/loans') }}/${loanId}`;
            form.style.display = 'none';

            // Add method spoofing for DELETE
            const methodInput = document.createElement('input');
            methodInput.type = 'hidden';
            methodInput.name = '_method';
            methodInput.value = 'DELETE';
            form.appendChild(methodInput);

            // Add CSRF token
            const csrfToken = document.createElement('input');
            csrfToken.type = 'hidden';
            csrfToken.name = '_token';
            csrfToken.value = '{{ csrf_token() }}';
            form.appendChild(csrfToken);

            // Add to body and submit
            document.body.appendChild(form);
            form.submit();
        }
    });
}

function exportToPDF() {
    // Show loading state
    const exportBtn = document.getElementById('exportBtn');
    const originalText = exportBtn.innerHTML;
    exportBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Generating...';
    exportBtn.disabled = true;
    exportBtn.classList.add('opacity-75', 'cursor-not-allowed');

    // Show success message
    Swal.fire({
        title: 'Generating PDF...',
        text: 'Please wait while we prepare your loan report.',
        allowOutsideClick: false,
        showConfirmButton: false,
        willOpen: () => {
            Swal.showLoading();
        }
    });

    // Create a form to submit the export request
    const form = document.createElement('form');
    form.method = 'POST';
    form.action = '{{ route("member.loans.export") }}';
    form.target = '_blank';

    // Add CSRF token
    const csrfToken = document.createElement('input');
    csrfToken.type = 'hidden';
    csrfToken.name = '_token';
    csrfToken.value = '{{ csrf_token() }}';
    form.appendChild(csrfToken);

    // Add to body and submit
    document.body.appendChild(form);
    form.submit();

    // Remove form and restore button after a delay
    setTimeout(() => {
        document.body.removeChild(form);
        exportBtn.innerHTML = originalText;
        exportBtn.disabled = false;
        exportBtn.classList.remove('opacity-75', 'cursor-not-allowed');
        Swal.close();
    }, 2000);
}

</script>
@endpush
@endsection
