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

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

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

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

// Handle user status updates, edits, and banking actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $user_id = $_POST['user_id'];
    
    if ($_POST['action'] === 'update_status') {
        $new_status = $_POST['status'];
        $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
        $stmt->execute([$new_status, $user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "User status updated successfully!";
        } else {
            $error_message = "Failed to update user status.";
        }
    } elseif ($_POST['action'] === 'edit_user') {
        // Handle user edit
        $firstname = $_POST['firstname'];
        $middlename = $_POST['middlename'];
        $lastname = $_POST['lastname'];
        $username = $_POST['username'];
        $email = $_POST['email'];
        $phone = $_POST['phone'];
        $account_type = $_POST['account_type'];
        $status = $_POST['status'];
        $balance = $_POST['balance'];
        $nationality = $_POST['nationality'];
        $date_of_birth = $_POST['date_of_birth'];
        $address = $_POST['address'];
        
        $stmt = $conn->prepare("UPDATE users SET 
            firstname = ?, middlename = ?, lastname = ?, username = ?, 
            email = ?, phone = ?, account_type = ?, status = ?, 
            balance = ?, nationality = ?, date_of_birth = ?, address = ?,
            updated_at = NOW() WHERE id = ?");
        
        $stmt->execute([
            $firstname, $middlename, $lastname, $username, $email, $phone,
            $account_type, $status, $balance, $nationality, $date_of_birth, $address, $user_id
        ]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "User updated successfully!";
        } else {
            $error_message = "Failed to update user.";
        }
    } elseif ($_POST['action'] === 'credit_account') {
        // Handle account credit
        $amount = floatval($_POST['amount']);
        $description = $_POST['description'] ?? 'Account credited by admin';
        
        if ($amount <= 0) {
            $error_message = "Credit amount must be greater than zero.";
        } else {
            $conn->beginTransaction();
            try {
                // Update user balance
                $stmt = $conn->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
                $stmt->execute([$amount, $user_id]);
                
                // Create transaction record
                $reference = 'CREDIT' . time() . rand(1000, 9999);
                $stmt = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, description, reference_number, status, created_at) VALUES (?, 'Deposit', ?, ?, ?, 'Completed', NOW())");
                $stmt->execute([$user_id, $amount, $description, $reference]);
                
                // Fetch user details for email
                $userStmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                $userStmt->execute([$user_id]);
                $user = $userStmt->fetch();

                $conn->commit();
                $success_message = "Account credited successfully! Amount: $" . number_format($amount, 2);

                // Send credit alert email
                if ($user && !empty($user['email'])) {
                    $general = $conn->query("SELECT * FROM general_settings WHERE id = 1")->fetch() ?: ['site_name' => 'TrustBank', 'logo_path' => null];
                    $available = (float)$user['balance']; // current balance after credit
                    [$subject, $html] = EmailTemplates::transactionAlert($general, $user, 'credit', (float)$amount, $reference, $description, date('Y-m-d H:i'), $available, $user['currency'] ?? '$');
                    $emailService = new EmailService($conn);
                    $emailService->sendEmail($user['email'], trim($user['firstname'] . ' ' . $user['lastname']), $subject, $html, 'Transaction Alert', (int)$user['id'], (int)$_SESSION['admin_id']);
                }
            } catch (Exception $e) {
                $conn->rollBack();
                $error_message = "Failed to credit account: " . $e->getMessage();
            }
        }
    } elseif ($_POST['action'] === 'debit_account') {
        // Handle account debit
        $amount = floatval($_POST['amount']);
        $description = $_POST['description'] ?? 'Account debited by admin';
        
        if ($amount <= 0) {
            $error_message = "Debit amount must be greater than zero.";
        } else {
            $conn->beginTransaction();
            try {
                // Check if user has sufficient balance
                $stmt = $conn->prepare("SELECT balance FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $current_balance = $stmt->fetchColumn();
                
                if ($current_balance < $amount) {
                    throw new Exception("Insufficient balance. Current balance: $" . number_format($current_balance, 2));
                }
                
                // Update user balance
                $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
                $stmt->execute([$amount, $user_id]);
                
                // Create transaction record
                $reference = 'DEBIT' . time() . rand(1000, 9999);
                $stmt = $conn->prepare("INSERT INTO transactions (user_id, transaction_type, amount, description, reference_number, status, created_at) VALUES (?, 'Withdrawal', ?, ?, ?, 'Completed', NOW())");
                $stmt->execute([$user_id, $amount, $description, $reference]);
                
                // Fetch user details for email
                $userStmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
                $userStmt->execute([$user_id]);
                $user = $userStmt->fetch();

                $conn->commit();
                $success_message = "Account debited successfully! Amount: $" . number_format($amount, 2);

                // Send debit alert email
                if ($user && !empty($user['email'])) {
                    $general = $conn->query("SELECT * FROM general_settings WHERE id = 1")->fetch() ?: ['site_name' => 'TrustBank', 'logo_path' => null];
                    $available = max(0, (float)$current_balance - (float)$amount);
                    [$subject, $html] = EmailTemplates::transactionAlert($general, $user, 'debit', (float)$amount, $reference, $description, date('Y-m-d H:i'), $available, $user['currency'] ?? '$');
                    $emailService = new EmailService($conn);
                    $emailService->sendEmail($user['email'], trim($user['firstname'] . ' ' . $user['lastname']), $subject, $html, 'Transaction Alert', (int)$user['id'], (int)$_SESSION['admin_id']);
                }
            } catch (Exception $e) {
                $conn->rollBack();
                $error_message = "Failed to debit account: " . $e->getMessage();
            }
        }
    } elseif ($_POST['action'] === 'toggle_swift') {
        // Toggle SWIFT code on/off
        $stmt = $conn->prepare("UPDATE users SET swift_enabled = NOT swift_enabled WHERE id = ?");
        $stmt->execute([$user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "SWIFT code status toggled successfully!";
        } else {
            $error_message = "Failed to toggle SWIFT code status.";
        }
    } elseif ($_POST['action'] === 'toggle_imf') {
        // Toggle IMF code on/off
        $stmt = $conn->prepare("UPDATE users SET imf_enabled = NOT imf_enabled WHERE id = ?");
        $stmt->execute([$user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "IMF code status toggled successfully!";
        } else {
            $error_message = "Failed to toggle IMF code status.";
        }
    } elseif ($_POST['action'] === 'toggle_cot') {
        // Toggle COT code on/off
        $stmt = $conn->prepare("UPDATE users SET cot_enabled = NOT cot_enabled WHERE id = ?");
        $stmt->execute([$user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "COT code status toggled successfully!";
        } else {
            $error_message = "Failed to toggle COT code status.";
        }
    } elseif ($_POST['action'] === 'delete_user') {
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        
        if ($stmt->rowCount() > 0) {
            $success_message = "User deleted successfully!";
        } else {
            $error_message = "Failed to delete user.";
        }
    }
}

// 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'] : '';
$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 email LIKE ? OR username 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;
}

$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_users = $stmt->fetch()['total'];
$total_pages = ceil($total_users / $per_page);

// Get users 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);
$users = $stmt->fetchAll();

// Get unique statuses and account types for filters
$statuses = $conn->query("SELECT DISTINCT status FROM users ORDER BY status")->fetchAll();
$account_types = $conn->query("SELECT DISTINCT account_type FROM users ORDER BY account_type")->fetchAll();

$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 Users</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 users...">
                </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 class="active">
                        <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">
                        <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 Users</h2>
                <nav class="breadcrumb">
                    <a href="index.php">Dashboard</a> / Manage Users
                </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; ?>

            <!-- User Statistics -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($total_users); ?></h3>
                        <p>Total Users</p>
                    </div>
                </div>
                
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-user-check"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format(array_reduce($users, function($carry, $user) { return $carry + ($user['status'] === 'Active' ? 1 : 0); }, 0)); ?></h3>
                        <p>Active Users</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(array_reduce($users, function($carry, $user) { return $carry + ($user['status'] === 'Pending' ? 1 : 0); }, 0)); ?></h3>
                        <p>Pending Users</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(array_reduce($users, function($carry, $user) { return $carry + floatval($user['balance']); }, 0), 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 Users</label>
                            <input type="text" id="search" name="search" 
                                   value="<?php echo htmlspecialchars($search); ?>"
                                   placeholder="Search by name, email, username, or account number">
                        </div>
                        
                        <div class="filter-group">
                            <label for="status">Status</label>
                            <select id="status" name="status">
                                <option value="">All Statuses</option>
                                <?php foreach ($statuses as $status): ?>
                                    <option value="<?php echo htmlspecialchars($status['status']); ?>"
                                            <?php echo $status_filter === $status['status'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($status['status']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </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>
                                <?php foreach ($account_types as $type): ?>
                                    <option value="<?php echo htmlspecialchars($type['account_type']); ?>"
                                            <?php echo $account_type_filter === $type['account_type'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($type['account_type']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="filter-actions">
                            <button type="submit" class="btn-primary">
                                <i class="fas fa-search"></i>
                                Filter
                            </button>
                            <a href="users.php" class="btn-secondary">
                                <i class="fas fa-undo"></i>
                                Clear
                            </a>
                        </div>
                    </div>
                </form>
            </div>

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

                <?php if (empty($users)): ?>
                    <div class="no-data">
                        <i class="fas fa-users"></i>
                        <p>No users found matching your criteria.</p>
                        <a href="users.php" class="btn-secondary">View All Users</a>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="users-table">
                            <thead>
                                <tr>
                                    <th>User Info</th>
                                    <th>Account Details</th>
                                    <th>Contact Info</th>
                                    <th>Status</th>
                                    <th>Created Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($users as $user): ?>
                                    <tr>
                                        <td class="user-info-cell">
                                            <div class="user-avatar">
                                                <?php if ($user['profile_photo']): ?>
                                                    <img src="uploads/profiles/<?php echo htmlspecialchars($user['profile_photo']); ?>" 
                                                         alt="Profile Photo">
                                                <?php else: ?>
                                                    <i class="fas fa-user"></i>
                                                <?php endif; ?>
                                            </div>
                                            <div class="user-details">
                                                <h4><?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname']); ?></h4>
                                                <p class="username">@<?php echo htmlspecialchars($user['username']); ?></p>
                                                <span class="account-type"><?php echo htmlspecialchars($user['account_type']); ?></span>
                                            </div>
                                        </td>
                                        
                                        <td class="account-info">
                                            <div class="info-item">
                                                <strong>Account:</strong> <?php echo htmlspecialchars($user['account_number']); ?>
                                            </div>
                                            <div class="info-item">
                                                <strong>SWIFT:</strong> <?php echo htmlspecialchars($user['swift_code']); ?>
                                            </div>
                                            <div class="info-item">
                                                <strong>Balance:</strong> <?php echo formatCurrency($user['balance'], $user['currency'] ?? '$'); ?>
                                            </div>
                                        </td>
                                        
                                        <td class="contact-info">
                                            <div class="info-item">
                                                <i class="fas fa-envelope"></i>
                                                <?php echo htmlspecialchars($user['email']); ?>
                                            </div>
                                            <div class="info-item">
                                                <i class="fas fa-phone"></i>
                                                <?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?>
                                            </div>
                                            <div class="info-item">
                                                <i class="fas fa-map-marker-alt"></i>
                                                <?php echo htmlspecialchars(substr($user['address'], 0, 50)) . (strlen($user['address']) > 50 ? '...' : ''); ?>
                                            </div>
                                        </td>
                                        
                                        <td class="status-cell">
                                            <span class="status-badge status-<?php echo strtolower($user['status']); ?>">
                                                <?php echo htmlspecialchars($user['status']); ?>
                                            </span>
                                        </td>
                                        
                                        <td class="date-cell">
                                            <div class="date"><?php echo date('M j, Y', strtotime($user['created_at'])); ?></div>
                                            <div class="time"><?php echo date('g:i A', strtotime($user['created_at'])); ?></div>
                                        </td>
                                        
                                        <td class="actions-cell">
                                            <div class="action-buttons">
                                                <button class="btn-action btn-view" 
                                                        onclick="viewUser(<?php echo $user['id']; ?>)"
                                                        title="View Details">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                
                                                <button class="btn-action btn-edit" 
                                                        onclick="editUser(<?php echo $user['id']; ?>)"
                                                        title="Edit User">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                
                                                <div class="dropdown">
                                                    <button class="btn-action btn-more" title="More Actions">
                                                        <i class="fas fa-ellipsis-v"></i>
                                                    </button>
                                                    <div class="dropdown-content">
                                                        <form method="POST" style="display: inline;">
                                                            <input type="hidden" name="action" value="update_status">
                                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                                            <select name="status" onchange="this.form.submit()">
                                                                <option value="">Change Status</option>
                                                                <option value="Active">Active</option>
                                                                <option value="Pending">Pending</option>
                                                                <option value="Inactive">Inactive</option>
                                                                <option value="Suspended">Suspended</option>
                                                            </select>
                                                        </form>
                                                        
                                                        <button onclick="creditAccount(<?php echo $user['id']; ?>)" 
                                                                class="btn-credit">
                                                            <i class="fas fa-plus"></i>
                                                            Credit Account
                                                        </button>
                                                        
                                                        <button onclick="debitAccount(<?php echo $user['id']; ?>)" 
                                                                class="btn-debit">
                                                            <i class="fas fa-minus"></i>
                                                            Debit Account
                                                        </button>
                                                        
                                                        <button onclick="toggleSwift(<?php echo $user['id']; ?>)" 
                                                                class="btn-toggle">
                                                            <i class="fas fa-toggle-on"></i>
                                                            Toggle SWIFT
                                                        </button>
                                                        
                                                        <button onclick="toggleImf(<?php echo $user['id']; ?>)" 
                                                                class="btn-toggle">
                                                            <i class="fas fa-toggle-on"></i>
                                                            Toggle IMF
                                                        </button>
                                                        
                                                        <button onclick="toggleCot(<?php echo $user['id']; ?>)" 
                                                                class="btn-toggle">
                                                            <i class="fas fa-toggle-on"></i>
                                                            Toggle COT
                                                        </button>
                                                        
                                                        <button onclick="deleteUser(<?php echo $user['id']; ?>)" 
                                                                class="btn-delete">
                                                            <i class="fas fa-trash"></i>
                                                            Delete
                                                        </button>
                                                    </div>
                                                </div>
                                            </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>

    <!-- View User Modal -->
    <div id="viewModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="modal-header">
                <h3>User Details</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div id="userDetailsContent">
                    <!-- User details will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeModal('viewModal')">Close</button>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">
                <h3>Edit User</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <form id="editUserForm" method="POST">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" id="editUserId">
                    
                    <div class="form-row">
                        <div class="form-column">
                            <div class="form-group">
                                <label for="edit_firstname">First Name</label>
                                <input type="text" id="edit_firstname" name="firstname" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_middlename">Middle Name</label>
                                <input type="text" id="edit_middlename" name="middlename">
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_lastname">Last Name</label>
                                <input type="text" id="edit_lastname" name="lastname" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_username">Username</label>
                                <input type="text" id="edit_username" name="username" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_email">Email</label>
                                <input type="email" id="edit_email" name="email" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_phone">Phone</label>
                                <input type="tel" id="edit_phone" name="phone">
                            </div>
                        </div>
                        
                        <div class="form-column">
                            <div class="form-group">
                                <label for="edit_account_type">Account Type</label>
                                <select id="edit_account_type" name="account_type" required>
                                    <option value="Savings">Savings</option>
                                    <option value="Current">Current</option>
                                    <option value="Business">Business</option>
                                    <option value="Premium">Premium</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_status">Status</label>
                                <select id="edit_status" name="status" required>
                                    <option value="Active">Active</option>
                                    <option value="Pending">Pending</option>
                                    <option value="Inactive">Inactive</option>
                                    <option value="Suspended">Suspended</option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_balance">Balance</label>
                                <input type="number" id="edit_balance" name="balance" step="0.01" min="0" required>
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_nationality">Nationality</label>
                                <input type="text" id="edit_nationality" name="nationality">
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_date_of_birth">Date of Birth</label>
                                <input type="date" id="edit_date_of_birth" name="date_of_birth">
                            </div>
                            
                            <div class="form-group">
                                <label for="edit_address">Address</label>
                                <textarea id="edit_address" name="address" rows="3"></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn-secondary" onclick="closeModal('editModal')">Cancel</button>
                        <button type="submit" class="btn-primary">Update User</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Credit Account Modal -->
    <div id="creditModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Credit Account</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" id="creditForm">
                    <input type="hidden" name="action" value="credit_account">
                    <input type="hidden" name="user_id" id="creditUserId">
                    
                    <div class="form-group">
                        <label for="credit_amount">Amount to Credit</label>
                        <input type="number" id="credit_amount" name="amount" step="0.01" min="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="credit_description">Description (Optional)</label>
                        <textarea id="credit_description" name="description" rows="3" placeholder="Reason for credit..."></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn-secondary" onclick="closeModal('creditModal')">Cancel</button>
                        <button type="submit" class="btn-primary">Credit Account</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Debit Account Modal -->
    <div id="debitModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Debit Account</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <form method="POST" id="debitForm">
                    <input type="hidden" name="action" value="debit_account">
                    <input type="hidden" name="user_id" id="debitUserId">
                    
                    <div class="form-group">
                        <label for="debit_amount">Amount to Debit</label>
                        <input type="number" id="debit_amount" name="amount" step="0.01" min="0.01" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="debit_description">Description (Optional)</label>
                        <textarea id="debit_description" name="description" rows="3" placeholder="Reason for debit..."></textarea>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn-secondary" onclick="closeModal('debitModal')">Cancel</button>
                        <button type="submit" class="btn-danger">Debit Account</button>
                    </div>
                </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 user? This action cannot be undone.</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteForm">
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_id" id="deleteUserId">
                    <button type="button" class="btn-secondary" onclick="closeModal('deleteModal')">Cancel</button>
                    <button type="submit" class="btn-danger">Delete User</button>
                </form>
            </div>
        </div>
    </div>

    <!-- View User Modal -->
    <div id="viewUserModal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h3>View User Details</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div id="viewUserContent">
                    <!-- User details will be loaded here via AJAX -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn-secondary" onclick="closeModal('viewUserModal')">Close</button>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editUserModal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h3>Edit User Details</h3>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div id="editUserContent">
                    <!-- Edit form will be loaded here via AJAX -->
                </div>
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        // User management functions
        function viewUser(userId) {
            // Load user details via AJAX
            fetch('get_user.php?id=' + userId)
                .then(response => response.json())
                .then(user => {
                    const content = `
                        <div class="user-details-view">
                            <div class="user-header">
                                <div class="user-avatar-large">
                                    ${user.profile_photo ? 
                                        `<img src="uploads/profiles/${user.profile_photo}" alt="Profile Photo">` : 
                                        '<i class="fas fa-user"></i>'
                                    }
                                </div>
                                <div class="user-info-main">
                                    <h3>${user.firstname} ${user.lastname}</h3>
                                    <p class="username">@${user.username}</p>
                                    <span class="status-badge status-${user.status.toLowerCase()}">${user.status}</span>
                                </div>
                            </div>
                            
                            <div class="user-details-grid">
                                <div class="detail-section">
                                    <h4>Account Information</h4>
                                    <div class="detail-item">
                                        <strong>Account Number:</strong> ${user.account_number}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Account Type:</strong> ${user.account_type}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Balance:</strong> ${user.currency || '$'}${parseFloat(user.balance).toLocaleString('en-US', {minimumFractionDigits: 2})}
                                    </div>
                                    <div class="detail-item">
                                        <strong>SWIFT Code:</strong> ${user.swift_code}
                                    </div>
                                    <div class="detail-item">
                                        <strong>IMF Code:</strong> ${user.imf_code}
                                    </div>
                                    <div class="detail-item">
                                        <strong>COT Code:</strong> ${user.cot_code}
                                    </div>
                                </div>
                                
                                <div class="detail-section">
                                    <h4>Personal Information</h4>
                                    <div class="detail-item">
                                        <strong>Email:</strong> ${user.email}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Phone:</strong> ${user.phone || 'N/A'}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Date of Birth:</strong> ${user.date_of_birth || 'N/A'}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Nationality:</strong> ${user.nationality || 'N/A'}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Address:</strong> ${user.address || 'N/A'}
                                    </div>
                                </div>
                                
                                <div class="detail-section">
                                    <h4>Account Details</h4>
                                    <div class="detail-item">
                                        <strong>Created:</strong> ${new Date(user.created_at).toLocaleDateString()}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Last Updated:</strong> ${new Date(user.updated_at).toLocaleDateString()}
                                    </div>
                                    <div class="detail-item">
                                        <strong>Transaction PIN:</strong> ${user.transaction_pin ? '****' : 'Not Set'}
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                    document.getElementById('userDetailsContent').innerHTML = content;
                    document.getElementById('viewModal').style.display = 'block';
                })
                .catch(error => {
                    console.error('Error loading user details:', error);
                    alert('Error loading user details. Please try again.');
                });
        }

        function editUser(userId) {
            // Load user details for editing
            fetch('get_user.php?id=' + userId)
                .then(response => response.json())
                .then(user => {
                    // Populate form fields
                    document.getElementById('editUserId').value = user.id;
                    document.getElementById('edit_firstname').value = user.firstname;
                    document.getElementById('edit_middlename').value = user.middlename || '';
                    document.getElementById('edit_lastname').value = user.lastname;
                    document.getElementById('edit_username').value = user.username;
                    document.getElementById('edit_email').value = user.email;
                    document.getElementById('edit_phone').value = user.phone || '';
                    document.getElementById('edit_account_type').value = user.account_type;
                    document.getElementById('edit_status').value = user.status;
                    document.getElementById('edit_balance').value = user.balance;
                    document.getElementById('edit_nationality').value = user.nationality || '';
                    document.getElementById('edit_date_of_birth').value = user.date_of_birth || '';
                    document.getElementById('edit_address').value = user.address || '';
                    
                    document.getElementById('editModal').style.display = 'block';
                })
                .catch(error => {
                    console.error('Error loading user details:', error);
                    alert('Error loading user details. Please try again.');
                });
        }

        function deleteUser(userId) {
            document.getElementById('deleteUserId').value = userId;
            document.getElementById('deleteModal').style.display = 'block';
        }

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

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

        // Banking action functions
        function creditAccount(userId) {
            document.getElementById('creditUserId').value = userId;
            document.getElementById('creditModal').style.display = 'block';
        }

        function debitAccount(userId) {
            document.getElementById('debitUserId').value = userId;
            document.getElementById('debitModal').style.display = 'block';
        }

        function toggleSwift(userId) {
            if (confirm('Are you sure you want to toggle SWIFT code status for this user?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_swift">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        function toggleImf(userId) {
            if (confirm('Are you sure you want to toggle IMF code status for this user?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_imf">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        function toggleCot(userId) {
            if (confirm('Are you sure you want to toggle COT code status for this user?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="toggle_cot">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // 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';
            }
        });

        // Auto-submit status changes
        document.querySelectorAll('select[name="status"]').forEach(select => {
            select.addEventListener('change', function() {
                if (this.value) {
                    this.form.submit();
                }
            });
        });

        // View and Edit User Functions
        function viewUser(userId) {
            // Show loading state
            document.getElementById('viewUserModal').style.display = 'block';
            document.getElementById('viewUserContent').innerHTML = '<div class="loading">Loading user details...</div>';
            
            // Fetch user details via AJAX
            fetch('get_user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_user&user_id=' + userId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayUserDetails(data.user);
                } else {
                    document.getElementById('viewUserContent').innerHTML = '<div class="error">Error loading user details: ' + data.error + '</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('viewUserContent').innerHTML = '<div class="error">Error loading user details. Please try again.</div>';
            });
        }

        function editUser(userId) {
            // Show loading state
            document.getElementById('editUserModal').style.display = 'block';
            document.getElementById('editUserContent').innerHTML = '<div class="loading">Loading user details...</div>';
            
            // Fetch user details via AJAX
            fetch('get_user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'action=get_user&user_id=' + userId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    populateEditForm(data.user);
                } else {
                    document.getElementById('editUserContent').innerHTML = '<div class="error">Error loading user details: ' + data.error + '</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('editUserContent').innerHTML = '<div class="error">Error loading user details. Please try again.</div>';
            });
        }

        function displayUserDetails(user) {
            const content = `
                <div class="user-details">
                    <div class="detail-row">
                        <div class="detail-column">
                            <h3>Personal Information</h3>
                            <div class="detail-item">
                                <label>Full Name:</label>
                                <span>${user.firstname} ${user.middlename ? user.middlename + ' ' : ''}${user.lastname}</span>
                            </div>
                            <div class="detail-item">
                                <label>Username:</label>
                                <span>${user.username}</span>
                            </div>
                            <div class="detail-item">
                                <label>Email:</label>
                                <span>${user.email}</span>
                            </div>
                            <div class="detail-item">
                                <label>Phone:</label>
                                <span>${user.phone || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>Date of Birth:</label>
                                <span>${user.date_of_birth || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>Nationality:</label>
                                <span>${user.nationality || 'N/A'}</span>
                            </div>
                        </div>
                        <div class="detail-column">
                            <h3>Account Information</h3>
                            <div class="detail-item">
                                <label>Account Number:</label>
                                <span>${user.account_number}</span>
                            </div>
                            <div class="detail-item">
                                <label>Account Type:</label>
                                <span>${user.account_type}</span>
                            </div>
                            <div class="detail-item">
                                <label>Status:</label>
                                <span class="status-badge status-${user.status.toLowerCase()}">${user.status}</span>
                            </div>
                            <div class="detail-item">
                                <label>Balance:</label>
                                <span class="balance">${user.currency || '$'}${parseFloat(user.balance).toLocaleString('en-US', {minimumFractionDigits: 2})}</span>
                            </div>
                            <div class="detail-item">
                                <label>Created:</label>
                                <span>${new Date(user.created_at).toLocaleDateString()}</span>
                            </div>
                        </div>
                        <div class="detail-column">
                            <h3>Banking Codes</h3>
                            <div class="detail-item">
                                <label>IMF Code:</label>
                                <span>${user.imf_code || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>SWIFT Code:</label>
                                <span>${user.swift_code || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>COT Code:</label>
                                <span>${user.cot_code || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>Transaction PIN:</label>
                                <span>${user.transaction_pin || 'N/A'}</span>
                            </div>
                            <div class="detail-item">
                                <label>IMF Enabled:</label>
                                <span class="status-badge status-${user.imf_enabled ? 'active' : 'inactive'}">${user.imf_enabled ? 'Yes' : 'No'}</span>
                            </div>
                            <div class="detail-item">
                                <label>SWIFT Enabled:</label>
                                <span class="status-badge status-${user.swift_enabled ? 'active' : 'inactive'}">${user.swift_enabled ? 'Yes' : 'No'}</span>
                            </div>
                            <div class="detail-item">
                                <label>COT Enabled:</label>
                                <span class="status-badge status-${user.cot_enabled ? 'active' : 'inactive'}">${user.cot_enabled ? 'Yes' : 'No'}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            document.getElementById('viewUserContent').innerHTML = content;
        }

        function populateEditForm(user) {
            const content = `
                <form method="POST" class="edit-user-form">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_id" value="${user.id}">
                    
                    <div class="form-row">
                        <div class="form-column">
                            <h3>Personal Information</h3>
                            <div class="form-group">
                                <label for="edit_firstname">First Name</label>
                                <input type="text" id="edit_firstname" name="firstname" value="${user.firstname}" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_middlename">Middle Name</label>
                                <input type="text" id="edit_middlename" name="middlename" value="${user.middlename || ''}">
                            </div>
                            <div class="form-group">
                                <label for="edit_lastname">Last Name</label>
                                <input type="text" id="edit_lastname" name="lastname" value="${user.lastname}" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_username">Username</label>
                                <input type="text" id="edit_username" name="username" value="${user.username}" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_email">Email</label>
                                <input type="email" id="edit_email" name="email" value="${user.email}" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_phone">Phone</label>
                                <input type="text" id="edit_phone" name="phone" value="${user.phone || ''}">
                            </div>
                        </div>
                        <div class="form-column">
                            <h3>Account Information</h3>
                            <div class="form-group">
                                <label for="edit_account_type">Account Type</label>
                                <select id="edit_account_type" name="account_type" required>
                                    <option value="Savings" ${user.account_type === 'Savings' ? 'selected' : ''}>Savings</option>
                                    <option value="Current" ${user.account_type === 'Current' ? 'selected' : ''}>Current</option>
                                    <option value="Business" ${user.account_type === 'Business' ? 'selected' : ''}>Business</option>
                                    <option value="Premium" ${user.account_type === 'Premium' ? 'selected' : ''}>Premium</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="edit_status">Status</label>
                                <select id="edit_status" name="status" required>
                                    <option value="Active" ${user.status === 'Active' ? 'selected' : ''}>Active</option>
                                    <option value="Pending" ${user.status === 'Pending' ? 'selected' : ''}>Pending</option>
                                    <option value="Suspended" ${user.status === 'Suspended' ? 'selected' : ''}>Suspended</option>
                                    <option value="Closed" ${user.status === 'Closed' ? 'selected' : ''}>Closed</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label for="edit_balance">Balance</label>
                                <input type="number" id="edit_balance" name="balance" value="${user.balance}" step="0.01" min="0" required>
                            </div>
                            <div class="form-group">
                                <label for="edit_nationality">Nationality</label>
                                <input type="text" id="edit_nationality" name="nationality" value="${user.nationality || ''}">
                            </div>
                            <div class="form-group">
                                <label for="edit_date_of_birth">Date of Birth</label>
                                <input type="date" id="edit_date_of_birth" name="date_of_birth" value="${user.date_of_birth || ''}">
                            </div>
                            <div class="form-group">
                                <label for="edit_address">Address</label>
                                <textarea id="edit_address" name="address">${user.address || ''}</textarea>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" class="btn btn-primary">Update User</button>
                        <button type="button" class="btn btn-secondary" onclick="closeModal('editUserModal')">Cancel</button>
                    </div>
                </form>
            `;
            document.getElementById('editUserContent').innerHTML = content;
        }
    </script>
</body>
</html>
