<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#3b82f6');
$balance = (float)($currentUser['balance'] ?? 0.00);
$fullName = htmlspecialchars($currentUser['full_name'] ?? $currentUser['username'] ?? 'User');
$email = htmlspecialchars($currentUser['email'] ?? '');
$phone = htmlspecialchars($currentUser['phone'] ?? '');

// ==========================================
// FETCH ADMIN LOAN SETTINGS
// ==========================================
$settingsQuery = mysqli_query($conn, "SELECT `setting_key`, `setting_value` FROM `admin_settings` WHERE `setting_key` IN ('min_loan_amount', 'max_loan_amount', 'interest_rate', 'max_duration_months', 'late_fee_percent')");
$loanSettings = [];
if ($settingsQuery) {
    while ($sRow = mysqli_fetch_assoc($settingsQuery)) {
        $loanSettings[$sRow['setting_key']] = $sRow['setting_value'];
    }
}
$minLoan = (float)($loanSettings['min_loan_amount'] ?? 100);
$maxLoan = (float)($loanSettings['max_loan_amount'] ?? 50000);
$interestRate = (float)($loanSettings['interest_rate'] ?? 12.5);
$maxDuration = (int)($loanSettings['max_duration_months'] ?? 36);
$lateFeePercent = (float)($loanSettings['late_fee_percent'] ?? 5.0);

// ==========================================
// HANDLE AJAX LOAN APPLICATION
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    ob_start();

    try {
        $action = $_POST['action'] ?? '';

        if ($action === 'apply_loan') {
            $amount = floatval($_POST['amount'] ?? 0);
            $duration = intval($_POST['duration'] ?? 12);
            $purpose = mysqli_real_escape_string($conn, $_POST['purpose'] ?? 'Personal');
            $employmentStatus = mysqli_real_escape_string($conn, $_POST['employment_status'] ?? 'Employed');
            $monthlyIncome = floatval($_POST['monthly_income'] ?? 0);
            $collateral = mysqli_real_escape_string($conn, $_POST['collateral'] ?? 'None');
            $notes = mysqli_real_escape_string($conn, $_POST['notes'] ?? '');

            if ($amount < $minLoan || $amount > $maxLoan) {
                throw new Exception("Loan amount must be between $" . number_format($minLoan, 2) . " and $" . number_format($maxLoan, 2));
            }
            if ($duration < 1 || $duration > $maxDuration) {
                throw new Exception("Duration must be between 1 and {$maxDuration} months.");
            }
            if ($monthlyIncome <= 0) {
                throw new Exception("Please enter a valid monthly income.");
            }

            // Calculate total repayment
            $monthlyInterest = ($interestRate / 100) / 12;
            $monthlyPayment = $amount * ($monthlyInterest * pow(1 + $monthlyInterest, $duration)) / (pow(1 + $monthlyInterest, $duration) - 1);
            $totalRepayment = $monthlyPayment * $duration;
            $totalInterest = $totalRepayment - $amount;

            $insertStmt = mysqli_prepare($conn, "INSERT INTO `loan_applications` 
                (`user_id`, `amount`, `duration_months`, `interest_rate`, `monthly_payment`, `total_repayment`, `total_interest`, 
                 `purpose`, `employment_status`, `monthly_income`, `collateral`, `notes`, `status`, `applied_at`) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())");

            if (!$insertStmt) throw new Exception("Prepare failed: " . mysqli_error($conn));

            mysqli_stmt_bind_param($insertStmt, "ididddsssdds", 
                $userId, $amount, $duration, $interestRate, $monthlyPayment, $totalRepayment, $totalInterest,
                $purpose, $employmentStatus, $monthlyIncome, $collateral, $notes
            );

            if (!mysqli_stmt_execute($insertStmt)) {
                throw new Exception("Execution failed: " . mysqli_stmt_error($insertStmt));
            }

            $loanId = mysqli_insert_id($conn);
            mysqli_stmt_close($insertStmt);

            ob_end_clean();
            echo json_encode([
                'success' => true,
                'message' => 'Loan application submitted successfully!',
                'loan_id' => 'LN-' . str_pad($loanId, 6, '0', STR_PAD_LEFT),
                'monthly_payment' => round($monthlyPayment, 2),
                'total_repayment' => round($totalRepayment, 2),
                'total_interest' => round($totalInterest, 2)
            ]);

        } elseif ($action === 'make_repayment') {
            $loanId = intval($_POST['loan_id'] ?? 0);
            $repayAmount = floatval($_POST['amount'] ?? 0);

            if ($loanId <= 0 || $repayAmount <= 0) throw new Exception('Invalid repayment details.');

            // Verify loan belongs to user and is approved
            $verifyStmt = mysqli_prepare($conn, "SELECT `remaining_balance`, `status` FROM `loan_applications` WHERE `id` = ? AND `user_id` = ?");
            mysqli_stmt_bind_param($verifyStmt, "ii", $loanId, $userId);
            mysqli_stmt_execute($verifyStmt);
            mysqli_stmt_bind_result($verifyStmt, $remainingBalance, $loanStatus);
            $found = mysqli_stmt_fetch($verifyStmt);
            mysqli_stmt_close($verifyStmt);

            if (!$found) throw new Exception('Loan not found.');
            if ($loanStatus !== 'approved') throw new Exception('Loan is not approved for repayment.');
            if ($repayAmount > $remainingBalance) throw new Exception('Repayment exceeds remaining balance.');
            if ($repayAmount > $balance) throw new Exception('Insufficient account balance.');

            // Deduct from user balance
            $newBalance = $balance - $repayAmount;
            mysqli_query($conn, "UPDATE `users` SET `balance` = $newBalance WHERE `id` = $userId");

            // Record repayment
            $repayStmt = mysqli_prepare($conn, "INSERT INTO `loan_repayments` (`loan_id`, `amount`, `paid_at`) VALUES (?, ?, NOW())");
            mysqli_stmt_bind_param($repayStmt, "id", $loanId, $repayAmount);
            mysqli_stmt_execute($repayStmt);
            mysqli_stmt_close($repayStmt);

            // Update loan balance
            $newRemaining = $remainingBalance - $repayAmount;
            $newStatus = $newRemaining <= 0 ? 'completed' : 'approved';
            mysqli_query($conn, "UPDATE `loan_applications` SET `remaining_balance` = $newRemaining, `status` = '$newStatus', `last_payment_at` = NOW() WHERE `id` = $loanId");

            ob_end_clean();
            echo json_encode([
                'success' => true,
                'message' => 'Repayment of $' . number_format($repayAmount, 2) . ' processed successfully!',
                'new_balance' => $newBalance,
                'remaining' => $newRemaining,
                'status' => $newStatus
            ]);

        } else {
            throw new Exception('Invalid action.');
        }

    } catch (Throwable $e) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ==========================================
// FETCH USER'S LOANS
// ==========================================
$loans = [];
$loansQuery = mysqli_query($conn, "SELECT * FROM `loan_applications` WHERE `user_id` = $userId ORDER BY `applied_at` DESC");
if ($loansQuery) {
    while ($row = mysqli_fetch_assoc($loansQuery)) {
        $loanId = (int)$row['id'];
        
        // Get total repaid
        $repaidResult = mysqli_query($conn, "SELECT COALESCE(SUM(`amount`), 0) as total_repaid FROM `loan_repayments` WHERE `loan_id` = $loanId");
        $repaidRow = mysqli_fetch_assoc($repaidResult);
        $totalRepaid = (float)$repaidRow['total_repaid'];
        
        $remaining = (float)($row['remaining_balance'] ?? $row['total_repayment']);
        $progress = $row['total_repayment'] > 0 ? (($row['total_repayment'] - $remaining) / $row['total_repayment']) * 100 : 0;

        $loans[] = [
            'id' => 'LN-' . str_pad($loanId, 6, '0', STR_PAD_LEFT),
            'raw_id' => $loanId,
            'amount' => (float)$row['amount'],
            'duration' => (int)$row['duration_months'],
            'interest_rate' => (float)$row['interest_rate'],
            'monthly_payment' => (float)$row['monthly_payment'],
            'total_repayment' => (float)$row['total_repayment'],
            'total_interest' => (float)$row['total_interest'],
            'remaining_balance' => $remaining,
            'total_repaid' => $totalRepaid,
            'progress' => round($progress, 1),
            'purpose' => $row['purpose'],
            'status' => $row['status'],
            'applied_at' => $row['applied_at'],
            'approved_at' => $row['approved_at'],
            'due_date' => $row['due_date'],
            'next_payment_due' => calculateNextPayment($row['approved_at'], $row['duration_months'], $totalRepaid, $row['monthly_payment'])
        ];
    }
}

function calculateNextPayment($approvedAt, $duration, $totalRepaid, $monthlyPayment) {
    if (!$approvedAt || $monthlyPayment <= 0) return null;
    $approved = strtotime($approvedAt);
    $monthsPaid = floor($totalRepaid / $monthlyPayment);
    $nextDue = strtotime("+".($monthsPaid + 1)." months", $approved);
    return date('Y-m-d', $nextDue);
}

// Calculate loan eligibility
$maxEligible = $balance * 5; // 5x account balance
$creditScore = calculateCreditScore($conn, $userId);
$eligibleAmount = min($maxEligible, $maxLoan);

function calculateCreditScore($conn, $userId) {
    // Simple credit score based on repayment history
    $score = 650; // Base score
    
    $completedQuery = mysqli_query($conn, "SELECT COUNT(*) as completed FROM `loan_applications` WHERE `user_id` = $userId AND `status` = 'completed'");
    $completed = mysqli_fetch_assoc($completedQuery)['completed'] ?? 0;
    $score += $completed * 25;
    
    $lateQuery = mysqli_query($conn, "SELECT COUNT(*) as late FROM `loan_applications` WHERE `user_id` = $userId AND `status` = 'late'");
    $late = mysqli_fetch_assoc($lateQuery)['late'] ?? 0;
    $score -= $late * 50;
    
    return min(max($score, 300), 850);
}
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    
    .glass-card {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .dark .glass-card {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    .loan-card {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    .loan-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 20px 40px -12px rgba(0, 0, 0, 0.15);
    }

    .status-pending { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
    .status-approved { background: rgba(16, 185, 129, 0.1); color: #10b981; }
    .status-rejected { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
    .status-completed { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
    .status-late { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

    .progress-bar {
        height: 8px;
        border-radius: 4px;
        background: #e2e8f0;
        overflow: hidden;
    }
    .dark .progress-bar { background: #1e293b; }
    .progress-fill {
        height: 100%;
        border-radius: 4px;
        background: var(--primary-theme);
        transition: width 0.6s ease;
    }

    .slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 100%;
        height: 6px;
        border-radius: 3px;
        background: #e2e8f0;
        outline: none;
    }
    .dark .slider-thumb { background: #1e293b; }
    .slider-thumb::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: var(--primary-theme);
        cursor: pointer;
        box-shadow: 0 2px 8px rgba(var(--primary-rgb), 0.4);
    }
    .slider-thumb::-moz-range-thumb {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: var(--primary-theme);
        cursor: pointer;
        box-shadow: 0 2px 8px rgba(var(--primary-rgb), 0.4);
    }

    .modal-overlay {
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
    }

    .input-field {
        transition: all 0.3s ease;
    }
    .input-field:focus {
        border-color: var(--primary-theme);
        box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
    }

    .credit-score-ring {
        width: 80px;
        height: 80px;
        border-radius: 50%;
        background: conic-gradient(var(--primary-theme) calc(var(--score) * 0.212%), #e2e8f0 0);
        display: flex;
        align-items: center;
        justify-content: center;
    }
    .dark .credit-score-ring { background: conic-gradient(var(--primary-theme) calc(var(--score) * 0.212%), #1e293b 0); }
    
    .step-indicator {
        transition: all 0.3s ease;
    }
    .step-indicator.active {
        background: var(--primary-theme);
        color: white;
    }
    .step-indicator.completed {
        background: #10b981;
        color: white;
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300"
     x-data='{
        balance: <?= $balance ?>,
        loans: <?= json_encode($loans, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        minLoan: <?= $minLoan ?>,
        maxLoan: <?= $maxLoan ?>,
        interestRate: <?= $interestRate ?>,
        maxDuration: <?= $maxDuration ?>,
        creditScore: <?= $creditScore ?>,
        eligibleAmount: <?= $eligibleAmount ?>,
        
        // Application form
        loanAmount: <?= $minLoan * 10 ?>,
        duration: 12,
        purpose: "Personal",
        employmentStatus: "Employed",
        monthlyIncome: 5000,
        collateral: "None",
        notes: "",
        
        // UI state
        showApplyModal: false,
        showRepayModal: false,
        selectedLoan: null,
        repayAmount: 0,
        isSubmitting: false,
        currentStep: 1,
        
        get monthlyPayment() {
            const r = (this.interestRate / 100) / 12;
            const n = this.duration;
            const p = this.loanAmount;
            if (r === 0) return p / n;
            return p * (r * Math.pow(1 + r, n)) / (Math.pow(1 + r, n) - 1);
        },
        
        get totalRepayment() {
            return this.monthlyPayment * this.duration;
        },
        
        get totalInterest() {
            return this.totalRepayment - this.loanAmount;
        },
        
        get apr() {
            return this.interestRate;
        },
        
        get creditRating() {
            if (this.creditScore >= 750) return "Excellent";
            if (this.creditScore >= 670) return "Good";
            if (this.creditScore >= 580) return "Fair";
            return "Poor";
        },
        
        get creditColor() {
            if (this.creditScore >= 750) return "text-emerald-500";
            if (this.creditScore >= 670) return "text-theme";
            if (this.creditScore >= 580) return "text-amber-500";
            return "text-rose-500";
        },
        
        formatCurrency(num) {
            return "$" + num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },
        
        formatDate(dateStr) {
            if (!dateStr) return "N/A";
            return new Date(dateStr).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
        },
        
        openApplyModal() {
            this.showApplyModal = true;
            this.currentStep = 1;
            this.loanAmount = Math.min(this.eligibleAmount, this.maxLoan);
        },
        
        openRepayModal(loan) {
            this.selectedLoan = loan;
            this.repayAmount = Math.min(loan.monthly_payment, loan.remaining_balance);
            this.showRepayModal = true;
        },
        
        async submitApplication() {
            this.isSubmitting = true;
            
            const params = new URLSearchParams();
            params.append("action", "apply_loan");
            params.append("amount", this.loanAmount);
            params.append("duration", this.duration);
            params.append("purpose", this.purpose);
            params.append("employment_status", this.employmentStatus);
            params.append("monthly_income", this.monthlyIncome);
            params.append("collateral", this.collateral);
            params.append("notes", this.notes);
            
            try {
                const response = await fetch("Loan_Application.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString()
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire({
                        icon: "success",
                        title: "Application Submitted!",
                        text: `Loan ${data.loan_id} is under review. Monthly payment: $${data.monthly_payment.toFixed(2)}`,
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 3000
                    });
                    this.showApplyModal = false;
                    // Refresh page to show new loan
                    setTimeout(() => location.reload(), 2000);
                } else {
                    Swal.fire({ icon: "error", title: "Application Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        },
        
        async submitRepayment() {
            if (this.repayAmount <= 0 || this.repayAmount > this.balance) {
                Swal.fire({ icon: "warning", title: "Invalid Amount", text: "Check your balance and repayment amount.", confirmButtonColor: "var(--primary-theme)" });
                return;
            }
            
            this.isSubmitting = true;
            const params = new URLSearchParams();
            params.append("action", "make_repayment");
            params.append("loan_id", this.selectedLoan.raw_id);
            params.append("amount", this.repayAmount);
            
            try {
                const response = await fetch("Loan_Application.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString()
                });
                const data = await response.json();
                
                if (data.success) {
                    Swal.fire({
                        icon: "success",
                        title: "Repayment Successful!",
                        text: data.message,
                        confirmButtonColor: "var(--primary-theme)",
                        timer: 2000
                    });
                    this.balance = data.new_balance;
                    this.selectedLoan.remaining_balance = data.remaining;
                    this.selectedLoan.status = data.status;
                    this.showRepayModal = false;
                    setTimeout(() => location.reload(), 1500);
                } else {
                    Swal.fire({ icon: "error", title: "Repayment Failed", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                Swal.fire({ icon: "error", title: "Error", text: "Something went wrong.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isSubmitting = false;
            }
        },
        
        nextStep() {
            if (this.currentStep < 3) this.currentStep++;
        },
        
        prevStep() {
            if (this.currentStep > 1) this.currentStep--;
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 py-8">

      <!-- Header -->
      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">
            Loan <span class="text-theme">Center</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Apply for loans, track repayments, and manage your credit.</p>
        </div>
        <div class="flex items-center gap-4">
            <div class="glass-card rounded-2xl px-5 py-3 flex items-center gap-3">
                <div class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                <span class="text-xs font-black uppercase tracking-widest text-slate-600 dark:text-slate-300">Balance</span>
                <span class="text-lg font-black text-slate-900 dark:text-white" x-text="formatCurrency(balance)"></span>
            </div>
            <button @click="openApplyModal()" 
                    class="px-6 py-3 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-xs shadow-xl shadow-theme/30 hover:brightness-110 transition-all flex items-center gap-2">
                <i data-lucide="plus" class="w-4 h-4"></i> Apply for Loan
            </button>
        </div>
      </div>

      <!-- Credit Score & Eligibility -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 flex items-center gap-6">
            <div class="credit-score-ring" :style="`--score: ${creditScore}`">
                <div class="w-16 h-16 rounded-full bg-white dark:bg-[#070b14] flex items-center justify-center">
                    <span class="text-lg font-black" :class="creditColor" x-text="creditScore"></span>
                </div>
            </div>
            <div>
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Credit Score</p>
                <p class="text-xl font-black text-slate-900 dark:text-white" x-text="creditRating"></p>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Updated today</p>
            </div>
        </div>
        
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Max Eligible</p>
                <p class="text-3xl font-black text-theme" x-text="formatCurrency(eligibleAmount)"></p>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">Based on account history</p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-theme/10 flex items-center justify-center text-theme">
                <i data-lucide="badge-check" class="w-6 h-6"></i>
            </div>
        </div>
        
        <div class="glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800 relative overflow-hidden">
            <div class="relative z-10">
                <p class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-1">Interest Rate</p>
                <p class="text-3xl font-black text-slate-900 dark:text-white" x-text="interestRate + '%'"></p>
                <p class="text-xs text-slate-500 dark:text-slate-400 mt-0.5">APR fixed rate</p>
            </div>
            <div class="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-2xl bg-amber-500/10 flex items-center justify-center text-amber-500">
                <i data-lucide="percent" class="w-6 h-6"></i>
            </div>
        </div>
      </div>

      <!-- Active Loans -->
      <div class="mb-8">
        <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Your Loans</h2>
        
        <div x-show="loans.length === 0" class="glass-card rounded-[2rem] p-12 text-center border border-slate-200 dark:border-slate-800">
            <div class="w-16 h-16 rounded-2xl bg-theme/10 flex items-center justify-center text-theme mx-auto mb-4">
                <i data-lucide="banknote" class="w-8 h-8"></i>
            </div>
            <h3 class="text-lg font-black text-slate-900 dark:text-white mb-2">No Active Loans</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mb-6">Apply for your first loan to get started.</p>
            <button @click="openApplyModal()" class="px-6 py-3 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-xs hover:brightness-110 transition-all">
                Apply Now
            </button>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <template x-for="loan in loans" :key="loan.id">
                <div class="loan-card glass-card rounded-[2rem] p-6 border border-slate-200 dark:border-slate-800">
                    <div class="flex items-start justify-between mb-4">
                        <div>
                            <div class="flex items-center gap-2 mb-1">
                                <h3 class="text-lg font-black text-slate-900 dark:text-white" x-text="loan.id"></h3>
                                <span class="px-2 py-0.5 rounded text-[9px] font-black uppercase tracking-widest"
                                      :class="'status-' + loan.status" x-text="loan.status"></span>
                            </div>
                            <p class="text-xs text-slate-500 dark:text-slate-400" x-text="loan.purpose"></p>
                        </div>
                        <div class="text-right">
                            <p class="text-2xl font-black text-slate-900 dark:text-white" x-text="formatCurrency(loan.amount)"></p>
                            <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest" x-text="loan.duration + ' months'"></p>
                        </div>
                    </div>

                    <!-- Progress -->
                    <div class="mb-4">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Repayment Progress</span>
                            <span class="text-xs font-black text-theme" x-text="loan.progress + '%'"></span>
                        </div>
                        <div class="progress-bar">
                            <div class="progress-fill" :style="'width: ' + loan.progress + '%'"></div>
                        </div>
                        <div class="flex justify-between mt-1">
                            <span class="text-[9px] font-bold text-slate-400" x-text="formatCurrency(loan.total_repaid) + ' paid'"></span>
                            <span class="text-[9px] font-bold text-slate-400" x-text="formatCurrency(loan.remaining_balance) + ' remaining'"></span>
                        </div>
                    </div>

                    <div class="grid grid-cols-3 gap-3 mb-4">
                        <div class="p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50 text-center">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Monthly</p>
                            <p class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(loan.monthly_payment)"></p>
                        </div>
                        <div class="p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50 text-center">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Interest</p>
                            <p class="text-sm font-black text-rose-500" x-text="formatCurrency(loan.total_interest)"></p>
                        </div>
                        <div class="p-2 rounded-xl bg-slate-50 dark:bg-slate-900/50 text-center">
                            <p class="text-[8px] font-black uppercase tracking-widest text-slate-400">Next Due</p>
                            <p class="text-sm font-black" :class="loan.status === 'late' ? 'text-rose-500' : 'text-theme'" x-text="formatDate(loan.next_payment_due)"></p>
                        </div>
                    </div>

                    <div class="flex gap-2" x-show="loan.status === 'approved' || loan.status === 'late'">
                        <button @click="openRepayModal(loan)" 
                                class="flex-1 py-3 rounded-xl bg-theme text-white text-xs font-black uppercase tracking-widest hover:brightness-110 transition-all">
                            Make Payment
                        </button>
                        <button @click="selectedLoan = loan" 
                                class="px-4 py-3 rounded-xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 hover:bg-slate-200 dark:hover:bg-slate-700 transition-all">
                            <i data-lucide="file-text" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </template>
        </div>
      </div>

      <!-- Loan Calculator -->
      <div class="glass-card rounded-[2.5rem] p-8 border border-slate-200 dark:border-slate-800 mb-8">
        <h2 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-6">Quick Calculator</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div class="space-y-6">
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <label class="text-xs font-black uppercase tracking-widest text-slate-500">Loan Amount</label>
                        <span class="text-sm font-black text-theme" x-text="formatCurrency(loanAmount)"></span>
                    </div>
                    <input type="range" x-model.number="loanAmount" :min="minLoan" :max="maxLoan" step="100" class="slider-thumb w-full">
                    <div class="flex justify-between mt-1">
                        <span class="text-[9px] font-bold text-slate-400" x-text="formatCurrency(minLoan)"></span>
                        <span class="text-[9px] font-bold text-slate-400" x-text="formatCurrency(maxLoan)"></span>
                    </div>
                </div>
                
                <div>
                    <div class="flex justify-between items-center mb-2">
                        <label class="text-xs font-black uppercase tracking-widest text-slate-500">Duration</label>
                        <span class="text-sm font-black text-theme" x-text="duration + ' months'"></span>
                    </div>
                    <input type="range" x-model.number="duration" min="1" :max="maxDuration" step="1" class="slider-thumb w-full">
                    <div class="flex justify-between mt-1">
                        <span class="text-[9px] font-bold text-slate-400">1 month</span>
                        <span class="text-[9px] font-bold text-slate-400" x-text="maxDuration + ' months'"></span>
                    </div>
                </div>
            </div>
            
            <div class="p-6 rounded-2xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                <div class="space-y-4">
                    <div class="flex justify-between items-center">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Monthly Payment</span>
                        <span class="text-xl font-black text-slate-900 dark:text-white" x-text="formatCurrency(monthlyPayment)"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Total Interest</span>
                        <span class="text-sm font-black text-rose-500" x-text="formatCurrency(totalInterest)"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">Total Repayment</span>
                        <span class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(totalRepayment)"></span>
                    </div>
                    <div class="border-t border-slate-200 dark:border-slate-800 pt-3">
                        <div class="flex justify-between items-center">
                            <span class="text-xs font-bold text-slate-500 uppercase tracking-widest">APR</span>
                            <span class="text-sm font-black text-theme" x-text="apr + '%'"></span>
                        </div>
                    </div>
                </div>
                <button @click="openApplyModal(); currentStep = 1;" 
                        class="w-full mt-6 py-3 rounded-xl bg-theme text-white font-black uppercase tracking-widest text-xs hover:brightness-110 transition-all">
                    Apply with These Terms
                </button>
            </div>
        </div>
      </div>

    </div>
  </main>

  <!-- Apply Modal -->
  <div x-show="showApplyModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-2xl w-full border border-slate-200 dark:border-slate-800 shadow-2xl max-h-[90vh] overflow-y-auto relative" @click.away="showApplyModal = false">
        
        <button @click="showApplyModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <div class="text-center mb-8">
            <div class="w-16 h-16 rounded-full bg-theme/10 flex items-center justify-center text-theme mx-auto mb-4">
                <i data-lucide="banknote" class="w-8 h-8"></i>
            </div>
            <h3 class="text-2xl font-black text-slate-900 dark:text-white">Loan Application</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Complete the steps below to apply.</p>
        </div>

        <!-- Steps -->
        <div class="flex items-center justify-center gap-4 mb-8">
            <div class="step-indicator w-10 h-10 rounded-full flex items-center justify-center text-xs font-black" 
                 :class="currentStep >= 1 ? (currentStep > 1 ? 'completed' : 'active') : 'bg-slate-100 dark:bg-slate-800 text-slate-400'">1</div>
            <div class="w-12 h-0.5 bg-slate-200 dark:bg-slate-800"></div>
            <div class="step-indicator w-10 h-10 rounded-full flex items-center justify-center text-xs font-black" 
                 :class="currentStep >= 2 ? (currentStep > 2 ? 'completed' : 'active') : 'bg-slate-100 dark:bg-slate-800 text-slate-400'">2</div>
            <div class="w-12 h-0.5 bg-slate-200 dark:bg-slate-800"></div>
            <div class="step-indicator w-10 h-10 rounded-full flex items-center justify-center text-xs font-black" 
                 :class="currentStep >= 3 ? 'active' : 'bg-slate-100 dark:bg-slate-800 text-slate-400'">3</div>
        </div>

        <!-- Step 1: Loan Details -->
        <div x-show="currentStep === 1" class="space-y-4">
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Amount ($)</label>
                    <input type="number" x-model.number="loanAmount" :min="minLoan" :max="maxLoan" step="100"
                           class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black focus:outline-none">
                </div>
                <div>
                    <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Duration (months)</label>
                    <input type="number" x-model.number="duration" min="1" :max="maxDuration"
                           class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black focus:outline-none">
                </div>
            </div>
            <div>
                <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Purpose</label>
                <select x-model="purpose" class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold focus:outline-none">
                    <option value="Personal">Personal</option>
                    <option value="Business">Business</option>
                    <option value="Education">Education</option>
                    <option value="Medical">Medical</option>
                    <option value="Home Improvement">Home Improvement</option>
                    <option value="Debt Consolidation">Debt Consolidation</option>
                    <option value="Vehicle">Vehicle</option>
                    <option value="Other">Other</option>
                </select>
            </div>
            <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                <div class="flex justify-between items-center mb-2">
                    <span class="text-xs font-bold text-slate-500">Monthly Payment</span>
                    <span class="text-lg font-black text-theme" x-text="formatCurrency(monthlyPayment)"></span>
                </div>
                <div class="flex justify-between items-center">
                    <span class="text-xs font-bold text-slate-500">Total Repayment</span>
                    <span class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(totalRepayment)"></span>
                </div>
            </div>
            <button @click="nextStep()" class="w-full py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm hover:brightness-110 transition-all">
                Continue
            </button>
        </div>

        <!-- Step 2: Personal Info -->
        <div x-show="currentStep === 2" class="space-y-4">
            <div>
                <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Employment Status</label>
                <select x-model="employmentStatus" class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold focus:outline-none">
                    <option value="Employed">Employed</option>
                    <option value="Self-Employed">Self-Employed</option>
                    <option value="Business Owner">Business Owner</option>
                    <option value="Unemployed">Unemployed</option>
                    <option value="Retired">Retired</option>
                </select>
            </div>
            <div>
                <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Monthly Income ($)</label>
                <input type="number" x-model.number="monthlyIncome" min="0" step="100"
                       class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black focus:outline-none">
            </div>
            <div>
                <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Collateral</label>
                <select x-model="collateral" class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold focus:outline-none">
                    <option value="None">None (Unsecured)</option>
                    <option value="Vehicle">Vehicle</option>
                    <option value="Property">Property</option>
                    <option value="Savings">Savings/Deposit</option>
                    <option value="Investments">Investments</option>
                </select>
            </div>
            <div class="flex gap-3">
                <button @click="prevStep()" class="flex-1 py-4 rounded-2xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 font-black uppercase tracking-widest text-sm hover:bg-slate-200 transition-all">
                    Back
                </button>
                <button @click="nextStep()" class="flex-1 py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm hover:brightness-110 transition-all">
                    Continue
                </button>
            </div>
        </div>

        <!-- Step 3: Review & Submit -->
        <div x-show="currentStep === 3" class="space-y-4">
            <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800 space-y-3">
                <div class="flex justify-between">
                    <span class="text-xs font-bold text-slate-500">Amount</span>
                    <span class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(loanAmount)"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-xs font-bold text-slate-500">Duration</span>
                    <span class="text-sm font-black text-slate-900 dark:text-white" x-text="duration + ' months'"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-xs font-bold text-slate-500">Purpose</span>
                    <span class="text-sm font-black text-slate-900 dark:text-white" x-text="purpose"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-xs font-bold text-slate-500">Monthly Payment</span>
                    <span class="text-sm font-black text-theme" x-text="formatCurrency(monthlyPayment)"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-xs font-bold text-slate-500">Total Interest</span>
                    <span class="text-sm font-black text-rose-500" x-text="formatCurrency(totalInterest)"></span>
                </div>
                <div class="border-t border-slate-200 dark:border-slate-800 pt-2">
                    <div class="flex justify-between">
                        <span class="text-xs font-bold text-slate-500">Total Repayment</span>
                        <span class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(totalRepayment)"></span>
                    </div>
                </div>
            </div>
            <div>
                <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Additional Notes (Optional)</label>
                <textarea x-model="notes" rows="3" placeholder="Any additional information..."
                          class="input-field w-full px-4 py-3 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-bold focus:outline-none resize-none"></textarea>
            </div>
            <div class="flex gap-3">
                <button @click="prevStep()" class="flex-1 py-4 rounded-2xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 font-black uppercase tracking-widest text-sm hover:bg-slate-200 transition-all">
                    Back
                </button>
                <button @click="submitApplication()" :disabled="isSubmitting"
                        class="flex-1 py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm hover:brightness-110 transition-all flex items-center justify-center gap-2">
                    <span x-show="!isSubmitting">Submit Application</span>
                    <span x-show="isSubmitting" class="flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                    </span>
                </button>
            </div>
        </div>
    </div>
  </div>

  <!-- Repayment Modal -->
  <div x-show="showRepayModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2.5rem] p-8 max-w-md w-full border border-slate-200 dark:border-slate-800 shadow-2xl relative" @click.away="showRepayModal = false">
        
        <button @click="showRepayModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <div class="text-center mb-6">
            <div class="w-16 h-16 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-500 mx-auto mb-4">
                <i data-lucide="wallet" class="w-8 h-8"></i>
            </div>
            <h3 class="text-xl font-black text-slate-900 dark:text-white">Make Repayment</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mt-1" x-text="selectedLoan ? selectedLoan.id : ''"></p>
        </div>

        <template x-if="selectedLoan">
            <div class="space-y-4">
                <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                    <div class="flex justify-between items-center mb-2">
                        <span class="text-xs font-bold text-slate-500">Remaining Balance</span>
                        <span class="text-lg font-black text-slate-900 dark:text-white" x-text="formatCurrency(selectedLoan.remaining_balance)"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-xs font-bold text-slate-500">Suggested Payment</span>
                        <span class="text-sm font-black text-theme" x-text="formatCurrency(selectedLoan.monthly_payment)"></span>
                    </div>
                </div>

                <div>
                    <label class="text-[9px] font-black uppercase tracking-widest text-slate-400 mb-2 block">Payment Amount ($)</label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-black">$</span>
                        <input type="number" x-model.number="repayAmount" :min="1" :max="Math.min(selectedLoan.remaining_balance, balance)" step="0.01"
                               class="input-field w-full pl-8 pr-4 py-4 rounded-xl bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-800 text-slate-900 dark:text-white font-black text-lg focus:outline-none">
                    </div>
                    <div class="flex gap-2 mt-2">
                        <button @click="repayAmount = selectedLoan.monthly_payment" class="flex-1 py-2 rounded-lg bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">Monthly</button>
                        <button @click="repayAmount = selectedLoan.remaining_balance" class="flex-1 py-2 rounded-lg bg-slate-100 dark:bg-slate-800 text-xs font-bold text-slate-600 dark:text-slate-400 hover:bg-theme hover:text-white transition-colors">Full</button>
                    </div>
                </div>

                <button @click="submitRepayment()" :disabled="isSubmitting || repayAmount <= 0 || repayAmount > balance"
                        class="w-full py-4 rounded-2xl bg-emerald-500 text-white font-black uppercase tracking-widest text-sm hover:brightness-110 transition-all flex items-center justify-center gap-2">
                    <span x-show="!isSubmitting">Confirm Payment</span>
                    <span x-show="isSubmitting" class="flex items-center gap-2">
                        <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                        Processing...
                    </span>
                </button>
            </div>
        </template>
    </div>
  </div>

</div>

<?php if(file_exists('include/footer.php')) include "include/footer.php"; ?>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
    });
    
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 50);
        });
    });
</script>

</body>
</html>