<?php
require_once '../includes/config.php';
requireLogin();
requireAdmin();

$page_title = "Users Management";

$success = '';
$error = '';

// Add/Update user balance
if (isset($_POST['fund_user'])) {
    $user_id = (int)$_POST['user_id'];
    $amount = (float)$_POST['amount'];
    $type = sanitize($_POST['type']);
    
    if ($type === 'add') {
        updateBalance($user_id, $amount, 'add');
        addTransaction($user_id, $amount, 'admin_credit', 'Balance credited by admin', 'completed');
        $success = 'User balance credited successfully!';
    } else {
        updateBalance($user_id, $amount, 'deduct');
        addTransaction($user_id, $amount, 'admin_debit', 'Balance debited by admin', 'completed');
        $success = 'User balance debited successfully!';
    }
}

// Update user status
if (isset($_POST['update_status'])) {
    $user_id = (int)$_POST['user_id'];
    $status = sanitize($_POST['status']);
    
    $stmt = $conn->prepare("UPDATE users SET status = ? WHERE id = ?");
    $stmt->bind_param("si", $status, $user_id);
    
    if ($stmt->execute()) {
        $success = 'User status updated successfully!';
    } else {
        $error = 'Failed to update user status';
    }
}

// Delete user
if (isset($_GET['delete'])) {
    $user_id = (int)$_GET['delete'];
    $conn->query("DELETE FROM users WHERE id = $user_id AND role = 'user'");
    $success = 'User deleted successfully!';
}

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Search
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$where = "WHERE role = 'user'";
if ($search) {
    $where .= " AND (username LIKE '%$search%' OR email LIKE '%$search%' OR full_name LIKE '%$search%')";
}

// Get total users
$total_users = $conn->query("SELECT COUNT(*) as count FROM users $where")->fetch_assoc()['count'];
$total_pages = ceil($total_users / $per_page);

// Get users
$users = $conn->query("SELECT * FROM users $where ORDER BY created_at DESC LIMIT $per_page OFFSET $offset");

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

<div class="page-header">
    <div>
        <h1>Users Management</h1>
        <p>Manage all registered users</p>
    </div>
</div>

<?php if ($success): ?>
    <div class="alert alert-success">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
            <polyline points="22 4 12 14.01 9 11.01"></polyline>
        </svg>
        <div><?php echo $success; ?></div>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger">
        <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <circle cx="12" cy="12" r="10"></circle>
            <line x1="15" y1="9" x2="9" y2="15"></line>
            <line x1="9" y1="9" x2="15" y2="15"></line>
        </svg>
        <div><?php echo $error; ?></div>
    </div>
<?php endif; ?>

<!-- Search -->
<div class="card">
    <div class="card-body">
        <form method="GET" class="d-flex gap-2">
            <input type="text" name="search" placeholder="Search by username, email or name" class="form-control" value="<?php echo htmlspecialchars($search); ?>" style="flex: 1;">
            <button type="submit" class="btn btn-primary">Search</button>
            <?php if ($search): ?>
                <a href="users.php" class="btn btn-secondary">Clear</a>
            <?php endif; ?>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h2>All Users (<?php echo number_format($total_users); ?>)</h2>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Email</th>
                        <th>WhatsApp</th>
                        <th>Full Name</th>
                        <th>Balance</th>
                        <th>Status</th>
                        <th>Joined</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($user = $users->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $user['id']; ?></td>
                            <td><strong><?php echo htmlspecialchars($user['username']); ?></strong></td>
                            <td><?php echo htmlspecialchars($user['email']); ?></td>
                            <td>
                                <?php if (!empty($user['whatsapp'])): ?>
                                    <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $user['whatsapp']); ?>"
                                       target="_blank"
                                       class="btn btn-sm"
                                       style="background:#25D366; color:#fff; text-decoration:none; white-space:nowrap;">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align:middle; margin-right:3px;">
                                            <path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07A19.5 19.5 0 0 1 4.69 13.6 19.79 19.79 0 0 1 1.6 5.06 2 2 0 0 1 3.56 3h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L7.91 10.7a16 16 0 0 0 5.34 5.34l.91-.91a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"></path>
                                        </svg>
                                        <?php echo htmlspecialchars($user['whatsapp']); ?>
                                    </a>
                                <?php else: ?>
                                    <span style="color:#9ca3af;">—</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($user['full_name']); ?></td>
                            <td><?php echo formatMoney($user['balance']); ?></td>
                            <td>
                                <span class="badge badge-<?php echo $user['status'] === 'active' ? 'success' : 'danger'; ?>">
                                    <?php echo ucfirst($user['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                            <td>
                                <button onclick="fundUser(<?php echo htmlspecialchars(json_encode($user)); ?>)" class="btn btn-sm btn-success">Fund</button>
                                <button onclick="changeStatus(<?php echo htmlspecialchars(json_encode($user)); ?>)" class="btn btn-sm btn-secondary">Status</button>
                                <a href="?delete=<?php echo $user['id']; ?>" onclick="return confirm('Delete this user?')" class="btn btn-sm btn-danger">Delete</a>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

        <?php if ($total_pages > 1): ?>
            <div class="mt-3 text-center">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?php echo $i; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>" 
                       class="btn btn-sm <?php echo $i === $page ? 'btn-primary' : 'btn-secondary'; ?>" 
                       style="margin: 0 2px;"><?php echo $i; ?></a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Fund User Modal -->
<div id="fundModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Fund User</h3>
            <button class="modal-close" onclick="document.getElementById('fundModal').classList.remove('active')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <input type="hidden" name="user_id" id="fund_user_id">
                <p><strong>User:</strong> <span id="fund_username"></span></p>
                <p><strong>Current Balance:</strong> <span id="fund_balance"></span></p>
                <p><strong>WhatsApp:</strong> <span id="fund_whatsapp"></span></p>
                
                <div class="form-group">
                    <label>Action</label>
                    <select name="type" class="form-control" required>
                        <option value="add">Add Funds</option>
                        <option value="deduct">Deduct Funds</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label>Amount</label>
                    <input type="number" name="amount" step="0.01" class="form-control" required>
                </div>
                
                <button type="submit" name="fund_user" class="btn btn-primary w-100">Update Balance</button>
            </form>
        </div>
    </div>
</div>

<!-- Change Status Modal -->
<div id="statusModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Change User Status</h3>
            <button class="modal-close" onclick="document.getElementById('statusModal').classList.remove('active')">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <input type="hidden" name="user_id" id="status_user_id">
                <p><strong>User:</strong> <span id="status_username"></span></p>
                
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" id="status_select" class="form-control" required>
                        <option value="active">Active</option>
                        <option value="suspended">Suspended</option>
                        <option value="banned">Banned</option>
                    </select>
                </div>
                
                <button type="submit" name="update_status" class="btn btn-primary w-100">Update Status</button>
            </form>
        </div>
    </div>
</div>

<script>
    function fundUser(user) {
        document.getElementById('fund_user_id').value = user.id;
        document.getElementById('fund_username').textContent = user.username;
        document.getElementById('fund_balance').textContent = '₦' + parseFloat(user.balance).toFixed(2);
        document.getElementById('fund_whatsapp').textContent = user.whatsapp || 'Not provided';
        document.getElementById('fundModal').classList.add('active');
    }
    
    function changeStatus(user) {
        document.getElementById('status_user_id').value = user.id;
        document.getElementById('status_username').textContent = user.username;
        document.getElementById('status_select').value = user.status;
        document.getElementById('statusModal').classList.add('active');
    }
</script>

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