<?php
session_start();
require_once 'config/database.php';
require_once __DIR__ . '/lib/EmailService.php';
require_once __DIR__ . '/lib/EmailTemplates.php';
use TrustBnk\Admin\Lib\EmailService;
use TrustBnk\Admin\Lib\EmailTemplates;

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

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

// Handle deposit status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $deposit_id = $_POST['deposit_id'];
    
    if ($_POST['action'] === 'approve_deposit') {
        // Start transaction
        $conn->beginTransaction();
        
        try {
            // Update deposit status
            $stmt = $conn->prepare("UPDATE deposits SET status = 'Approved', approved_at = NOW(), approved_by = ? WHERE id = ?");
            $stmt->execute([$_SESSION['admin_id'], $deposit_id]);
            
            // Get deposit details
            $stmt = $conn->prepare("SELECT user_id, amount FROM deposits WHERE id = ?");
            $stmt->execute([$deposit_id]);
            $deposit = $stmt->fetch();
            
            if ($deposit) {
                // Update user balance
                $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->execute([$deposit['amount'], $deposit['user_id']]);
                
                // Create transaction record
                $stmt = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, description, reference_number, status, created_at) VALUES (?, 'Deposit', ?, 'Deposit approved by admin', ?, 'Completed', NOW())");
                $stmt->execute([$deposit['user_id'], $deposit['amount'], 'DEP' . time() . rand(1000, 9999)]);

                // Fetch user for email
                $userStmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                $userStmt->execute([$deposit['user_id']]);
                $user = $userStmt->fetch();
                
                // Prepare email
                $general = $conn->query("SELECT * FROM general_settings WHERE id = 1")->fetch() ?: ['site_name' => 'TrustBank', 'logo_path' => null];
                $reference = 'CREDIT' . time() . rand(100, 999);
                $available = (float)$user['balance']; // current balance after deposit
                [$subject, $html] = EmailTemplates::transactionAlert($general, $user, 'credit', (float)$deposit['amount'], $reference, 'Deposit approved by admin', date('Y-m-d H:i'), $available);
                $emailService = new EmailService($conn);
                $emailService->sendEmail($user['email'], trim($user['firstname'] . ' ' . $user['lastname']), $subject, $html, 'Transaction Alert', (int)$user['id'], (int)$_SESSION['admin_id']);
                
                $conn->commit();
                $success_message = "Deposit approved successfully! User balance has been updated.";
            } else {
                throw new Exception("Deposit not found");
            }
        } catch (Exception $e) {
            $conn->rollBack();
            $error_message = "Failed to approve deposit: " . $e->getMessage();
        }
    } elseif ($_POST['action'] === 'reject_deposit') {
        $rejection_reason = $_POST['rejection_reason'] ?? 'Deposit rejected by admin';
        $stmt = $conn->prepare("UPDATE deposits SET status = 'Rejected', rejected_at = NOW(), rejected_by = ?, rejection_reason = ? WHERE id = ?");
        $stmt->execute([$_SESSION['admin_id'], $rejection_reason, $deposit_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Deposit rejected successfully!";
        } else {
            $error_message = "Failed to reject deposit.";
        }
    } elseif ($_POST['action'] === 'delete_deposit') {
        $stmt = $conn->prepare("DELETE FROM deposits WHERE id = ? AND status IN ('Pending', 'Rejected')");
        $stmt->execute([$deposit_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Deposit deleted successfully!";
        } else {
            $error_message = "Failed to delete deposit.";
        }
    }
}

// Get search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

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

if (!empty($search)) {
    $where_conditions[] = "(u.firstname LIKE ? OR u.lastname LIKE ? OR u.username LIKE ? OR u.account_number LIKE ? OR d.reference_number LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param, $search_param]);
}

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

if (!empty($date_from)) {
    $where_conditions[] = "d.created_at >= ?";
    $params[] = $date_from . ' 00:00:00';
}

if (!empty($date_to)) {
    $where_conditions[] = "d.created_at <= ?";
    $params[] = $date_to . ' 23:59:59';
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM deposits d LEFT JOIN users u ON d.user_id = u.id $where_clause";
$stmt = $conn->prepare($count_sql);
$stmt->execute($params);
$total_deposits = $stmt->fetch()['total'];
$total_pages = ceil($total_deposits / $per_page);

// Get deposits with pagination
$sql = "SELECT d.*, u.firstname, u.lastname, u.username, u.account_number, u.profile_photo 
        FROM deposits d 
        LEFT JOIN users u ON d.user_id = u.id 
        $where_clause 
        ORDER BY d.created_at DESC LIMIT $per_page OFFSET $offset";

$stmt = $conn->prepare($sql);
$stmt->execute($params);
$deposits = $stmt->fetchAll();

// Get deposit statistics
$stats_sql = "SELECT 
    COUNT(*) as total_deposits,
    SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'Approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'Rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'Approved' THEN amount ELSE 0 END) as total_approved_amount,
    SUM(CASE WHEN status = 'Pending' THEN amount ELSE 0 END) as total_pending_amount
FROM deposits";
$stats_stmt = $conn->query($stats_sql);
$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 - Manage Deposits</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">
</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 deposits...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($_SESSION['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 class="active">
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <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">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="page-header">
                <h2>Manage Deposits</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Manage Deposits
                </nav>
            </div>

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

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

            <!-- Deposit Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_deposits']); ?></h3>
                        <p>Total Deposits</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['pending']); ?></h3>
                        <p>Pending Review</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['approved']); ?></h3>
                        <p>Approved</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3>$<?php echo number_format($stats['total_approved_amount'], 2); ?></h3>
                        <p>Total Approved Amount</p>
                    </div>
                </div>
            </div>

            <!-- Filters and Search -->
            <div class="filters-section">
                <form method="GET" class="filters-form">
                    <div class="filter-row">
                        <div class="filter-group">
                            <label for="search">Search Deposits</label>
                            <input type="text" id="search" name="search" 
                                   value="<?php echo htmlspecialchars($search); ?>"
                                   placeholder="Search by name, username, account number, or reference">
                        </div>
                        
                        <div class="filter-group">
                            <label for="status">Status</label>
                            <select id="status" name="status">
                                <option value="">All Statuses</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="Rejected" <?php echo $status_filter === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label for="date_from">Date From</label>
                            <input type="date" id="date_from" name="date_from" 
                                   value="<?php echo htmlspecialchars($date_from); ?>">
                        </div>
                        
                        <div class="filter-group">
                            <label for="date_to">Date To</label>
                            <input type="date" id="date_to" name="date_to" 
                                   value="<?php echo htmlspecialchars($date_to); ?>">
                        </div>
                        
                        <div class="filter-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-search"></i>
                                Filter
                            </button>
                            <a href="deposits.php" class="btn-secondary">
                                <i class="fas fa-undo"></i>
                                Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Deposits Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3>Deposits (<?php echo number_format($total_deposits); ?> total)</h3>
                    <div class="header-actions">
                        <button class="btn-secondary" onclick="exportDeposits()">
                            <i class="fas fa-download"></i>
                            Export
                        </button>
                    </div>
                </div>

                <?php if (empty($deposits)): ?>
                    <div class="no-data">
                        <i class="fas fa-arrow-down"></i>
                        <p>No deposits found matching your criteria.</p>
                        <a href="deposits.php" class="btn-secondary">View All Deposits</a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="users-table">
                            <thead>
                                <tr>
                                    <th>User Info</th>
                                    <th>Deposit Details</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($deposits as $deposit): ?>
                                    <tr>
                                        <td class="user-info-cell">
                                            <div class="user-avatar">
                                                <?php if ($deposit['profile_photo']): ?>
                                                    <img src="uploads/profiles/<?php echo htmlspecialchars($deposit['profile_photo']); ?>" 
                                                         alt="Profile Photo">
                                                <?php else: ?>
                                                    <i class="fas fa-user"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div class="user-details">
                                                <h4><?php echo htmlspecialchars($deposit['firstname'] . ' ' . $deposit['lastname']); ?></h4>
                                                <p class="username">@<?php echo htmlspecialchars($deposit['username']); ?></p>
                                                <div class="account-number"><?php echo htmlspecialchars($deposit['account_number']); ?></div>
                                            </div>
                                        </td>
                                        
                                        <td class="deposit-info">
                                            <div class="info-item">
                                                <strong>Reference:</strong> <?php echo htmlspecialchars($deposit['reference_number']); ?>
                                            </div>
                                            <div class="info-item">
                                                <strong>Method:</strong> <?php echo htmlspecialchars($deposit['payment_method'] ?? 'Bank Transfer'); ?>
                                            </div>
                                            <?php if ($deposit['notes']): ?>
                                                <div class="info-item">
                                                    <strong>Notes:</strong> <?php echo htmlspecialchars(substr($deposit['notes'], 0, 50)) . (strlen($deposit['notes']) > 50 ? '...' : ''); ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td class="amount-cell">
                                            <div class="amount">$<?php echo number_format($deposit['amount'], 2); ?></div>
                                        </td>
                                        
                                        <td class="status-cell">
                                            <span class="status-badge status-<?php echo strtolower($deposit['status']); ?>">
                                                <?php echo htmlspecialchars($deposit['status']); ?>
                                            </span>
                                        </td>
                                        
                                        <td class="date-cell">
                                            <div class="date"><?php echo date('M j, Y', strtotime($deposit['created_at'])); ?></div>
                                            <div class="time"><?php echo date('g:i A', strtotime($deposit['created_at'])); ?></div>
                                        </td>
                                        
                                        <td class="actions-cell">
                                            <div class="action-buttons">
                                                <button class="btn-action btn-view" 
                                                        onclick="viewDeposit(<?php echo $deposit['id']; ?>)"
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                
                                                <?php if ($deposit['status'] === 'Pending'): ?>
                                                    <button class="btn-action btn-edit" 
                                                            onclick="approveDeposit(<?php echo $deposit['id']; ?>)"
                                                            title="Approve">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                    
                                                    <button class="btn-action btn-more" 
                                                            onclick="rejectDeposit(<?php echo $deposit['id']; ?>)"
                                                            title="Reject">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <?php if (in_array($deposit['status'], ['Pending', 'Rejected'])): ?>
                                                    <div class="dropdown">
                                                        <button class="btn-action btn-more" title="More Actions">
                                                            <i class="fas fa-ellipsis-v"></i>
                                                        </button>
                                                        <div class="dropdown-content">
                                                            <button onclick="deleteDeposit(<?php echo $deposit['id']; ?>)" 
                                                                    class="btn-delete">
                                                                <i class="fas fa-trash"></i>
                                                                Delete
                                                            </button>
                                                        </div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <div class="pagination">
                            <?php if ($page > 1): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                                   class="page-link">
                                    <i class="fas fa-chevron-left"></i>
                                    Previous
                                </a>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" 
                                   class="page-link <?php echo $i === $page ? 'active' : ''; ?>">
                                    <?php echo $i; ?>
                                </a>
                            <?php endfor; ?>
                            
                            <?php if ($page < $total_pages): ?>
                                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                                   class="page-link">
                                    Next
                                    <i class="fas fa-chevron-right"></i>
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <!-- Approval Modal -->
    <div id="approvalModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Approve Deposit</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to approve this deposit? The user's balance will be updated immediately.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="approvalForm">
                    <input type="hidden" name="action" value="approve_deposit">
                    <input type="hidden" name="deposit_id" id="approvalDepositId">
                    <button type="button" class="btn-secondary" onclick="closeModal('approvalModal')">Cancel</button>
                    <button type="submit" class="btn-primary">Approve Deposit</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Rejection Modal -->
    <div id="rejectionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Reject Deposit</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Please provide a reason for rejecting this deposit:</p>
                <textarea name="rejection_reason" id="rejectionReason" 
                          placeholder="Enter rejection reason..." rows="3" style="width: 100%; margin-top: 15px;"></textarea>
            </div>
            <div class="modal-footer">
                <form method="POST" id="rejectionForm">
                    <input type="hidden" name="action" value="reject_deposit">
                    <input type="hidden" name="deposit_id" id="rejectionDepositId">
                    <input type="hidden" name="rejection_reason" id="rejectionReasonHidden">
                    <button type="button" class="btn-secondary" onclick="closeModal('rejectionModal')">Cancel</button>
                    <button type="submit" class="btn-danger">Reject Deposit</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Confirm Delete</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this deposit? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteForm">
                    <input type="hidden" name="action" value="delete_deposit">
                    <input type="hidden" name="deposit_id" id="deleteDepositId">
                    <button type="button" class="btn-secondary" onclick="closeModal('deleteModal')">Cancel</button>
                    <button type="submit" class="btn-danger">Delete Deposit</button>
                </form>
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        // Deposit management functions
        function viewDeposit(depositId) {
            // Implement view deposit functionality
            console.log('Viewing deposit:', depositId);
            // You can redirect to a detailed view page or show a modal
        }

        function approveDeposit(depositId) {
            document.getElementById('approvalDepositId').value = depositId;
            document.getElementById('approvalModal').style.display = 'block';
        }

        function rejectDeposit(depositId) {
            document.getElementById('rejectionDepositId').value = depositId;
            document.getElementById('rejectionModal').style.display = 'block';
        }

        function deleteDeposit(depositId) {
            document.getElementById('deleteDepositId').value = depositId;
            document.getElementById('deleteModal').style.display = 'block';
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        function exportDeposits() {
            // Implement export functionality
            console.log('Exporting deposits');
            // You can implement CSV/Excel export
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }

        // Close modal when clicking close button
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.onclick = function() {
                this.closest('.modal').style.display = 'none';
            }
        });

        // Handle rejection form submission
        document.getElementById('rejectionForm').addEventListener('submit', function(e) {
            const reason = document.getElementById('rejectionReason').value.trim();
            if (!reason) {
                e.preventDefault();
                alert('Please provide a rejection reason.');
                return;
            }
            document.getElementById('rejectionReasonHidden').value = reason;
        });
    </script>
</body>
</html>
