<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/notification.php';

// Redirect if not admin
redirectIfNotAdmin();

// Add this after the require statements at the top
function calculatePenalty($loan)
{
    $currentDate = new DateTime();
    $approvedDate = new DateTime($loan['approved_at']);
    $termEndDate = clone $approvedDate;
    $termEndDate->modify('+' . $loan['term_months'] . ' months');

    if ($currentDate > $termEndDate) {
        $penaltyRate = 0.05; // 5% penalty
        $penaltyAmount = $loan['total_due'] * $penaltyRate;
        return $penaltyAmount;
    }
    return 0;
}

// Handle loan approval, rejection, or deletion
if (isset($_GET['id']) && isset($_GET['action'])) {
    $loanId = $_GET['id'];
    $action = $_GET['action'];

    // Initialize the status and email variables
    $status = null;
    $subject = '';
    $messageHtml = '';
    $messagePlain = '';

    if ($action == 'approve' || $action == 'reject') {
        $status = ($action == 'approve') ? 'approved' : 'rejected';
        $approvedAt = ($action == 'approve') ? date('Y-m-d H:i:s') : null;

        // Fetch loan details
        $stmt = $pdo->prepare("SELECT amount, interest_rate, user_id FROM loans WHERE loan_id = ?");
        $stmt->execute([$loanId]);
        $loan = $stmt->fetch();

        if ($loan) {
            $amount = $loan['amount'];
            $interest = $loan['interest_rate'];
            $totalDue = $amount + ($amount * ($interest / 100));

            // Update loan status
            $stmt = $pdo->prepare("UPDATE loans SET status = ?, approved_at = ?, total_due = ?, amount = ?, due_date = DATE_SUB(DATE_ADD(?, INTERVAL term_months MONTH), INTERVAL 1 DAY), is_paid = 'no' WHERE loan_id = ?");
            $stmt->execute([$status, $approvedAt, $totalDue, $amount, $approvedAt, $loanId]);

            // Insert into loan_history to track status change
            $stmt = $pdo->prepare("INSERT INTO loan_history (loan_id, status, changed_at) VALUES (?, ?, ?)");
            $stmt->execute([$loanId, $status, date('Y-m-d H:i:s')]);

            // If the loan is approved, update the user's account balance
            if ($action == 'approve') {
                $stmt = $pdo->prepare("UPDATE accounts SET balance = balance + ? WHERE user_id = ?");
                $stmt->execute([$amount, $loan['user_id']]);

                // Insert transaction record for approved loan
                $stmt = $pdo->prepare("SELECT account_id FROM accounts WHERE user_id = ?");
                $stmt->execute([$loan['user_id']]);
                $account = $stmt->fetch();
                $accountId = $account['account_id'];

                $stmt = $pdo->prepare('INSERT INTO transactions (account_id, type, amount, description, created_at) VALUES (?, \'approved_loan\', ?, ?, NOW())');
                $stmt->execute([$accountId, $amount, 'Loan approved: $' . number_format($amount, 2)]);
            }

            // Fetch user's email for notification
            $stmt = $pdo->prepare("SELECT email FROM users WHERE user_id = ?");
            $stmt->execute([$loan['user_id']]);
            $user = $stmt->fetch();

            if ($user) {
                // Prepare the email content
                if ($action == 'approve') {
                    $subject = 'Your Loan Request Has Been Approved';
                    $messageHtml = "<p>Dear User,</p><p>Your loan request has been <strong>approved</strong>.</p><p>Amount: $" . number_format($amount, 2) . "<br>Total Due: $" . number_format($totalDue, 2) . "</p><p>Thank you for choosing us.</p>";
                    $messagePlain = "Dear User, Your loan request has been approved.\nAmount: $" . number_format($amount, 2) . "\nTotal Due: $" . number_format($totalDue, 2) . "\nThank you for choosing us.";
                } else {
                    $subject = 'Your Loan Request Has Been Rejected';
                    $messageHtml = "<p>Dear User,</p><p>Your loan request has been <strong>rejected</strong>.</p><p>We regret to inform you that we are unable to process your loan request at this time.</p><p>Thank you.</p>";
                    $messagePlain = "Dear User, Your loan request has been rejected.\nWe regret to inform you that we are unable to process your loan request at this time.\nThank you.";
                }

                // Send the notification email
                sendNotification($user['email'], $subject, $messageHtml, $messagePlain);
            }
        }
    } elseif ($action == 'delete') {
        // Fetch loan details first for email notification
        $stmt = $pdo->prepare("SELECT user_id FROM loans WHERE loan_id = ?");
        $stmt->execute([$loanId]);
        $loan = $stmt->fetch();

        // Delete loan
        $stmt = $pdo->prepare("DELETE FROM loans WHERE loan_id = ?");
        $stmt->execute([$loanId]);

        // Delete loan history
        $stmt = $pdo->prepare("DELETE FROM loan_history WHERE loan_id = ?");
        $stmt->execute([$loanId]);

        // Fetch user's email for notification
        if ($loan) {
            $stmt = $pdo->prepare("SELECT email FROM users WHERE user_id = ?");
            $stmt->execute([$loan['user_id']]);
            $user = $stmt->fetch();

            if ($user) {
                // Send deletion notification email
                sendNotification($user['email'], 'Your Loan Has Been Deleted', 'Your loan request has been deleted from our system.', 'Your loan request has been deleted from our system.');
            }
        }
    }

    header("Location: manage-loans.php");
    exit;
}

// Limit for displaying results
$perPage = 10;
$pendingPage = isset($_GET['pending_page']) && is_numeric($_GET['pending_page']) ? (int) $_GET['pending_page'] : 1;
$approvedPage = isset($_GET['approved_page']) && is_numeric($_GET['approved_page']) ? (int) $_GET['approved_page'] : 1;
$pendingOffset = ($pendingPage - 1) * $perPage;
$approvedOffset = ($approvedPage - 1) * $perPage;

// Count total pending and approved loans
$totalPending = $pdo->query("SELECT COUNT(*) FROM loans WHERE status = 'pending'")->fetchColumn();
$totalPendingPages = ceil($totalPending / $perPage);
$totalApproved = $pdo->query("SELECT COUNT(*) FROM loans WHERE status = 'approved' AND is_paid = 'no'")->fetchColumn();
$totalApprovedPages = ceil($totalApproved / $perPage);

// Fetch pending loan requests
$pendingLoansStmt = $pdo->prepare("
    SELECT l.*, u.full_name, u.email
    FROM loans l
    JOIN users u ON l.user_id = u.user_id
    WHERE l.status = 'pending'
    ORDER BY l.created_at DESC
    LIMIT :perPage OFFSET :offset
");
$pendingLoansStmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$pendingLoansStmt->bindValue(':offset', $pendingOffset, PDO::PARAM_INT);
$pendingLoansStmt->execute();
$pendingLoans = $pendingLoansStmt->fetchAll();

// Fetch recent approved loans
$approvedLoansStmt = $pdo->prepare("
    SELECT l.*, u.full_name, u.email
    FROM loans l
    JOIN users u ON l.user_id = u.user_id
    WHERE l.status = 'approved' AND l.is_paid = 'no'
    ORDER BY l.approved_at DESC
    LIMIT :perPage OFFSET :offset
");
$approvedLoansStmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$approvedLoansStmt->bindValue(':offset', $approvedOffset, PDO::PARAM_INT);
$approvedLoansStmt->execute();
$approvedLoans = $approvedLoansStmt->fetchAll();

// Update penalty amounts for all approved loans
foreach ($approvedLoans as &$loan) {
    $currentDate = new DateTime();
    $approvedDate = new DateTime($loan['approved_at']);
    $termEndDate = clone $approvedDate;
    $termEndDate->modify('+' . $loan['term_months'] . ' months');

    if ($currentDate > $termEndDate) {
        $daysOverdue = $currentDate->diff($termEndDate)->days;
        $penaltyRate = 0.01; // 1% penalty per day
        $penaltyAmount = $loan['total_due'] * ($penaltyRate * $daysOverdue);

        // Update the penalty amount in the database
        $updateStmt = $pdo->prepare("UPDATE loans SET penalty_amount = ? WHERE loan_id = ?");
        $updateStmt->execute([$penaltyAmount, $loan['loan_id']]);

        // Update the penalty amount in our current result set
        $loan['penalty_amount'] = $penaltyAmount;
    } else {
        $loan['penalty_amount'] = 0;
    }
}

// Get current admin info
$adminId = $_SESSION['user_id'];
$adminInfo = $pdo->prepare("SELECT full_name, email FROM users WHERE user_id = ?");
$adminInfo->execute([$adminId]);
$admin = $adminInfo->fetch();

// Calculate totals for stats
$totalLoanAmount = $pdo->query("SELECT SUM(amount) FROM loans WHERE status = 'approved'")->fetchColumn();
$totalLoanAmount = $totalLoanAmount ?: 0;
?>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oakshire Finance - Manage 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: var(--transition);
            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;
        }

        .nav-menu {
            padding: 24px 16px;
        }

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

        .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: 24px 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);
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .user-avatar i {
            font-size: 18px;
            color: white;
        }

        .user-details h4 {
            font-size: 14px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .user-details p {
            font-size: 12px;
            color: var(--gray-600);
        }

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

        /* Stats Cards */
        .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);
        }

        /* Section Headers */
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 32px 0 24px;
        }

        .section-header h2 {
            font-size: 20px;
            font-weight: 600;
            color: var(--gray-900);
        }

        .section-badge {
            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-active {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

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

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

        .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: 13px;
            color: var(--gray-700);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .data-table td {
            font-size: 14px;
            color: var(--gray-800);
        }

        .data-table tr:hover td {
            background: var(--gray-50);
        }

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

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

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

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

        .badge-info {
            background: rgba(23, 162, 184, 0.1);
            color: var(--info-blue);
        }

        .status-overdue {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
            display: inline-block;
        }

        /* Buttons */
        .btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 12px;
            font-weight: 500;
            text-decoration: none;
            transition: var(--transition);
            border: none;
            cursor: pointer;
        }

        .btn-sm {
            padding: 4px 10px;
            font-size: 11px;
        }

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

        .btn-success:hover {
            background: var(--success-green);
            color: white;
        }

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

        .btn-danger:hover {
            background: var(--error-red);
            color: white;
        }

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

        .btn-warning:hover {
            background: var(--warning-orange);
            color: white;
        }

        .btn-info {
            background: rgba(23, 162, 184, 0.1);
            color: var(--info-blue);
        }

        .btn-info:hover {
            background: var(--info-blue);
            color: white;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 24px;
        }

        .pagination a {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 36px;
            height: 36px;
            padding: 0 12px;
            border-radius: 8px;
            background: var(--white);
            border: 1px solid var(--gray-200);
            color: var(--gray-700);
            text-decoration: none;
            font-size: 14px;
            transition: var(--transition);
        }

        .pagination a:hover {
            background: var(--gray-100);
            border-color: var(--gray-300);
        }

        .pagination a.active {
            background: var(--primary-navy);
            border-color: var(--primary-navy);
            color: white;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 48px;
            color: var(--gray-500);
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        /* Divider */
        .divider {
            height: 1px;
            background: var(--gray-200);
            margin: 40px 0;
        }

        /* 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;
            }

            .user-details {
                display: none;
            }

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

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

            .section-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
            }
        }
    </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>

            <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="manage-users.php" class="nav-link">
                        <i class="fas fa-users"></i>
                        <span>Manage Users</span>
                    </a>
                </div>


                <div class="nav-item"><a href="manage-balance.php" class="nav-link"><i class="fas fa-wallet"></i> Manage
                        Balance</a></div>
                <div class="nav-item">
                    <a href="manage-loans.php" class="nav-link active">
                        <i class="fas fa-hand-holding-usd"></i>
                        <span>Manage Loans</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-investments.php" class="nav-link">
                        <i class="fas fa-chart-pie"></i>
                        <span>Manage Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="track-investments.php" class="nav-link">
                        <i class="fas fa-chart-simple"></i>
                        <span>Users Investments</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="role.php" class="nav-link">
                        <i class="fas fa-user-tag"></i>
                        <span>Roles</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="recent_transactions.php" class="nav-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span>Transactions</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="loan-history.php" class="nav-link">
                        <i class="fas fa-history"></i>
                        <span>Loan History</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="login-records.php" class="nav-link">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>Login Records</span>
                    </a>
                </div>
                <div class="nav-item">
                    <a href="manage-messages.php" class="nav-link">
                        <i class="fas fa-envelope"></i>
                        <span>Contact Messages</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 class="user-info">
                        <div class="user-avatar">
                            <i class="fas fa-user-shield"></i>
                        </div>
                        <div class="user-details">
                            <h4><?= htmlspecialchars($admin['full_name'] ?? 'Admin User') ?></h4>
                            <p>System Administrator</p>
                        </div>
                    </div>
                </div>
            </header>

            <!-- Content Area -->
            <div class="content-area">
                <!-- Statistics Cards -->
                <div class="stats-grid">
                    <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) ?></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($totalApproved) ?></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <h3>Total Loan Amount</h3>
                        <div class="stat-value">$<?= number_format($totalLoanAmount, 2) ?></div>
                    </div>
                </div>

                <!-- Pending Loans Section -->
                <div class="section-header">
                    <h2>
                        <i class="fas fa-clock" style="color: var(--warning-orange); margin-right: 8px;"></i>
                        Pending Loan Requests
                    </h2>
                    <span class="section-badge badge-pending"><?= $totalPending ?> pending</span>
                </div>

                <div class="table-container">
                    <?php if (empty($pendingLoans)): ?>
                        <div class="empty-state">
                            <i class="fas fa-check-circle"></i>
                            <p>No pending loan applications at the moment</p>
                        </div>
                    <?php else: ?>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Loan ID</th>
                                    <th>User</th>
                                    <th>Amount</th>
                                    <th>Interest</th>
                                    <th>Term</th>
                                    <th>Purpose</th>
                                    <th>Requested</th>
                                    <th>Verification</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($pendingLoans as $loan): ?>
                                    <tr>
                                        <td><code>#<?= $loan['loan_id'] ?></code></td>
                                        <td>
                                            <strong><?= htmlspecialchars($loan['full_name']) ?></strong><br>
                                            <small
                                                style="color: var(--gray-500);"><?= htmlspecialchars($loan['email']) ?></small>
                                        </td>
                                        <td><strong>$<?= number_format($loan['amount'], 2) ?></strong></td>
                                        <td><?= $loan['interest_rate'] ?>%</td>
                                        <td><?= $loan['term_months'] ?> months</td>
                                        <td><?= htmlspecialchars($loan['purpose']) ?></td>
                                        <td><?= date('M d, Y', strtotime($loan['created_at'])) ?></td>
                                        <td>
                                            <?php if ($loan['id_selfie_file_path'] && $loan['id_document_file_path']): ?>
                                                <a href="view-loan-verification.php?loan_id=<?= $loan['loan_id'] ?>"
                                                    class="btn btn-sm btn-info">
                                                    <i class="fas fa-eye"></i> View
                                                </a>
                                            <?php else: ?>
                                                <span class="badge badge-warning">No files</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <a href="manage-loans.php?id=<?= $loan['loan_id'] ?>&action=approve"
                                                    class="btn btn-sm btn-success"
                                                    onclick="return confirm('Approve this loan?')">
                                                    <i class="fas fa-check"></i> Approve
                                                </a>
                                                <a href="manage-loans.php?id=<?= $loan['loan_id'] ?>&action=reject"
                                                    class="btn btn-sm btn-danger" onclick="return confirm('Reject this loan?')">
                                                    <i class="fas fa-times"></i> Reject
                                                </a>
                                                <a href="manage-loans.php?id=<?= $loan['loan_id'] ?>&action=delete"
                                                    class="btn btn-sm btn-warning"
                                                    onclick="return confirm('Are you sure you want to delete this loan?')">
                                                    <i class="fas fa-trash"></i> Delete
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <!-- Pagination for Pending Loans -->
                <?php if ($totalPendingPages > 1): ?>
                    <div class="pagination">
                        <?php if ($pendingPage > 1): ?>
                            <a href="?pending_page=<?= $pendingPage - 1 ?>&approved_page=<?= $approvedPage ?>">&laquo; Prev</a>
                        <?php endif; ?>
                        <?php for ($i = 1; $i <= $totalPendingPages; $i++): ?>
                            <a href="?pending_page=<?= $i ?>&approved_page=<?= $approvedPage ?>"
                                class="<?= $i == $pendingPage ? 'active' : '' ?>"><?= $i ?></a>
                        <?php endfor; ?>
                        <?php if ($pendingPage < $totalPendingPages): ?>
                            <a href="?pending_page=<?= $pendingPage + 1 ?>&approved_page=<?= $approvedPage ?>">Next &raquo;</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <div class="divider"></div>

                <!-- Active Loans Section -->
                <div class="section-header">
                    <h2>
                        <i class="fas fa-hand-holding-usd" style="color: var(--success-green); margin-right: 8px;"></i>
                        Active Loans
                    </h2>
                    <span class="section-badge badge-active"><?= $totalApproved ?> active</span>
                </div>

                <div class="table-container">
                    <?php if (empty($approvedLoans)): ?>
                        <div class="empty-state">
                            <i class="fas fa-folder-open"></i>
                            <p>No active loans at the moment</p>
                        </div>
                    <?php else: ?>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Loan ID</th>
                                    <th>User</th>
                                    <th>Amount</th>
                                    <th>Interest</th>
                                    <th>Term</th>
                                    <th>Due Date</th>
                                    <th>Total Due</th>
                                    <th>Purpose</th>
                                    <th>Approved On</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($approvedLoans as $loan): ?>
                                    <?php
                                    $currentDate = new DateTime();
                                    $approvedDate = new DateTime($loan['approved_at']);
                                    $termEndDate = clone $approvedDate;
                                    $termEndDate->modify('+' . $loan['term_months'] . ' months');
                                    $isOverdue = $currentDate > $termEndDate && $loan['is_paid'] === 'no';
                                    $totalWithPenalty = $loan['total_due'] + ($loan['penalty_amount'] ?? 0);
                                    ?>
                                    <tr>
                                        <td><code>#<?= $loan['loan_id'] ?></code></td>
                                        <td>
                                            <strong><?= htmlspecialchars($loan['full_name']) ?></strong><br>
                                            <small
                                                style="color: var(--gray-500);"><?= htmlspecialchars($loan['email']) ?></small>
                                        </td>
                                        <td><strong>$<?= number_format($loan['amount'], 2) ?></strong></td>
                                        <td><?= $loan['interest_rate'] ?>%</td>
                                        <td><?= $loan['term_months'] ?> months</td>
                                        <td>
                                            <?php
                                            if ($loan['approved_at'] !== null) {
                                                $dueDate = new DateTime($loan['approved_at']);
                                                $dueDate->modify('+' . $loan['term_months'] . ' months');
                                                echo '<strong>' . $dueDate->format('M d, Y') . '</strong>';
                                                if ($isOverdue) {
                                                    echo '<br><span class="badge badge-danger">Overdue</span>';
                                                }
                                            } else {
                                                echo 'N/A';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <strong>$<?= number_format($totalWithPenalty, 2) ?></strong>
                                            <?php if ($loan['penalty_amount'] > 0): ?>
                                                <br><small
                                                    style="color: var(--error-red);">(+$<?= number_format($loan['penalty_amount'], 2) ?>
                                                    penalty)</small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= htmlspecialchars($loan['purpose']) ?></td>
                                        <td>
                                            <?php
                                            if ($loan['approved_at'] !== null) {
                                                echo date('M d, Y', strtotime($loan['approved_at']));
                                            } else {
                                                echo 'Not approved yet';
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($isOverdue): ?>
                                                <span class="status-overdue">Overdue</span>
                                            <?php else: ?>
                                                <span class="badge badge-success">Active</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    <?php endif; ?>
                </div>

                <!-- Pagination for Approved Loans -->
                <?php if ($totalApprovedPages > 1): ?>
                    <div class="pagination">
                        <?php if ($approvedPage > 1): ?>
                            <a href="?pending_page=<?= $pendingPage ?>&approved_page=<?= $approvedPage - 1 ?>">&laquo; Prev</a>
                        <?php endif; ?>
                        <?php for ($i = 1; $i <= $totalApprovedPages; $i++): ?>
                            <a href="?pending_page=<?= $pendingPage ?>&approved_page=<?= $i ?>"
                                class="<?= $i == $approvedPage ? 'active' : '' ?>"><?= $i ?></a>
                        <?php endfor; ?>
                        <?php if ($approvedPage < $totalApprovedPages): ?>
                            <a href="?pending_page=<?= $pendingPage ?>&approved_page=<?= $approvedPage + 1 ?>">Next &raquo;</a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </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');
                }
            }
        });
    </script>
</body>

</html>