<?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();

// Handle application status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $application_id = $_POST['application_id'];
    
    if ($_POST['action'] === 'approve_application') {
        $stmt = $conn->prepare("UPDATE users SET status = 'Active' WHERE id = ?");
        $stmt->execute([$application_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Application approved successfully! User account is now active.";
        } else {
            $error_message = "Failed to approve application.";
        }
    } elseif ($_POST['action'] === 'reject_application') {
        $rejection_reason = $_POST['rejection_reason'] ?? 'Application rejected by admin';
        $stmt = $conn->prepare("UPDATE users SET status = 'Rejected', notes = ? WHERE id = ?");
        $stmt->execute([$rejection_reason, $application_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Application rejected successfully!";
        } else {
            $error_message = "Failed to reject application.";
        }
    } elseif ($_POST['action'] === 'delete_application') {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND status IN ('Pending', 'Rejected')");
        $stmt->execute([$application_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "Application deleted successfully!";
        } else {
            $error_message = "Failed to delete application.";
        }
    }
}

// Get search and filter parameters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$account_type_filter = isset($_GET['account_type']) ? $_GET['account_type'] : '';
$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[] = "(firstname LIKE ? OR lastname LIKE ? OR username LIKE ? OR email LIKE ? OR account_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[] = "status = ?";
    $params[] = $status_filter;
}

if (!empty($account_type_filter)) {
    $where_conditions[] = "account_type = ?";
    $params[] = $account_type_filter;
}

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

if (!empty($date_to)) {
    $where_conditions[] = "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 users $where_clause";
$stmt = $conn->prepare($count_sql);
$stmt->execute($params);
$total_applications = $stmt->fetch()['total'];
$total_pages = ceil($total_applications / $per_page);

// Get applications with pagination
$sql = "SELECT * FROM users $where_clause ORDER BY created_at DESC LIMIT $per_page OFFSET $offset";

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

// Get application statistics
$stats_sql = "SELECT 
    COUNT(*) as total_applications,
    SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'Rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(CASE WHEN status = 'Active' THEN balance ELSE 0 END) as total_balance
FROM users";
$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 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">
</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 applications...">
                </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 class="active">
                        <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">
                        <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 Applications</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Manage Applications
                </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; ?>

            <!-- Application Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-file-alt"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_applications']); ?></h3>
                        <p>Total Applications</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_balance'], 2); ?></h3>
                        <p>Total Balance</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 Applications</label>
                            <input type="text" id="search" name="search" 
                                   value="<?php echo htmlspecialchars($search); ?>"
                                   placeholder="Search by name, username, email, or account number">
                        </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="Active" <?php echo $status_filter === 'Active' ? 'selected' : ''; ?>>Active</option>
                                <option value="Rejected" <?php echo $status_filter === 'Rejected' ? 'selected' : ''; ?>>Rejected</option>
                                <option value="Suspended" <?php echo $status_filter === 'Suspended' ? 'selected' : ''; ?>>Suspended</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label for="account_type">Account Type</label>
                            <select id="account_type" name="account_type">
                                <option value="">All Types</option>
                                <option value="Savings" <?php echo $account_type_filter === 'Savings' ? 'selected' : ''; ?>>Savings</option>
                                <option value="Current" <?php echo $account_type_filter === 'Current' ? 'selected' : ''; ?>>Current</option>
                                <option value="Business" <?php echo $account_type_filter === 'Business' ? 'selected' : ''; ?>>Business</option>
                                <option value="Premium" <?php echo $account_type_filter === 'Premium' ? 'selected' : ''; ?>>Premium</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="applications.php" class="btn-secondary">
                                <i class="fas fa-undo"></i>
                                Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>

            <!-- Applications Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3>Applications (<?php echo number_format($total_applications); ?> total)</h3>
                    <div class="header-actions">
                        <button class="btn-secondary" onclick="exportApplications()">
                            <i class="fas fa-download"></i>
                            Export
                        </button>
                        <a href="create-user.php" class="btn-primary">
                            <i class="fas fa-plus"></i>
                            Create User Manually
                        </a>
                    </div>
                </div>

                <?php if (empty($applications)): ?>
                    <div class="no-data">
                        <i class="fas fa-file-alt"></i>
                        <p>No applications found matching your criteria.</p>
                        <a href="applications.php" class="btn-secondary">View All Applications</a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="users-table">
                            <thead>
                                <tr>
                                    <th>Applicant Info</th>
                                    <th>Account Details</th>
                                    <th>Contact Info</th>
                                    <th>Status</th>
                                    <th>Application Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($applications as $application): ?>
                                    <tr>
                                        <td class="user-info-cell">
                                            <div class="user-avatar">
                                                <?php if ($application['profile_photo']): ?>
                                                    <img src="uploads/profiles/<?php echo htmlspecialchars($application['profile_photo']); ?>" 
                                                         alt="Profile Photo">
                                                <?php else: ?>
                                                    <i class="fas fa-user"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div class="user-details">
                                                <h4><?php echo htmlspecialchars($application['firstname'] . ' ' . $application['lastname']); ?></h4>
                                                <p class="username">@<?php echo htmlspecialchars($application['username']); ?></p>
                                                <span class="account-type"><?php echo htmlspecialchars($application['account_type']); ?></span>
                                            </div>
                                        </td>
                                        
                                        <td class="account-info">
                                            <div class="info-item">
                                                <strong>Account:</strong> <?php echo htmlspecialchars($application['account_number']); ?>
                                            </div>
                                            <div class="info-item">
                                                <strong>SWIFT:</strong> <?php echo htmlspecialchars($application['swift_code']); ?>
                                            </div>
                                            <div class="info-item">
                                                <strong>Balance:</strong> $<?php echo number_format($application['balance'], 2); ?>
                                            </div>
                                        </td>
                                        
                                        <td class="contact-info">
                                            <div class="info-item">
                                                <i class="fas fa-envelope"></i>
                                                <?php echo htmlspecialchars($application['email']); ?>
                                            </div>
                                            <div class="info-item">
                                                <i class="fas fa-phone"></i>
                                                <?php echo htmlspecialchars($application['phone'] ?? 'N/A'); ?>
                                            </div>
                                            <div class="info-item">
                                                <i class="fas fa-map-marker-alt"></i>
                                                <?php echo htmlspecialchars(substr($application['address'], 0, 50)) . (strlen($application['address']) > 50 ? '...' : ''); ?>
                                            </div>
                                        </td>
                                        
                                        <td class="status-cell">
                                            <span class="status-badge status-<?php echo strtolower($application['status']); ?>">
                                                <?php echo htmlspecialchars($application['status']); ?>
                                            </span>
                                        </td>
                                        
                                        <td class="date-cell">
                                            <div class="date"><?php echo date('M j, Y', strtotime($application['created_at'])); ?></div>
                                            <div class="time"><?php echo date('g:i A', strtotime($application['created_at'])); ?></div>
                                        </td>
                                        
                                        <td class="actions-cell">
                                            <div class="action-buttons">
                                                <button class="btn-action btn-view" 
                                                        onclick="viewApplication(<?php echo $application['id']; ?>)"
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                
                                                <?php if ($application['status'] === 'Pending'): ?>
                                                    <button class="btn-action btn-edit" 
                                                            onclick="approveApplication(<?php echo $application['id']; ?>)"
                                                            title="Approve">
                                                        <i class="fas fa-check"></i>
                                                    </button>
                                                    
                                                    <button class="btn-action btn-more" 
                                                            onclick="rejectApplication(<?php echo $application['id']; ?>)"
                                                            title="Reject">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <?php if (in_array($application['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="deleteApplication(<?php echo $application['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 Application</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to approve this application? The user account will be activated immediately.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="approvalForm">
                    <input type="hidden" name="action" value="approve_application">
                    <input type="hidden" name="application_id" id="approvalApplicationId">
                    <button type="button" class="btn-secondary" onclick="closeModal('approvalModal')">Cancel</button>
                    <button type="submit" class="btn-primary">Approve Application</button>
                </form>
            </div>
        </div>
    </div>

    <!-- Rejection Modal -->
    <div id="rejectionModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Reject Application</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <p>Please provide a reason for rejecting this application:</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_application">
                    <input type="hidden" name="application_id" id="rejectionApplicationId">
                    <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 Application</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 application? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteForm">
                    <input type="hidden" name="action" value="delete_application">
                    <input type="hidden" name="application_id" id="deleteApplicationId">
                    <button type="button" class="btn-secondary" onclick="closeModal('deleteModal')">Cancel</button>
                    <button type="submit" class="btn-danger">Delete Application</button>
                </form>
            </div>
        </div>
    </div>

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

        function approveApplication(applicationId) {
            document.getElementById('approvalApplicationId').value = applicationId;
            document.getElementById('approvalModal').style.display = 'block';
        }

        function rejectApplication(applicationId) {
            document.getElementById('rejectionApplicationId').value = applicationId;
            document.getElementById('rejectionModal').style.display = 'block';
        }

        function deleteApplication(applicationId) {
            document.getElementById('deleteApplicationId').value = applicationId;
            document.getElementById('deleteModal').style.display = 'block';
        }

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

        function exportApplications() {
            // Implement export functionality
            console.log('Exporting applications');
            // 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>
