<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();

// Redirect to login if the admin is not authenticated
if (!isset($_SESSION['admin_id'])) {
    header("Location: index.php");
    exit();
}

// Include Database Connection
require_once "../account/include/db.php";

// --- ACTION LOGIC (Fund, Suspend & Delete) ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && isset($_POST['user_id'])) {
    $target_user_id = (int)$_POST['user_id'];

    if ($_POST['action'] === 'delete') {
        $del_query = "DELETE FROM `users` WHERE `id` = ?";
        if ($stmt = mysqli_prepare($conn, $del_query)) {
            mysqli_stmt_bind_param($stmt, "i", $target_user_id);
            if (mysqli_stmt_execute($stmt)) {
                $_SESSION['swal_success'] = "User account has been permanently removed.";
                $_SESSION['swal_title'] = "Deleted!";
            } else {
                $_SESSION['swal_error'] = "Failed to delete user: " . mysqli_error($conn);
            }
            mysqli_stmt_close($stmt);
        }
    } elseif ($_POST['action'] === 'toggle_suspend') {
        $stat_query = "SELECT `status` FROM `users` WHERE `id` = ?";
        $current_status = 'active';
        
        if ($stmt = mysqli_prepare($conn, $stat_query)) {
            mysqli_stmt_bind_param($stmt, "i", $target_user_id);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_bind_result($stmt, $fetched_status);
            if (mysqli_stmt_fetch($stmt)) { $current_status = $fetched_status; }
            mysqli_stmt_close($stmt);
            
            $new_status = ($current_status === 'suspended') ? 'active' : 'suspended';
            $upd_query = "UPDATE `users` SET `status` = ? WHERE `id` = ?";
            if ($stmt2 = mysqli_prepare($conn, $upd_query)) {
                mysqli_stmt_bind_param($stmt2, "si", $new_status, $target_user_id);
                if (mysqli_stmt_execute($stmt2)) {
                    $_SESSION['swal_success'] = "Account status is now " . ucfirst($new_status);
                    $_SESSION['swal_title'] = "Status Updated";
                }
                mysqli_stmt_close($stmt2);
            }
        }
    } elseif ($_POST['action'] === 'fund_wallet' && isset($_POST['amount'])) {
        $amount = (float)$_POST['amount'];
        if ($amount > 0) {
            $fund_query = "UPDATE `users` SET `balance` = `balance` + ? WHERE `id` = ?";
            if ($stmt3 = mysqli_prepare($conn, $fund_query)) {
                mysqli_stmt_bind_param($stmt3, "di", $amount, $target_user_id);
                if (mysqli_stmt_execute($stmt3)) {
                    $_SESSION['swal_success'] = "Successfully added $" . number_format($amount, 2) . " to the user's wallet.";
                    $_SESSION['swal_title'] = "Funds Added!";
                } else {
                    $_SESSION['swal_error'] = "Failed to add funds: " . mysqli_error($conn);
                }
                mysqli_stmt_close($stmt3);
            }
        } else {
            $_SESSION['swal_error'] = "Please enter a valid amount greater than 0.";
        }
    }
    
    // Refresh to clear POST data and show alert
    header("Location: manage_users.php?page=" . (isset($_GET['page']) ? (int)$_GET['page'] : 1));
    exit();
}

// --- PAGINATION LOGIC ---
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$total_query = "SELECT COUNT(*) as total FROM `users`";
$total_result = mysqli_query($conn, $total_query);
$total_row = mysqli_fetch_assoc($total_result);
$total_users = $total_row['total'];
$total_pages = ceil($total_users / $limit);

$query = "SELECT `id`, `username`, `full_name`, `email`, `balance`, `country`, `phone`, `status`, `created_at` 
          FROM `users` 
          ORDER BY `created_at` DESC 
          LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $query);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    body { font-family: 'Inter', system-ui, -apple-system, sans-serif !important; }
    .data-table { font-variant-numeric: tabular-nums; }
    .pagination-link:hover { background-color: rgba(51, 65, 85, 1); }
    .active-page { background-color: #3b82f6 !important; color: white !important; }
</style>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<main class="md:ml-64 p-4 md:p-6 min-h-[calc(100vh-65px)] flex flex-col relative z-10 bg-slate-950">
    
    <div class="mb-8">
        <div class="text-[10px] font-bold text-blue-500 tracking-widest uppercase mb-1">Premiumtrustglobal Admin</div>
        <h1 class="text-2xl md:text-3xl font-bold text-white tracking-tight">User Management</h1>
        <p class="text-slate-400 mt-1 text-sm">Manage, suspend, fund, and monitor all registered accounts</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="bg-slate-900 border border-slate-800 p-6 rounded-xl shadow-lg">
            <h3 class="text-xs font-semibold text-slate-500 uppercase tracking-wider mb-2">Total Users</h3>
            <div class="flex items-baseline gap-3">
                <span class="text-3xl font-bold text-white"><?php echo number_format($total_users); ?></span>
            </div>
        </div>
    </div>

    <div class="bg-slate-900 border border-slate-800 rounded-xl overflow-hidden flex-grow mb-6 shadow-xl">
        <div class="p-4 border-b border-slate-800 flex justify-between items-center bg-slate-900/50">
            <h2 class="text-sm font-semibold text-slate-300">Active Directory</h2>
        </div>
        
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse data-table min-w-[800px]">
                <thead>
                    <tr class="border-b border-slate-800 bg-slate-950 text-xs text-slate-400 uppercase tracking-widest">
                        <th class="p-4 font-medium">User</th>
                        <th class="p-4 font-medium">Contact</th>
                        <th class="p-4 font-medium">Balance</th>
                        <th class="p-4 font-medium">Status / Location</th>
                        <th class="p-4 font-medium text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="text-sm text-slate-300 divide-y divide-slate-800/50">
                    <?php 
                    if ($result && mysqli_num_rows($result) > 0) {
                        while ($row = mysqli_fetch_assoc($result)) {
                            $is_suspended = (isset($row['status']) && $row['status'] === 'suspended');
                    ?>
                            <tr class="hover:bg-slate-800/40 transition-colors <?php echo $is_suspended ? 'opacity-60' : ''; ?>">
                                <td class="p-4">
                                    <div class="font-medium text-slate-100 flex items-center gap-2">
                                        <?php echo htmlspecialchars($row['full_name']); ?>
                                        <?php if($is_suspended): ?>
                                            <span class="w-2 h-2 rounded-full bg-red-500" title="Suspended"></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-xs text-slate-500">@<?php echo htmlspecialchars($row['username']); ?></div>
                                </td>
                                <td class="p-4">
                                    <div class="text-slate-300"><?php echo htmlspecialchars($row['email']); ?></div>
                                    <div class="text-xs text-slate-500"><?php echo htmlspecialchars($row['phone']); ?></div>
                                </td>
                                <td class="p-4 font-semibold text-emerald-400">
                                    $<?php echo number_format((float)$row['balance'], 2); ?>
                                </td>
                                <td class="p-4">
                                    <div class="mb-1">
                                        <?php if($is_suspended): ?>
                                            <span class="px-2 py-0.5 rounded text-[10px] uppercase font-bold bg-red-500/10 text-red-400 border border-red-500/20">Suspended</span>
                                        <?php else: ?>
                                            <span class="px-2 py-0.5 rounded text-[10px] uppercase font-bold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Active</span>
                                        <?php endif; ?>
                                    </div>
                                    <span class="text-xs text-slate-400"><?php echo htmlspecialchars($row['country'] ?: 'Unknown'); ?></span>
                                </td>
                                <td class="p-4 text-right flex justify-end items-center gap-3">
                                    <button type="button" onclick="fundUserWallet(<?php echo $row['id']; ?>, '<?php echo htmlspecialchars($row['username']); ?>')" class="text-xs font-medium text-emerald-400 hover:text-emerald-300 border border-emerald-500/30 px-2 py-1 rounded bg-emerald-500/10">Fund</button>
                                    
                                    <a href="edit_user.php?id=<?php echo $row['id']; ?>" class="text-blue-400 hover:text-blue-300 text-xs font-medium">Edit</a>
                                    
                                    <form method="POST" class="inline m-0">
                                        <input type="hidden" name="user_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="toggle_suspend">
                                        <button type="button" onclick="confirmAction(this.form, '<?php echo $is_suspended ? 'reactivate' : 'suspend'; ?>')" class="text-xs font-medium <?php echo $is_suspended ? 'text-emerald-500' : 'text-orange-400'; ?>">
                                            <?php echo $is_suspended ? 'Activate' : 'Suspend'; ?>
                                        </button>
                                    </form>

                                    <form method="POST" class="inline m-0">
                                        <input type="hidden" name="user_id" value="<?php echo $row['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="button" onclick="confirmAction(this.form, 'delete')" class="text-xs font-medium text-red-500 hover:text-red-400 bg-red-500/10 px-2 py-1 rounded border border-red-500/20">
                                            Delete
                                        </button>
                                    </form>
                                </td>
                            </tr>
                    <?php 
                        }
                    }
                    ?>
                </tbody>
            </table>
        </div>

        <div class="p-4 border-t border-slate-800 flex items-center justify-between bg-slate-900/50">
            <div class="text-xs text-slate-500">Showing page <?php echo $page; ?> of <?php echo $total_pages; ?></div>
            <div class="flex gap-1">
                <?php if($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-link px-3 py-1 rounded border border-slate-700 text-slate-400 text-xs">Prev</a>
                <?php endif; ?>
                <?php if($page < $total_pages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-link px-3 py-1 rounded border border-slate-700 text-slate-400 text-xs">Next</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</main>

<script>
// Logic to handle the "Fund Wallet" prompt
function fundUserWallet(userId, username) {
    Swal.fire({
        title: 'Fund Wallet',
        text: `Enter the amount to add to @${username}'s account:`,
        input: 'number',
        inputAttributes: {
            min: '0.01',
            step: '0.01'
        },
        showCancelButton: true,
        confirmButtonText: 'Add Funds',
        confirmButtonColor: '#10b981',
        cancelButtonColor: '#1e293b',
        background: '#0f172a',
        color: '#f1f5f9',
        preConfirm: (amount) => {
            if (!amount || amount <= 0) {
                Swal.showValidationMessage('Please enter a valid amount greater than 0');
            }
            return amount;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            // Dynamically create a form to submit the request
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'fund_wallet';

            const userIdInput = document.createElement('input');
            userIdInput.type = 'hidden';
            userIdInput.name = 'user_id';
            userIdInput.value = userId;

            const amountInput = document.createElement('input');
            amountInput.type = 'hidden';
            amountInput.name = 'amount';
            amountInput.value = result.value;

            form.appendChild(actionInput);
            form.appendChild(userIdInput);
            form.appendChild(amountInput);
            
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Logic to handle the "Are you sure?" confirmation alerts
function confirmAction(form, actionType) {
    let config = {
        title: 'Are you sure?',
        text: `You are about to ${actionType} this user account.`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: actionType === 'delete' ? '#ef4444' : '#3b82f6',
        cancelButtonColor: '#1e293b',
        confirmButtonText: 'Yes, proceed!',
        background: '#0f172a',
        color: '#f1f5f9'
    };

    Swal.fire(config).then((result) => {
        if (result.isConfirmed) {
            form.submit();
        }
    });
}

// Logic to show the success message after the page reloads
<?php if (isset($_SESSION['swal_success'])): ?>
    Swal.fire({
        title: '<?php echo $_SESSION['swal_title']; ?>',
        text: '<?php echo $_SESSION['swal_success']; ?>',
        icon: 'success',
        background: '#0f172a',
        color: '#f1f5f9',
        confirmButtonColor: '#3b82f6'
    });
    <?php unset($_SESSION['swal_success'], $_SESSION['swal_title']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['swal_error'])): ?>
    Swal.fire({
        title: 'Error!',
        text: '<?php echo $_SESSION['swal_error']; ?>',
        icon: 'error',
        background: '#0f172a',
        color: '#f1f5f9',
        confirmButtonColor: '#ef4444'
    });
    <?php unset($_SESSION['swal_error']); ?>
<?php endif; ?>
</script>

<?php include 'includes/footer.php'; ?>