<?php
// Enable error reporting for debugging purposes
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';

// Fetch all of this user's loans (ordered by creation date descending)
$stmt = $pdo->prepare("
    SELECT *
      FROM loans 
     WHERE user_id = ?
  ORDER BY created_at DESC
");
$stmt->execute([$userId]);
$loans = $stmt->fetchAll();

// Fetch user's account balance
$accountStmt = $pdo->prepare("
    SELECT balance 
      FROM accounts 
     WHERE user_id = ?
");
$accountStmt->execute([$userId]);
$account = $accountStmt->fetch();
$balance = $account ? $account['balance'] : 0;

// Generate and store CSRF token to prevent double submissions
if (empty($_SESSION['loan_token'])) {
    $_SESSION['loan_token'] = bin2hex(random_bytes(32));
}
$token = $_SESSION['loan_token'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['token']) || $_POST['token'] !== $_SESSION['loan_token']) {
        $error = "Duplicate submission or invalid token.";
    } else {
        // Sanitize and validate input
        $amount = filter_var($_POST['amount'], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        $term = intval($_POST['term']);
        $purpose = htmlspecialchars($_POST['purpose'], ENT_QUOTES, 'UTF-8');

        // Validate ID and selfie file uploads
        $uploadErrors = [];
        $uploadDir = '../uploads/loan_verifications/';

        // Create upload directory if it doesn't exist
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }

        $idSelfiePath = null;
        $idDocumentPath = null;

        // Validate and process ID selfie upload
        if (!isset($_FILES['id_selfie']) || $_FILES['id_selfie']['error'] !== UPLOAD_ERR_OK) {
            $uploadErrors[] = "Please upload a valid selfie holding your ID.";
        } else {
            $allowedTypes = ['image/jpeg', 'image/png'];
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if (!in_array($_FILES['id_selfie']['type'], $allowedTypes)) {
                $uploadErrors[] = "Invalid file type for selfie. Please upload JPG or PNG files only.";
            }

            if ($_FILES['id_selfie']['size'] > $maxFileSize) {
                $uploadErrors[] = "Selfie file size too large. Maximum size is 5MB.";
            }

            if (empty($uploadErrors)) {
                $fileExtension = pathinfo($_FILES['id_selfie']['name'], PATHINFO_EXTENSION);
                $fileName = 'selfie_' . $userId . '_' . time() . '.' . $fileExtension;
                $filePath = $uploadDir . $fileName;
                if (move_uploaded_file($_FILES['id_selfie']['tmp_name'], $filePath)) {
                    $idSelfiePath = str_replace('../', '', $filePath);
                } else {
                    $uploadErrors[] = "Failed to upload selfie file.";
                }
            }
        }

        // Validate and process ID document upload
        if (!isset($_FILES['id_document']) || $_FILES['id_document']['error'] !== UPLOAD_ERR_OK) {
            $uploadErrors[] = "Please upload a valid ID document.";
        } else {
            $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            $maxFileSize = 5 * 1024 * 1024; // 5MB

            if (!in_array($_FILES['id_document']['type'], $allowedTypes)) {
                $uploadErrors[] = "Invalid file type for ID document. Please upload JPG, PNG, or PDF files only.";
            }

            if ($_FILES['id_document']['size'] > $maxFileSize) {
                $uploadErrors[] = "ID document file size too large. Maximum size is 5MB.";
            }

            if (empty($uploadErrors)) {
                $fileExtension = pathinfo($_FILES['id_document']['name'], PATHINFO_EXTENSION);
                $fileName = 'document_' . $userId . '_' . time() . '.' . $fileExtension;
                $filePath = $uploadDir . $fileName;
                if (move_uploaded_file($_FILES['id_document']['tmp_name'], $filePath)) {
                    $idDocumentPath = str_replace('../', '', $filePath);
                } else {
                    $uploadErrors[] = "Failed to upload ID document file.";
                }
            }
        }

        if (!empty($uploadErrors)) {
            $error = implode('<br>', $uploadErrors);
        } elseif ($amount < 100) {
            $error = "Minimum loan amount is $100";
        } elseif ($amount > 50000) {
            $error = "Maximum loan amount is $50,000";
        } elseif ($term < 1 || $term > 60) {
            $error = "Loan term must be between 1 and 60 months";
        } else {
            // Calculate interest rate
            $interestRate = 5.0;
            if ($amount > 10000) {
                $interestRate = 4.5;
            }
            if ($term > 36) {
                $interestRate += 1.0;
            }

            try {
                // Insert new loan application with status = 'pending' and file paths
                $stmt = $pdo->prepare("
                    INSERT INTO loans (
                        user_id, 
                        amount, 
                        interest_rate, 
                        term_months, 
                        status, 
                        purpose,
                        total_due,
                        is_paid,
                        penalty_amount,
                        id_selfie_file_path,
                        id_document_file_path
                    ) VALUES (
                        ?, ?, ?, ?, 'pending', ?, 
                        ?, 'no', 0.00, ?, ?
                    )
                ");
                $stmt->execute([
                    $userId,
                    $amount,
                    $interestRate,
                    $term,
                    $purpose,
                    $amount, // total_due initialized to amount
                    $idSelfiePath,
                    $idDocumentPath
                ]);

                // Regenerate token to prevent double submissions
                $_SESSION['loan_token'] = bin2hex(random_bytes(32));

                $success = "Loan application submitted successfully! Please wait for review.";
            } catch (Exception $e) {
                $error = "Failed to submit loan application: " . $e->getMessage();
            }
        }
    }
}

// ──────────────────────────────────────────────────────────────────────────────
// FETCH "Quick Summary" VALUES
// ──────────────────────────────────────────────────────────────────────────────

// 1) Total Loan Balance & Current Active Loans (approved, not yet paid)
$summaryStmt = $pdo->prepare("
    SELECT 
       COALESCE(SUM(total_due), 0)   AS total_balance,
       COUNT(*)                     AS active_loans
      FROM loans
     WHERE user_id = ?
       AND status = 'approved'
       AND is_paid = 'no'
");
$summaryStmt->execute([$userId]);
$summary = $summaryStmt->fetch();

$totalBalance = $summary['total_balance'];
$activeLoans = $summary['active_loans'];

// 2) Total Pending Loan
$pendingStmt = $pdo->prepare("
    SELECT COALESCE(SUM(amount), 0) AS pending_amount
      FROM loans
     WHERE user_id = ?
       AND status = 'pending'
");
$pendingStmt->execute([$userId]);
$pending = $pendingStmt->fetch();
$totalPending = $pending['pending_amount'];

// 3) Last Loan Taken (most recent created_at, regardless of status)
$lastLoanStmt = $pdo->prepare("
    SELECT amount, created_at
      FROM loans
     WHERE user_id = ?
  ORDER BY created_at DESC
     LIMIT 1
");
$lastLoanStmt->execute([$userId]);
$lastLoan = $lastLoanStmt->fetch();

// 4) Next Payment (estimate for oldest approved loan)
$nextPaymentAmount = null;
$nextPaymentDate = null;

$nextLoanStmt = $pdo->prepare("
    SELECT approved_at, total_due, term_months
      FROM loans
     WHERE user_id = ?
       AND status = 'approved'
       AND is_paid = 'no'
  ORDER BY approved_at ASC
     LIMIT 1
");
$nextLoanStmt->execute([$userId]);
$nextLoan = $nextLoanStmt->fetch();

if ($nextLoan && !empty($nextLoan['approved_at'])) {
    $monthlyInstallment = floatval($nextLoan['total_due']) / max(1, intval($nextLoan['term_months']));
    $timestamp = strtotime($nextLoan['approved_at'] . ' +1 month');
    $nextDueString = date('M j, Y', $timestamp);
    $nextPaymentAmount = $monthlyInstallment;
    $nextPaymentDate = $nextDueString;
}

// 5) Loan Application History Summary
$appHistoryStmt = $pdo->prepare("
    SELECT 
      COUNT(*) AS total_apps,
      SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) AS approved_count,
      SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) AS rejected_count
    FROM loans
    WHERE user_id = ?
");
$appHistoryStmt->execute([$userId]);
$appHistory = $appHistoryStmt->fetch();

$totalApps = $appHistory['total_apps'];
$approvedCount = $appHistory['approved_count'];
$rejectedCount = $appHistory['rejected_count'];

// 6) Overdue Payments
$overdueStmt = $pdo->prepare("
    SELECT COALESCE(SUM(penalty_amount), 0) AS total_overdue
      FROM loans
     WHERE user_id = ?
       AND status = 'approved'
       AND is_paid = 'no'
       AND penalty_amount > 0
");
$overdueStmt->execute([$userId]);
$overdue = $overdueStmt->fetch();
$totalOverdue = $overdue['total_overdue'];

// Get user account information for sidebar
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
      FROM users u 
      JOIN accounts a ON u.user_id = a.user_id 
     WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

// Check if the user has a profile picture
$stmt = $pdo->prepare("SELECT profile_picture FROM users WHERE user_id = ?");
$stmt->execute([$userId]);
$picRow = $stmt->fetch();
$profilePic = $picRow['profile_picture']
    ? '../uploads/' . $picRow['profile_picture']
    : '../assets/images/default-avatars.png';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Oakshire Finance - Loans</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --accent-blue: #2c7da0;
            --success-green: #2e7d32;
            --warning-orange: #f39c12;
            --error-red: #dc3545;
            --info-blue: #17a2b8;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
            overflow-x: hidden;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
            letter-spacing: -0.3px;
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-avatar i {
            font-size: 40px;
            color: white;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            color: var(--gray-900);
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .nav-link.active i {
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            transition: var(--transition);
            font-weight: 500;
        }

        .logout-btn:hover {
            background: rgba(220, 53, 69, 0.1);
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        /* Top Header */
        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            position: relative;
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
            transition: var(--transition);
        }

        .notification-btn:hover {
            color: var(--primary-blue);
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Balance Card */
        .balance-card {
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-dark));
            border-radius: 20px;
            padding: 24px;
            margin-bottom: 32px;
            color: white;
        }

        .balance-card h3 {
            font-size: 14px;
            font-weight: 500;
            opacity: 0.8;
            margin-bottom: 8px;
        }

        .balance-amount {
            font-size: 36px;
            font-weight: 700;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: var(--white);
            border-radius: 20px;
            padding: 20px;
            border: 1px solid var(--gray-200);
            transition: var(--transition);
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: var(--shadow-hover);
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            background: rgba(26, 77, 140, 0.1);
            border-radius: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
        }

        .stat-icon i {
            font-size: 24px;
            color: var(--primary-blue);
        }

        .stat-card h3 {
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-600);
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: var(--gray-900);
        }

        /* Loan Form Card */
        .loan-card {
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            padding: 32px;
            margin-bottom: 32px;
        }

        .loan-card h2 {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .form-group small {
            display: block;
            font-size: 12px;
            color: var(--gray-500);
            margin-top: 4px;
        }

        .btn-primary {
            width: 100%;
            padding: 14px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        /* Summary Card */
        .summary-card {
            background: var(--white);
            border-radius: 20px;
            padding: 24px;
            border: 1px solid var(--gray-200);
            margin-bottom: 32px;
        }

        .summary-card h2 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        .summary-list {
            list-style: none;
        }

        .summary-list li {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid var(--gray-200);
        }

        .summary-list li:last-child {
            border-bottom: none;
        }

        .summary-list strong {
            color: var(--primary-blue);
        }

        .btn-secondary {
            display: inline-block;
            width: 100%;
            padding: 12px;
            background: var(--success-green);
            color: white;
            text-align: center;
            text-decoration: none;
            border-radius: 12px;
            font-weight: 600;
            margin-top: 16px;
            transition: var(--transition);
        }

        .btn-secondary:hover {
            background: #1b5e1f;
            transform: translateY(-2px);
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 500px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 13px;
        }

        /* Badges */
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-pending {
            background: rgba(243, 156, 18, 0.1);
            color: var(--warning-orange);
        }

        .badge-approved {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .badge-rejected {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        /* Alerts */
        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        /* Hamburger Menu */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-700);
        }

        /* Mobile Responsive */
        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .balance-amount {
                font-size: 28px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .loan-card {
                padding: 20px;
            }

            .summary-card {
                padding: 20px;
            }

            .summary-list li {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }

            .data-table th,
            .data-table td {
                padding: 12px 16px;
            }
        }

        @media (max-width: 480px) {
            .balance-amount {
                font-size: 24px;
            }

            .stat-value {
                font-size: 24px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar Navigation -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon">
                        <i class="fas fa-building-columns"></i>
                    </div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <?php if ($user['profile_picture']): ?>
                        <img src="<?= $profilePic ?>" alt="Profile Picture">
                    <?php else: ?>
                        <i class="fas fa-user-circle"></i>
                    <?php endif; ?>
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item">
                    <a href="dashboard.php" class="nav-link">
                        <i class="fas fa-chart-line"></i>
                        <span>Dashboard</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="deposit.php" class="nav-link">
                        <i class="fas fa-arrow-down"></i>
                        <span>Deposit</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="withdraw.php" class="nav-link">
                        <i class="fas fa-arrow-up"></i>
                        <span>Withdraw</span>
                    </a>
                </div>

                <div class="nav-item"><a href="cards.php" class="nav-link "><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item">
                    <a href="transactions.php" class="nav-link">
                        <i class="fas fa-receipt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="investment.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Investment</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan.php" class="nav-link active">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="profile.php" class="nav-link">
                        <i class="fas fa-user-circle"></i>
                        <span>Settings</span>
                    </a>
                </div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <button class="hamburger" id="hamburger">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="page-title">
                    <h1>Loan Management</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn">
                        <i class="fas fa-bell"></i>
                    </button>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Balance Card -->
                <div class="balance-card">
                    <h3>Available Balance</h3>
                    <div class="balance-amount">$<?= number_format($balance, 2) ?></div>
                </div>

                <!-- Stats Grid -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <h3>Total Loan Balance</h3>
                        <div class="stat-value">$<?= number_format($totalBalance, 2) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-hand-holding-usd"></i>
                        </div>
                        <h3>Active Loans</h3>
                        <div class="stat-value"><?= number_format($activeLoans) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-clock"></i>
                        </div>
                        <h3>Pending Applications</h3>
                        <div class="stat-value">$<?= number_format($totalPending, 2) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-exclamation-triangle"></i>
                        </div>
                        <h3>Overdue Payments</h3>
                        <div class="stat-value">$<?= number_format($totalOverdue, 2) ?></div>
                    </div>
                </div>

                <!-- Apply for Loan Form -->
                <div class="loan-card">
                    <h2><i class="fas fa-plus-circle"></i> Apply for a Loan</h2>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle"></i>
                            <span><?= $error ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle"></i>
                            <span><?= $success ?></span>
                        </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

                        <div class="form-group">
                            <label for="amount">Loan Amount ($)</label>
                            <input type="number" name="amount" id="amount" min="100" max="50000" step="100" required>
                            <small>Minimum: $100 | Maximum: $50,000</small>
                        </div>

                        <div class="form-group">
                            <label for="term">Loan Term (months)</label>
                            <input type="number" name="term" id="term" min="1" max="60" required>
                            <small>Term must be between 1 and 60 months</small>
                        </div>

                        <div class="form-group">
                            <label for="purpose">Purpose of Loan</label>
                            <textarea name="purpose" id="purpose" required
                                placeholder="e.g., Home renovation, Education, Business, Medical expenses, etc."></textarea>
                        </div>

                        <div class="form-group">
                            <label for="id_selfie">Upload Selfie with ID (JPG, PNG)</label>
                            <input type="file" name="id_selfie" id="id_selfie" accept=".jpg,.jpeg,.png" required>
                            <small>Upload a clear photo of yourself holding your ID.</small>
                        </div>

                        <div class="form-group">
                            <label for="id_document">Upload ID Document (JPG, PNG, PDF)</label>
                            <input type="file" name="id_document" id="id_document" accept=".jpg,.jpeg,.png,.pdf"
                                required>
                            <small>Upload a clear photo or scan of your valid ID document.</small>
                        </div>

                        <button type="submit" class="btn-primary">
                            <i class="fas fa-paper-plane"></i> Apply for Loan
                        </button>
                    </form>
                </div>

                <!-- Quick Summary -->
                <div class="summary-card">
                    <h2><i class="fas fa-chart-simple"></i> Loan Summary</h2>
                    <ul class="summary-list">
                        <li>
                            <span>Total Loan Balance:</span>
                            <strong>$<?= number_format($totalBalance, 2) ?></strong>
                        </li>
                        <li>
                            <span>Active Loans:</span>
                            <strong><?= $activeLoans ?></strong>
                        </li>
                        <li>
                            <span>Next Payment:</span>
                            <strong>
                                <?php if ($nextPaymentAmount !== null && $nextPaymentDate !== null): ?>
                                    $<?= number_format($nextPaymentAmount, 2) ?> due on <?= $nextPaymentDate ?>
                                <?php else: ?>
                                    N/A
                                <?php endif; ?>
                            </strong>
                        </li>
                        <li>
                            <span>Last Loan Taken:</span>
                            <strong>
                                <?php if ($lastLoan): ?>
                                    $<?= number_format($lastLoan['amount'], 2) ?> on
                                    <?= date('M j, Y', strtotime($lastLoan['created_at'])) ?>
                                <?php else: ?>
                                    N/A
                                <?php endif; ?>
                            </strong>
                        </li>
                        <li>
                            <span>Pending Applications:</span>
                            <strong>$<?= number_format($totalPending, 2) ?></strong>
                        </li>
                        <li>
                            <span>Overdue Payments:</span>
                            <strong class="badge"
                                style="background: rgba(220, 53, 69, 0.1); color: var(--error-red);">$<?= number_format($totalOverdue, 2) ?></strong>
                        </li>
                        <li>
                            <span>Total Applications:</span>
                            <strong><?= $totalApps ?> (<?= $approvedCount ?> approved, <?= $rejectedCount ?>
                                rejected)</strong>
                        </li>
                    </ul>
                    <a href="loan-payment.php" class="btn-secondary">
                        <i class="fas fa-credit-card"></i> Make a Loan Payment
                    </a>
                </div>

                <!-- Your Loans List -->
                <div class="loan-card" style="padding: 0; overflow: hidden;">
                    <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                        <h2><i class="fas fa-history"></i> Your Loans</h2>
                    </div>
                    <div class="table-container" style="margin: 0; border-radius: 0;">
                        <?php if (empty($loans)): ?>
                            <div style="text-align: center; padding: 48px; color: var(--gray-500);">
                                <i class="fas fa-hand-holding-usd"
                                    style="font-size: 48px; margin-bottom: 16px; opacity: 0.5;"></i>
                                <p>You have no loans at the moment.</p>
                            </div>
                        <?php else: ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Amount</th>
                                        <th>Interest</th>
                                        <th>Term</th>
                                        <th>Due Date</th>
                                        <th>Status</th>
                                        <th>Applied On</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($loans as $loan):
                                        $statusClass = '';
                                        if ($loan['status'] === 'pending')
                                            $statusClass = 'badge-pending';
                                        elseif ($loan['status'] === 'approved')
                                            $statusClass = 'badge-approved';
                                        else
                                            $statusClass = 'badge-rejected';

                                        // Calculate due date
                                        $dueDate = 'N/A';
                                        if (!empty($loan['created_at'])) {
                                            $appliedDate = new DateTime($loan['created_at']);
                                            $appliedDate->modify('+' . $loan['term_months'] . ' months');
                                            $dueDate = $appliedDate->format('M j, Y');
                                        }
                                        ?>
                                        <tr>
                                            <td><strong>$<?= number_format($loan['amount'], 2) ?></strong></td>
                                            <td><?= $loan['interest_rate'] ?>%</td>
                                            <td><?= $loan['term_months'] ?> months</td>
                                            <td><?= $dueDate ?></td>
                                            <td>
                                                <span class="badge <?= $statusClass ?>">
                                                    <?= ucfirst($loan['status']) ?>
                                                </span>
                                            </td>
                                            <td><?= date('M j, Y', strtotime($loan['created_at'])) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                sidebar.classList.toggle('mobile-open');
            });
        }

        // Close sidebar when clicking outside on mobile
        document.addEventListener('click', function (event) {
            if (window.innerWidth <= 1024) {
                const isClickInside = sidebar.contains(event.target) || hamburger.contains(event.target);
                if (!isClickInside && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Auto-dismiss alerts after 5 seconds
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });

        // Real-time amount formatting
        const amountInput = document.getElementById('amount');
        if (amountInput) {
            amountInput.addEventListener('input', function () {
                let value = parseFloat(this.value);
                if (value < 100) {
                    this.setCustomValidity('Minimum loan amount is $100');
                } else if (value > 50000) {
                    this.setCustomValidity('Maximum loan amount is $50,000');
                } else {
                    this.setCustomValidity('');
                }
            });
        }
    </script>
</body>

</html>