<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: login.php');
    exit();
}

require_once 'admin/config/database.php';

// Format currency display - currency field now contains the actual symbol
function formatCurrency($amount, $currencySymbol) {
    return $currencySymbol . number_format($amount, 2);
}

$database = new Database();
$conn = $database->getConnection();

// Get user data
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: login.php');
    exit();
}

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loan_amount = $_POST['loan_amount'];
    $loan_type = $_POST['loan_type'];
    $term_months = $_POST['term_months'];
    $monthly_payment = $_POST['monthly_payment'];
    $purpose = $_POST['purpose'];
    
    // Validate inputs
    if (empty($loan_amount) || empty($loan_type) || empty($term_months) || empty($monthly_payment)) {
        $message = 'Please fill in all required fields.';
        $message_type = 'error';
    } elseif (!is_numeric($loan_amount) || $loan_amount <= 0) {
        $message = 'Loan amount must be a positive number.';
        $message_type = 'error';
    } elseif (!is_numeric($term_months) || $term_months <= 0) {
        $message = 'Loan term must be a positive number.';
        $message_type = 'error';
    } elseif (!is_numeric($monthly_payment) || $monthly_payment <= 0) {
        $message = 'Monthly payment must be a positive number.';
        $message_type = 'error';
    } elseif (!in_array($loan_type, ['Personal', 'Business', 'Mortgage', 'Auto'])) {
        $message = 'Invalid loan type selected.';
        $message_type = 'error';
    } elseif ($loan_amount < 1000) {
        $message = 'Minimum loan amount is ' . formatCurrency(1000, $_SESSION['currency'] ?? '$') . '.';
        $message_type = 'error';
    } elseif ($loan_amount > 500000) {
        $message = 'Maximum loan amount is ' . formatCurrency(500000, $_SESSION['currency'] ?? '$') . '.';
        $message_type = 'error';
    } elseif ($term_months < 12 || $term_months > 360) {
        $message = 'Loan term must be between 12 and 360 months.';
        $message_type = 'error';
    } elseif ($monthly_payment < 100 || $monthly_payment > 50000) {
        $message = 'Monthly payment must be between ' . formatCurrency(100, $_SESSION['currency'] ?? '$') . ' and ' . formatCurrency(50000, $_SESSION['currency'] ?? '$') . '.';
        $message_type = 'error';
    } else {
        try {
            // Get default interest rate based on loan type (for reference only)
            $interest_rate = 0;
            switch ($loan_type) {
                case 'Personal':
                    $interest_rate = 12.5;
                    break;
                case 'Business':
                    $interest_rate = 10.0;
                    break;
                case 'Mortgage':
                    $interest_rate = 6.5;
                    break;
                case 'Auto':
                    $interest_rate = 8.0;
                    break;
            }
            
            // Insert new loan application with user-provided values
            $stmt = $conn->prepare("INSERT INTO loan_applications (user_id, loan_amount, loan_type, purpose, interest_rate, term_months, monthly_payment, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending')");
            
            if ($stmt->execute([$user_id, $loan_amount, $loan_type, $purpose, $interest_rate, $term_months, $monthly_payment])) {
                $message = 'Loan application submitted successfully! We will review your application and get back to you within 2-3 business days.';
                $message_type = 'success';
            } else {
                $message = 'Failed to submit loan application. Please try again.';
                $message_type = 'error';
            }
        } catch (Exception $e) {
            $message = 'An error occurred. Please try again.';
            $message_type = 'error';
        }
    }
}

// Get user's existing loan applications
$stmt = $conn->prepare("SELECT * FROM loan_applications WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$loan_applications = $stmt->fetchAll();

// Calculate loan statistics
$stmt = $conn->prepare("SELECT COUNT(*) as total_applications FROM loan_applications WHERE user_id = ?");
$stmt->execute([$user_id]);
$total_applications = $stmt->fetch()['total_applications'];

$stmt = $conn->prepare("SELECT SUM(loan_amount) as total_requested FROM loan_applications WHERE user_id = ? AND status IN ('Pending', 'Approved', 'Active')");
$stmt->execute([$user_id]);
$total_requested = $stmt->fetch()['total_requested'] ?? 0;

$stmt = $conn->prepare("SELECT SUM(monthly_payment) as total_monthly_payments FROM loan_applications WHERE user_id = ? AND status IN ('Active', 'Completed')");
$stmt->execute([$user_id]);
$total_monthly_payments = $stmt->fetch()['total_monthly_payments'] ?? 0;

$stmt = $conn->prepare("SELECT COUNT(*) as active_loans FROM loan_applications WHERE user_id = ? AND status = 'Active'");
$stmt->execute([$user_id]);
$active_loans = $stmt->fetch()['active_loans'];

// Get general settings for site name
$siteName = 'TrustBNK';
try {
    $stmt = $conn->prepare("SELECT site_name FROM general_settings WHERE id = 1");
    $stmt->execute();
    $settings = $stmt->fetch();
    
    if ($settings && $settings['site_name']) {
        $siteName = $settings['site_name'];
    }
} catch (Exception $e) {
    // Use default site name if database query fails
    $siteName = 'TrustBNK';
}

$database->closeConnection();

// Get current date and time
$current_date = date('l, F j, Y');
$current_time = date('H:i:s');
$greeting = 'Good Morning';
$hour = (int)date('H');
if ($hour >= 12 && $hour < 17) {
    $greeting = 'Good Afternoon';
} elseif ($hour >= 17) {
    $greeting = 'Good Evening';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loan Request - <?php echo htmlspecialchars($siteName); ?> Credit</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .loan-request-container {
            max-width: 1000px;
            margin: 0 auto;
        }

        .page-header {
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            border: 1px solid #e0e6ed;
        }

        .page-header .header-content h1 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .page-header .header-content h1 i {
            color: #667eea;
        }

        .page-header .header-content p {
            color: #5a6c7d;
            margin: 0;
            font-size: 1.1rem;
        }

        .application-form {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .form-section {
            margin-bottom: 30px;
        }

        .form-section h3 {
            color: #2c3e50;
            margin: 0 0 20px 0;
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .form-section h3 i {
            color: #667eea;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }

        .form-group label .required {
            color: #dc3545;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
            font-family: inherit;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

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

        .form-group .help-text {
            font-size: 0.85rem;
            color: #6c757d;
            margin-top: 5px;
        }

        .loan-type-options {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-top: 10px;
        }

        .loan-type-option {
            border: 2px solid #e0e6ed;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: white;
        }

        .loan-type-option:hover {
            border-color: #667eea;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .loan-type-option.selected {
            border-color: #667eea;
            background: #f8f9ff;
        }

        .loan-type-option input[type="radio"] {
            display: none;
        }

        .loan-type-option .loan-icon {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .loan-type-option .personal {
            color: #28a745;
        }

        .loan-type-option .business {
            color: #007bff;
        }

        .loan-type-option .mortgage {
            color: #fd7e14;
        }

        .loan-type-option .auto {
            color: #6f42c1;
        }

        .loan-type-option .loan-name {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 5px;
        }

        .loan-type-option .loan-description {
            font-size: 0.85rem;
            color: #5a6c7d;
        }

        .form-actions {
            display: flex;
            gap: 15px;
            justify-content: flex-end;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e0e6ed;
        }

        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background: #5a67d8;
            transform: translateY(-2px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .loan-applications {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
        }

        .applications-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        .applications-header h3 {
            color: #2c3e50;
            margin: 0;
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .applications-header h3 i {
            color: #667eea;
        }

        .loan-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .loan-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            border: 1px solid #e9ecef;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .loan-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
        }

        .loan-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .loan-id {
            font-weight: 600;
            color: #2c3e50;
            font-size: 1.1rem;
        }

        .loan-amount {
            font-size: 1.3rem;
            font-weight: 700;
            color: #28a745;
        }

        .loan-details {
            margin-bottom: 15px;
        }

        .loan-detail {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 0.9rem;
        }

        .loan-detail-label {
            color: #5a6c7d;
            font-weight: 500;
        }

        .loan-detail-value {
            color: #2c3e50;
            font-weight: 600;
        }

        .loan-purpose {
            background: white;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-size: 0.9rem;
            color: #495057;
            border-left: 4px solid #667eea;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-approved {
            background: #d1ecf1;
            color: #0c5460;
        }

        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-completed {
            background: #e2e3e5;
            color: #383d41;
        }

        .no-applications {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .no-applications i {
            font-size: 4rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }

        .no-applications h4 {
            color: #5a6c7d;
            margin: 0 0 10px 0;
            font-size: 1.3rem;
        }

        .no-applications p {
            margin: 0;
            font-size: 1rem;
        }

        .loan-benefits {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 30px;
        }

        .loan-benefits h4 {
            color: #2c3e50;
            margin: 0 0 15px 0;
            font-size: 1.1rem;
            font-weight: 600;
        }

        .benefits-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .benefit-item {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 0.9rem;
            color: #5a6c7d;
        }

        .benefit-item i {
            color: #28a745;
            font-size: 1rem;
        }

        .loan-calculator {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            border: 1px solid #e0e6ed;
            margin-bottom: 30px;
        }

        .calculator-header {
            margin-bottom: 25px;
        }

        .calculator-header h3 {
            color: #2c3e50;
            margin: 0 0 10px 0;
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .calculator-header h3 i {
            color: #667eea;
        }

        .calculator-header p {
            color: #5a6c7d;
            margin: 0;
            font-size: 0.95rem;
        }

        .calculator-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            align-items: start;
        }

        .calculator-inputs {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .calculator-results {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 25px;
        }

        .calculator-results h4 {
            margin: 0 0 20px 0;
            font-size: 1.2rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .result-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }

        .result-item:last-child {
            border-bottom: none;
        }

        .result-label {
            font-size: 0.95rem;
            opacity: 0.9;
        }

        .result-value {
            font-size: 1.1rem;
            font-weight: 600;
        }

        .total-payment {
            background: rgba(255,255,255,0.2);
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }

        .total-payment-label {
            font-size: 0.9rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }

        .total-payment-value {
            font-size: 1.4rem;
            font-weight: 700;
        }

        .calculator-input-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .calculator-input-group label {
            font-weight: 600;
            color: #2c3e50;
            font-size: 0.95rem;
        }

        .calculator-input-group input,
        .calculator-input-group select {
            padding: 12px 15px;
            border: 2px solid #e0e6ed;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
            background: white;
            font-family: inherit;
        }

        .calculator-input-group input:focus,
        .calculator-input-group select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .calculator-input-group .input-with-unit {
            position: relative;
        }

        .calculator-input-group .input-unit {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-weight: 500;
        }

        .calculator-actions {
            display: flex;
            gap: 15px;
            margin-top: 20px;
        }

        .btn-calculate {
            background: #28a745;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
            flex: 1;
        }

        .btn-calculate:hover {
            background: #218838;
            transform: translateY(-2px);
        }

        .btn-reset-calc {
            background: #6c757d;
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .btn-reset-calc:hover {
            background: #5a6268;
        }

        .loan-eligibility {
            background: #e8f5e8;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }

        .loan-eligibility h5 {
            color: #155724;
            margin: 0 0 10px 0;
            font-size: 1rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .loan-eligibility p {
            color: #155724;
            margin: 0;
            font-size: 0.9rem;
        }

        @media (max-width: 768px) {
            .loan-request-container {
                padding: 0 20px;
            }
            
            .loan-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .applications-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }
            
            .loan-type-options {
                grid-template-columns: 1fr;
            }
            
            .benefits-grid {
                grid-template-columns: 1fr;
            }
            
            .calculator-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .calculator-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body class="dashboard-page">
    <!-- Top Header Bar -->
    <div class="dashboard-header">
        <div class="header-left">
            <div class="current-balance">
                <span class="balance-label">Current Balance</span>
                <span class="balance-amount"><?php echo formatCurrency($user['balance'], $_SESSION['currency'] ?? '$'); ?></span>
            </div>
        </div>
        <div class="header-center">
            <div class="current-date"><?php echo $current_date; ?></div>
        </div>
        <div class="header-right">
            <div class="header-actions">
                <button class="notification-btn">
                    <i class="fas fa-bell"></i>
                    <span class="notification-badge">3</span>
                </button>
                <div class="user-profile">
                    <div class="user-avatar">
                        <?php if ($user['profile_photo']): ?>
                            <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                        <?php else: ?>
                            <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                        <?php endif; ?>
                    </div>
                    <div class="user-info">
                        <span class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></span>
                        <span class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></span>
                        <span class="kyc-badge">KYC Verified</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="dashboard-container">
        <!-- Mobile Menu Toggle -->
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="fas fa-bars"></i>
        </button>
        
        <!-- Sidebar Overlay -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        
        <!-- Left Sidebar -->
        <aside class="dashboard-sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <div class="logo-emblem">
                        <span class="logo-t">T</span>
                        <span class="logo-b">B</span>
                    </div>
                    <div class="logo-text">
                        <div class="logo-main"><?php echo htmlspecialchars($siteName); ?></div>
                        <div class="logo-sub">Credit</div>
                    </div>
                </div>
            </div>
            
            <div class="user-profile-sidebar">
                <div class="user-avatar-sidebar">
                    <?php if ($user['profile_photo']): ?>
                        <img src="admin/<?php echo htmlspecialchars($user['profile_photo']); ?>" alt="Profile Photo">
                    <?php else: ?>
                        <span><?php echo strtoupper(substr($user['firstname'], 0, 1) . substr($user['lastname'], 0, 1)); ?></span>
                    <?php endif; ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></div>
                    <div class="user-id"><?php echo htmlspecialchars($user['account_number']); ?></div>
                    <span class="kyc-badge">KYC Verified</span>
                </div>
                <div class="profile-actions">
                    <a href="profile.php" class="btn btn-profile">Profile</a>
                    <a href="logout.php" class="btn btn-logout">Logout</a>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <div class="nav-section">
                    <h3>MAIN MENU</h3>
                    <ul>
                        <li>
                            <a href="dashboard.php">
                                <i class="fas fa-home"></i>
                                <span>Dashboard</span>
                            </a>
                        </li>
                        <li>
                            <a href="transactions.php">
                                <i class="fas fa-exchange-alt"></i>
                                <span>Transactions</span>
                            </a>
                        </li>
                        <li>
                            <a href="cards.php">
                                <i class="fas fa-credit-card"></i>
                                <span>Cards</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>TRANSFERS</h3>
                    <ul>
                        <li>
                            <a href="transfer.php">
                                <i class="fas fa-paper-plane"></i>
                                <span>Transfer Funds</span>
                            </a>
                        </li>
                        <li>
                            <a href="deposit.php">
                                <i class="fas fa-arrow-down"></i>
                                <span>Deposit</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>SERVICES</h3>
                    <ul>
                        <li class="active">
                            <a href="loan-request.php">
                                <i class="fas fa-hand-holding-usd"></i>
                                <span>Loan Request</span>
                            </a>
                        </li>
                        <li>
                            <a href="irs-refund.php">
                                <i class="fas fa-file-invoice-dollar"></i>
                                <span>IRS Tax Refund</span>
                            </a>
                        </li>
                    </ul>
                </div>
                
                <div class="nav-section">
                    <h3>ACCOUNT</h3>
                    <ul>
                        <li>
                            <a href="account-info.php">
                                <i class="fas fa-user-circle"></i>
                                <span>Account Info</span>
                            </a>
                        </li>
                        <li>
                            <a href="loan-history.php">
                                <i class="fas fa-history"></i>
                                <span>Loan History</span>
                            </a>
                        </li>
                        <li>
                            <a href="settings.php">
                                <i class="fas fa-cog"></i>
                                <span>Settings</span>
                            </a>
                        </li>
                        <li>
                            <a href="support.php">
                                <i class="fas fa-headset"></i>
                                <span>Support Ticket</span>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>
            
            <div class="sidebar-footer">
                <div class="secure-banking">
                    <i class="fas fa-shield-alt"></i>
                    <span>Secure Banking</span>
                </div>
                <div class="version">v1.2.0</div>
            </div>
        </aside>

        <!-- Main Content Area -->
        <main class="dashboard-main">
            <div class="loan-request-container">
                <!-- Page Header -->
                <div class="page-header">
                    <div class="header-content">
                        <h1><i class="fas fa-hand-holding-usd"></i> Loan Request</h1>
                        <p>Apply for a loan with competitive rates and flexible terms</p>
                    </div>
                </div>

                <!-- Loan Statistics -->
                <div class="overview-cards">
                    <div class="overview-card">
                        <div class="card-icon">
                            <i class="fas fa-file-alt"></i>
                        </div>
                        <div class="card-content">
                            <h3>Total Applications</h3>
                            <div class="card-amount"><?php echo number_format($total_applications); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon income">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="card-content">
                            <h3>Total Requested</h3>
                            <div class="card-amount"><?php echo formatCurrency($total_requested, $_SESSION['currency'] ?? '$'); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon limit">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <div class="card-content">
                            <h3>Monthly Payments</h3>
                            <div class="card-amount"><?php echo formatCurrency($total_monthly_payments, $_SESSION['currency'] ?? '$'); ?></div>
                        </div>
                    </div>
                    
                    <div class="overview-card">
                        <div class="card-icon outgoing">
                            <i class="fas fa-clock"></i>
                        </div>
                        <div class="card-content">
                            <h3>Active Loans</h3>
                            <div class="card-amount"><?php echo number_format($active_loans); ?></div>
                        </div>
                    </div>
                </div>

                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $message_type === 'success' ? 'success' : 'error'; ?>">
                        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                        <?php echo htmlspecialchars($message); ?>
                    </div>
                <?php endif; ?>

                <!-- Loan Benefits -->
                <div class="loan-benefits">
                    <h4><i class="fas fa-star"></i> Why Choose <?php echo htmlspecialchars($siteName); ?> Credit Loans?</h4>
                    <div class="benefits-grid">
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>Competitive interest rates</span>
                        </div>
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>Quick approval process</span>
                        </div>
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>Flexible repayment terms</span>
                        </div>
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>No hidden fees</span>
                        </div>
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>24/7 customer support</span>
                        </div>
                        <div class="benefit-item">
                            <i class="fas fa-check"></i>
                            <span>Online application process</span>
                        </div>
                    </div>
                </div>

                <!-- Loan Calculator -->
                <div class="loan-calculator">
                    <div class="calculator-header">
                        <h3><i class="fas fa-calculator"></i> Loan Calculator</h3>
                        <p>Calculate your monthly payments and total interest before applying</p>
                    </div>
                    
                    <div class="calculator-grid">
                        <div class="calculator-inputs">
                            <div class="calculator-input-group">
                                <label for="calc_loan_amount">Loan Amount</label>
                                <div class="input-with-unit">
                                    <input type="number" id="calc_loan_amount" min="1000" max="500000" step="100" value="25000">
                                    <span class="input-unit"><?php echo $_SESSION['currency'] ?? '$'; ?></span>
                                </div>
                            </div>
                            
                            <div class="calculator-input-group">
                                <label for="calc_loan_type">Loan Type</label>
                                <select id="calc_loan_type">
                                    <option value="Personal">Personal Loan (12.5% APR)</option>
                                    <option value="Business">Business Loan (10.0% APR)</option>
                                    <option value="Mortgage">Mortgage (6.5% APR)</option>
                                    <option value="Auto">Auto Loan (8.0% APR)</option>
                                </select>
                            </div>
                            
                            <div class="calculator-input-group">
                                <label for="calc_term_months">Loan Term</label>
                                <input type="number" id="calc_term_months" min="12" max="360" step="1" value="36">
                                <div class="help-text">Term in months (auto-updated based on loan type)</div>
                            </div>
                            
                            <div class="calculator-input-group">
                                <label for="calc_interest_rate">Interest Rate</label>
                                <div class="input-with-unit">
                                    <input type="number" id="calc_interest_rate" min="1" max="30" step="0.1" value="12.5">
                                    <span class="input-unit">%</span>
                                </div>
                                <div class="help-text">Rate auto-updated based on loan type</div>
                            </div>
                            
                            <div class="calculator-actions">
                                <button type="button" class="btn-calculate" onclick="calculateLoan()">
                                    <i class="fas fa-calculator"></i>
                                    Calculate Payment
                                </button>
                                <button type="button" class="btn-reset-calc" onclick="resetCalculator()">
                                    <i class="fas fa-undo"></i>
                                    Reset
                                </button>
                            </div>
                        </div>
                        
                        <div class="calculator-results">
                            <h4><i class="fas fa-chart-line"></i> Payment Summary</h4>
                            
                            <div class="result-item">
                                <span class="result-label">Monthly Payment:</span>
                                <span class="result-value" id="monthly_payment_result"><?php echo $_SESSION['currency'] ?? '$'; ?>0.00</span>
                            </div>
                            
                            <div class="result-item">
                                <span class="result-label">Total Interest:</span>
                                <span class="result-value" id="total_interest_result"><?php echo $_SESSION['currency'] ?? '$'; ?>0.00</span>
                            </div>
                            
                            <div class="result-item">
                                <span class="result-label">Loan Term:</span>
                                <span class="result-value" id="term_result">0 months</span>
                            </div>
                            
                            <div class="result-item">
                                <span class="result-label">Interest Rate:</span>
                                <span class="result-value" id="rate_result">0.0%</span>
                            </div>
                            
                            <div class="total-payment">
                                <div class="total-payment-label">Total Amount to Pay:</div>
                                <div class="total-payment-value" id="total_payment_result">$0.00</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="loan-eligibility">
                        <h5><i class="fas fa-info-circle"></i> Loan Eligibility</h5>
                        <p>Based on your current balance of $<?php echo number_format($user['balance'], 2); ?>, you may be eligible for loans up to $<?php echo number_format($user['balance'] * 5, 2); ?>. Higher amounts may require additional documentation.</p>
                    </div>
                </div>

                <!-- Application Form -->
                <form method="POST" class="application-form">
                    <div class="form-section">
                        <h3><i class="fas fa-edit"></i> Loan Application Details</h3>
                        
                        <div class="form-group">
                            <label>Loan Type <span class="required">*</span></label>
                            <div class="loan-type-options">
                                <label class="loan-type-option" for="personal">
                                    <input type="radio" id="personal" name="loan_type" value="Personal" required>
                                    <div class="loan-icon personal">
                                        <i class="fas fa-user"></i>
                                    </div>
                                    <div class="loan-name">Personal Loan</div>
                                    <div class="loan-description">12.5% APR, 36 months</div>
                                </label>
                                
                                <label class="loan-type-option" for="business">
                                    <input type="radio" id="business" name="loan_type" value="Business" required>
                                    <div class="loan-icon business">
                                        <i class="fas fa-briefcase"></i>
                                    </div>
                                    <div class="loan-name">Business Loan</div>
                                    <div class="loan-description">10.0% APR, 60 months</div>
                                </label>
                                
                                <label class="loan-type-option" for="mortgage">
                                    <input type="radio" id="mortgage" name="loan_type" value="Mortgage" required>
                                    <div class="loan-icon mortgage">
                                        <i class="fas fa-home"></i>
                                    </div>
                                    <div class="loan-name">Mortgage</div>
                                    <div class="loan-description">6.5% APR, 30 years</div>
                                </label>
                                
                                <label class="loan-type-option" for="auto">
                                    <input type="radio" id="auto" name="loan_type" value="Auto" required>
                                    <div class="loan-icon auto">
                                        <i class="fas fa-car"></i>
                                    </div>
                                    <div class="loan-name">Auto Loan</div>
                                    <div class="loan-description">8.0% APR, 48 months</div>
                                </label>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="loan_amount">Loan Amount <span class="required">*</span></label>
                            <input type="number" id="loan_amount" name="loan_amount" min="1000" max="500000" step="100" required>
                            <div class="help-text">Enter the amount you wish to borrow ($1,000 - $500,000)</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="term_months">Loan Term (Months) <span class="required">*</span></label>
                            <input type="number" id="term_months" name="term_months" min="12" max="360" step="1" required>
                            <div class="help-text">Enter the loan term in months (12-360 months)</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="monthly_payment">Expected Monthly Payment <span class="required">*</span></label>
                            <input type="number" id="monthly_payment" name="monthly_payment" min="100" max="50000" step="0.01" required>
                            <div class="help-text">Enter the monthly payment amount you can afford</div>
                        </div>
                        
                        <div class="form-group">
                            <label for="purpose">Purpose of Loan</label>
                            <textarea id="purpose" name="purpose" placeholder="Please describe the purpose of your loan..."></textarea>
                            <div class="help-text">Provide details about how you plan to use the loan funds</div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="reset" class="btn btn-secondary">
                            <i class="fas fa-undo"></i>
                            Clear Form
                        </button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-paper-plane"></i>
                            Submit Application
                        </button>
                    </div>
                </form>

                <!-- Existing Applications -->
                <div class="loan-applications">
                    <div class="applications-header">
                        <h3><i class="fas fa-history"></i> Your Loan Applications</h3>
                    </div>
                    
                    <?php if (empty($loan_applications)): ?>
                        <div class="no-applications">
                            <i class="fas fa-file-alt"></i>
                            <h4>No Loan Applications</h4>
                            <p>You haven't submitted any loan applications yet. Use the form above to submit your first application.</p>
                        </div>
                    <?php else: ?>
                        <div class="loan-grid">
                            <?php foreach ($loan_applications as $application): ?>
                                <div class="loan-card">
                                    <div class="loan-header">
                                        <div class="loan-id">Application #<?php echo str_pad($application['id'], 6, '0', STR_PAD_LEFT); ?></div>
                                        <div class="loan-amount">$<?php echo number_format($application['loan_amount'], 2); ?></div>
                                    </div>
                                    
                                    <div class="loan-details">
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Type:</span>
                                            <span class="loan-detail-value"><?php echo htmlspecialchars($application['loan_type']); ?></span>
                                        </div>
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Status:</span>
                                            <span class="status-badge status-<?php echo strtolower($application['status']); ?>">
                                                <?php echo htmlspecialchars($application['status']); ?>
                                            </span>
                                        </div>
                                        <?php if ($application['interest_rate']): ?>
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Interest Rate:</span>
                                            <span class="loan-detail-value"><?php echo $application['interest_rate']; ?>%</span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($application['term_months']): ?>
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Term:</span>
                                            <span class="loan-detail-value"><?php echo $application['term_months']; ?> months</span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($application['monthly_payment']): ?>
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Monthly Payment:</span>
                                            <span class="loan-detail-value"><?php echo formatCurrency($application['monthly_payment'], $_SESSION['currency'] ?? '$'); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="loan-detail">
                                            <span class="loan-detail-label">Applied:</span>
                                            <span class="loan-detail-value"><?php echo date('M j, Y', strtotime($application['created_at'])); ?></span>
                                        </div>
                                    </div>
                                    
                                    <?php if ($application['purpose']): ?>
                                        <div class="loan-purpose">
                                            <strong>Purpose:</strong><br>
                                            <?php echo htmlspecialchars($application['purpose']); ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <script src="assets/js/main.js"></script>
    <script>
        // Loan type selection handling
        document.addEventListener('DOMContentLoaded', function() {
            const loanOptions = document.querySelectorAll('.loan-type-option');
            
            loanOptions.forEach(option => {
                option.addEventListener('click', function() {
                    // Remove selected class from all options
                    loanOptions.forEach(opt => opt.classList.remove('selected'));
                    
                    // Add selected class to clicked option
                    this.classList.add('selected');
                    
                    // Check the radio button
                    this.querySelector('input[type="radio"]').checked = true;
                });
            });
            
            // Calculator loan type change handler
            const calcLoanType = document.getElementById('calc_loan_type');
            calcLoanType.addEventListener('change', function() {
                updateCalculatorDefaults();
            });
            
            // Initialize calculator with defaults
            updateCalculatorDefaults();
            calculateLoan();
        });
        
        // Update calculator defaults based on loan type
        function updateCalculatorDefaults() {
            const loanType = document.getElementById('calc_loan_type').value;
            const termInput = document.getElementById('calc_term_months');
            const rateInput = document.getElementById('calc_interest_rate');
            
            const loanDefaults = {
                'Personal': { term: 36, rate: 12.5 },
                'Business': { term: 60, rate: 10.0 },
                'Mortgage': { term: 360, rate: 6.5 },
                'Auto': { term: 48, rate: 8.0 }
            };
            
            const defaults = loanDefaults[loanType];
            termInput.value = defaults.term;
            rateInput.value = defaults.rate;
        }
        
        // Calculate loan payments
        function calculateLoan() {
            const loanAmount = parseFloat(document.getElementById('calc_loan_amount').value) || 0;
            const interestRate = parseFloat(document.getElementById('calc_interest_rate').value) || 0;
            const termMonths = parseInt(document.getElementById('calc_term_months').value) || 0;
            
            if (loanAmount <= 0 || termMonths <= 0) {
                return;
            }
            
            const monthlyRate = interestRate / 100 / 12;
            let monthlyPayment = 0;
            let totalInterest = 0;
            
            if (monthlyRate > 0) {
                monthlyPayment = loanAmount * (monthlyRate * Math.pow(1 + monthlyRate, termMonths)) / (Math.pow(1 + monthlyRate, termMonths) - 1);
            } else {
                monthlyPayment = loanAmount / termMonths;
            }
            
            totalInterest = (monthlyPayment * termMonths) - loanAmount;
            const totalPayment = monthlyPayment * termMonths;
            
            // Update results
            const currencySymbol = '<?php echo $_SESSION['currency'] ?? '$'; ?>';
            document.getElementById('monthly_payment_result').textContent = currencySymbol + monthlyPayment.toFixed(2);
            document.getElementById('total_interest_result').textContent = currencySymbol + totalInterest.toFixed(2);
            document.getElementById('term_result').textContent = termMonths + ' months';
            document.getElementById('rate_result').textContent = interestRate.toFixed(1) + '%';
            document.getElementById('total_payment_result').textContent = currencySymbol + totalPayment.toFixed(2);
        }
        
        // Reset calculator
        function resetCalculator() {
            document.getElementById('calc_loan_amount').value = 25000;
            document.getElementById('calc_loan_type').value = 'Personal';
            document.getElementById('calc_term_months').value = 36;
            document.getElementById('calc_interest_rate').value = 12.5;
            
            // Clear results
            const currencySymbol = '<?php echo $_SESSION['currency'] ?? '$'; ?>';
            document.getElementById('monthly_payment_result').textContent = currencySymbol + '0.00';
            document.getElementById('total_interest_result').textContent = currencySymbol + '0.00';
            document.getElementById('term_result').textContent = '0 months';
            document.getElementById('rate_result').textContent = '0.0%';
            document.getElementById('total_payment_result').textContent = currencySymbol + '0.00';
        }
        
        // Auto-calculate on input change
        document.addEventListener('input', function(e) {
            if (e.target.matches('#calc_loan_amount, #calc_interest_rate, #calc_term_months')) {
                calculateLoan();
            }
        });
    </script>
    <script src="assets/js/logout-confirmation.js"></script>
</body>
</html>