<?php
session_start();
require_once 'config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

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

// Get admin info
$admin_id = $_SESSION['admin_id'];
$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->execute([$admin_id]);
$current_admin = $stmt->fetch();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_status':
                $loan_id = $_POST['loan_id'];
                $new_status = $_POST['status'];
                $interest_rate = $_POST['interest_rate'] ?? null;
                $term_months = $_POST['term_months'] ?? null;
                $monthly_payment = $_POST['monthly_payment'] ?? null;
                
                // Update loan application
                $stmt = $conn->prepare("UPDATE loan_applications SET status = ?, interest_rate = ?, term_months = ?, monthly_payment = ? WHERE id = ?");
                if ($stmt->execute([$new_status, $interest_rate, $term_months, $monthly_payment, $loan_id])) {
                    $message = 'Loan application updated successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update loan application.';
                    $message_type = 'error';
                }
                break;
                
            case 'delete':
                $loan_id = $_POST['loan_id'];
                
                $stmt = $conn->prepare("DELETE FROM loan_applications WHERE id = ?");
                if ($stmt->execute([$loan_id])) {
                    $message = 'Loan application deleted successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to delete loan application.';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where_conditions = [];
$params = [];

if (!empty($status_filter)) {
    $where_conditions[] = "l.status = ?";
    $params[] = $status_filter;
}

if (!empty($type_filter)) {
    $where_conditions[] = "l.loan_type = ?";
    $params[] = $type_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(u.firstname LIKE ? OR u.lastname LIKE ? OR u.email LIKE ? OR l.purpose LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get loan applications with user information
$query = "SELECT l.*, u.firstname, u.lastname, u.email, u.account_number, u.phone 
          FROM loan_applications l 
          LEFT JOIN users u ON l.user_id = u.id 
          $where_clause
          ORDER BY l.created_at DESC";

$stmt = $conn->prepare($query);
$stmt->execute($params);
$loans = $stmt->fetchAll();

// Get statistics
$stats_query = "SELECT 
    COUNT(*) as total_loans,
    SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) as pending_loans,
    SUM(CASE WHEN status = 'Approved' THEN 1 ELSE 0 END) as approved_loans,
    SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) as active_loans,
    SUM(CASE WHEN status = 'Completed' THEN 1 ELSE 0 END) as completed_loans,
    SUM(CASE WHEN status = 'Rejected' THEN 1 ELSE 0 END) as rejected_loans,
    SUM(loan_amount) as total_loan_amount
    FROM loan_applications";

$stats_stmt = $conn->query($stats_query);
$stats = $stats_stmt->fetch();

$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - Loan Applications</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>
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: #fff;
            margin: 2% auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            position: relative;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover {
            color: #000;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn-sm {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .alert {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
        }
        
        .stat-icon.pending { background: linear-gradient(135deg, #ffc107, #ff8f00); }
        .stat-icon.approved { background: linear-gradient(135deg, #28a745, #20c997); }
        .stat-icon.active { background: linear-gradient(135deg, #007bff, #6610f2); }
        .stat-icon.completed { background: linear-gradient(135deg, #6f42c1, #e83e8c); }
        .stat-icon.rejected { background: linear-gradient(135deg, #dc3545, #fd7e14); }
        .stat-icon.total { background: linear-gradient(135deg, #17a2b8, #20c997); }
        
        .stat-content h3 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }
        
        .stat-content p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .table-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
        }
        
        .table-header h3 {
            margin: 0;
            font-size: 24px;
        }
        
        .table-header p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }
        
        .filters {
            padding: 20px;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
        }
        
        .filters form {
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #666;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-approved {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-active {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .status-completed {
            background-color: #e2e3e5;
            color: #383d41;
        }
        
        .status-rejected {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .type-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            background-color: #e9ecef;
            color: #495057;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .amount {
            font-weight: 600;
            color: #28a745;
        }
        
        .user-info {
            display: flex;
            flex-direction: column;
        }
        
        .user-name {
            font-weight: 600;
            color: #333;
        }
        
        .user-email {
            font-size: 12px;
            color: #666;
        }
        
        .purpose-text {
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        @media (max-width: 768px) {
            .filters form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Search...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($current_admin['username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu active">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php" class="active">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="refunds.php">View All</a></li>
                            <li><a href="refunds.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="dashboard-header">
                <h2>Loan Applications</h2>
                <p>Manage loan applications and their status</p>
            </div>

            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon total">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_loans']); ?></h3>
                        <p>Total Loans</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon pending">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['pending_loans']); ?></h3>
                        <p>Pending</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon approved">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['approved_loans']); ?></h3>
                        <p>Approved</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon active">
                        <i class="fas fa-play-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['active_loans']); ?></h3>
                        <p>Active</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon completed">
                        <i class="fas fa-flag-checkered"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['completed_loans']); ?></h3>
                        <p>Completed</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon rejected">
                        <i class="fas fa-times-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['rejected_loans']); ?></h3>
                        <p>Rejected</p>
                    </div>
                </div>
            </div>

            <!-- Loans Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3><i class="fas fa-hand-holding-usd"></i> Loan Applications</h3>
                    <p>Review and manage loan applications from users</p>
                </div>
                
                <div class="filters">
                    <form method="GET" action="">
                        <div class="filter-group">
                            <label>Search</label>
                            <input type="text" name="search" placeholder="Search by name, email, or purpose..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="filter-group">
                            <label>Status</label>
                            <select name="status">
                                <option value="">All Status</option>
                                <option value="Pending" <?php echo $status_filter === 'Pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="Approved" <?php echo $status_filter === 'Approved' ? 'selected' : ''; ?>>Approved</option>
                                <option value="Active" <?php echo $status_filter === 'Active' ? 'selected' : ''; ?>>Active</option>
                                <option value="Completed" <?php echo $status_filter === 'Completed' ? 'selected' : ''; ?>>Completed</option>
                                <option value="Rejected" <?php echo $status_filter === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>Loan Type</label>
                            <select name="type">
                                <option value="">All Types</option>
                                <option value="Personal" <?php echo $type_filter === 'Personal' ? 'selected' : ''; ?>>Personal</option>
                                <option value="Business" <?php echo $type_filter === 'Business' ? 'selected' : ''; ?>>Business</option>
                                <option value="Mortgage" <?php echo $type_filter === 'Mortgage' ? 'selected' : ''; ?>>Mortgage</option>
                                <option value="Auto" <?php echo $type_filter === 'Auto' ? 'selected' : ''; ?>>Auto</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <button type="submit" class="btn btn-primary">Filter</button>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <a href="loans.php" class="btn btn-secondary">Clear</a>
                        </div>
                    </form>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Applicant</th>
                            <th>Loan Details</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Interest Rate</th>
                            <th>Monthly Payment</th>
                            <th>Applied Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($loans)): ?>
                            <tr>
                                <td colspan="9" style="text-align: center; padding: 40px;">
                                    <i class="fas fa-hand-holding-usd" style="font-size: 48px; color: #ccc; margin-bottom: 15px;"></i>
                                    <p style="color: #666;">No loan applications found.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($loans as $loan): ?>
                                <tr>
                                    <td><?php echo $loan['id']; ?></td>
                                    <td>
                                        <div class="user-info">
                                            <div class="user-name"><?php echo htmlspecialchars($loan['firstname'] . ' ' . $loan['lastname']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($loan['email']); ?></div>
                                            <div style="font-size: 11px; color: #999;"><?php echo htmlspecialchars($loan['account_number']); ?></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div>
                                            <div class="amount">$<?php echo number_format($loan['loan_amount'], 2); ?></div>
                                            <?php if ($loan['term_months']): ?>
                                                <div style="font-size: 12px; color: #666;"><?php echo $loan['term_months']; ?> months</div>
                                            <?php endif; ?>
                                            <?php if ($loan['purpose']): ?>
                                                <div class="purpose-text" title="<?php echo htmlspecialchars($loan['purpose']); ?>">
                                                    <?php echo htmlspecialchars(substr($loan['purpose'], 0, 50)) . (strlen($loan['purpose']) > 50 ? '...' : ''); ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="type-badge"><?php echo htmlspecialchars($loan['loan_type']); ?></span>
                                    </td>
                                    <td>
                                        <span class="status-badge status-<?php echo strtolower($loan['status']); ?>">
                                            <?php echo htmlspecialchars($loan['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php echo $loan['interest_rate'] ? $loan['interest_rate'] . '%' : '-'; ?>
                                    </td>
                                    <td>
                                        <?php echo $loan['monthly_payment'] ? '$' . number_format($loan['monthly_payment'], 2) : '-'; ?>
                                    </td>
                                    <td><?php echo date('M j, Y', strtotime($loan['created_at'])); ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn btn-info btn-sm" onclick="viewLoanDetails(<?php echo $loan['id']; ?>)" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-warning btn-sm" onclick="openUpdateModal(<?php echo $loan['id']; ?>, '<?php echo $loan['status']; ?>', <?php echo $loan['interest_rate'] ?? 'null'; ?>, <?php echo $loan['term_months'] ?? 'null'; ?>, <?php echo $loan['monthly_payment'] ?? 'null'; ?>)" title="Update Status">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-danger btn-sm" onclick="deleteLoan(<?php echo $loan['id']; ?>)" title="Delete Application">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Update Status Modal -->
    <div id="updateModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeUpdateModal()">&times;</span>
            <h3>Update Loan Application</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" id="loanId" name="loan_id">
                
                <div class="form-group">
                    <label for="status">Status:</label>
                    <select id="status" name="status" required>
                        <option value="Pending">Pending</option>
                        <option value="Approved">Approved</option>
                        <option value="Active">Active</option>
                        <option value="Completed">Completed</option>
                        <option value="Rejected">Rejected</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="interest_rate">Interest Rate (%):</label>
                    <input type="number" id="interest_rate" name="interest_rate" step="0.01" min="0" max="100">
                </div>
                
                <div class="form-group">
                    <label for="term_months">Term (months):</label>
                    <input type="number" id="term_months" name="term_months" min="1" max="360">
                </div>
                
                <div class="form-group">
                    <label for="monthly_payment">Monthly Payment ($):</label>
                    <input type="number" id="monthly_payment" name="monthly_payment" step="0.01" min="0">
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeUpdateModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Application</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Details Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeDetailsModal()">&times;</span>
            <h3>Loan Application Details</h3>
            <div id="loanDetails">
                <!-- Details will be loaded here -->
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        function openUpdateModal(loanId, status, interestRate, termMonths, monthlyPayment) {
            document.getElementById('loanId').value = loanId;
            document.getElementById('status').value = status;
            document.getElementById('interest_rate').value = interestRate || '';
            document.getElementById('term_months').value = termMonths || '';
            document.getElementById('monthly_payment').value = monthlyPayment || '';
            document.getElementById('updateModal').style.display = 'block';
        }

        function closeUpdateModal() {
            document.getElementById('updateModal').style.display = 'none';
            document.querySelector('#updateModal form').reset();
        }

        function viewLoanDetails(loanId) {
            // This would typically load loan details via AJAX
            // For now, we'll show a simple message
            document.getElementById('loanDetails').innerHTML = `
                <p>Loading loan application details for ID: ${loanId}</p>
                <p><em>This feature would load detailed information about the loan application including:</em></p>
                <ul>
                    <li>Complete applicant information</li>
                    <li>Full loan purpose and description</li>
                    <li>Application history and timeline</li>
                    <li>Supporting documents (if any)</li>
                    <li>Payment schedule details</li>
                </ul>
            `;
            document.getElementById('detailsModal').style.display = 'block';
        }

        function closeDetailsModal() {
            document.getElementById('detailsModal').style.display = 'none';
        }

        function deleteLoan(loanId) {
            if (confirm('Are you sure you want to delete this loan application? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="loan_id" value="${loanId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const updateModal = document.getElementById('updateModal');
            const detailsModal = document.getElementById('detailsModal');
            
            if (event.target === updateModal) {
                closeUpdateModal();
            }
            if (event.target === detailsModal) {
                closeDetailsModal();
            }
        }

        // Auto-calculate monthly payment when interest rate and term are entered
        document.getElementById('interest_rate').addEventListener('input', calculateMonthlyPayment);
        document.getElementById('term_months').addEventListener('input', calculateMonthlyPayment);

        function calculateMonthlyPayment() {
            const loanAmount = <?php echo json_encode(array_column($loans, 'loan_amount', 'id')); ?>;
            const loanId = document.getElementById('loanId').value;
            const interestRate = parseFloat(document.getElementById('interest_rate').value);
            const termMonths = parseInt(document.getElementById('term_months').value);
            
            if (loanId && interestRate && termMonths && loanAmount[loanId]) {
                const principal = parseFloat(loanAmount[loanId]);
                const monthlyRate = interestRate / 100 / 12;
                const monthlyPayment = (principal * monthlyRate * Math.pow(1 + monthlyRate, termMonths)) / 
                                     (Math.pow(1 + monthlyRate, termMonths) - 1);
                
                document.getElementById('monthly_payment').value = monthlyPayment.toFixed(2);
            }
        }
    </script>
</body>
</html>

