<?php
require_once 'config.inc.php';
require_login();

// Sanitize filter
$filter = $_GET['filter'] ?? 'all';
if (!in_array($filter, ['pending', 'approved', 'rejected'], true)) {
    $filter = 'all';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_csrf();
    $op = $_POST['op'] ?? '';

    if ($op === 'update_status') {
        $id = (int)($_POST['id'] ?? 0);
        $newStatus = $_POST['status'] ?? '';
        $allowedStatuses = ['pending', 'approved', 'rejected'];

        if ($id && in_array($newStatus, $allowedStatuses, true)) {
            $s = db()->prepare("UPDATE users SET account_status = ?, status = ? WHERE id = ?");
            $s->bind_param("ssi", $newStatus, $newStatus, $id);
            $s->execute();
            flash('success', 'User status updated to ' . ucfirst($newStatus) . '.');
        } else {
            flash('danger', 'Invalid status update request.');
        }
        redirect('users.php' . ($filter !== 'all' ? '?filter=' . urlencode($filter) : ''));
    }

    if ($op === 'delete') {
        try {
            $id = (int)$_POST['id'];
            $s = db()->prepare("DELETE FROM users WHERE id = ?");
            $s->bind_param("i", $id);
            $s->execute();
            flash('success', 'User deleted successfully.');
        } catch (Throwable $e) {
            flash('danger', 'User cannot be deleted because they have active orders or linked records.');
        }
        redirect('users.php' . ($filter !== 'all' ? '?filter=' . urlencode($filter) : ''));
    }
}

$pageTitle = 'User Management';
include 'partials/header.php';
?>

<div class="card p-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h5 class="m-0">User Management</h5>
        <!-- Top Right Filter Links -->
        <div class="btn-group btn-group-sm">
            <a href="users.php?filter=all" class="btn btn-<?= $filter === 'all' ? 'primary' : 'outline-primary' ?>">All</a>
            <a href="users.php?filter=pending" class="btn btn-<?= $filter === 'pending' ? 'warning' : 'outline-warning' ?>">Pending</a>
            <a href="users.php?filter=approved" class="btn btn-<?= $filter === 'approved' ? 'success' : 'outline-success' ?>">Approved</a>
            <a href="users.php?filter=rejected" class="btn btn-<?= $filter === 'rejected' ? 'danger' : 'outline-danger' ?>">Rejected</a>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>User Details</th>
                    <th>Phone</th>
                    <th>Address</th>
                    <th>Registered</th>
                    <th>Status</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                if ($filter !== 'all') {
                    $s = db()->prepare("SELECT * FROM users WHERE status = ? ORDER BY id DESC");
                    $s->bind_param("s", $filter);
                    $s->execute();
                    $r = $s->get_result();
                } else {
                    $r = db()->query("SELECT * FROM users ORDER BY id DESC");
                }
                
                if ($r->num_rows === 0): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">No users found for this filter.</td>
                    </tr>
                <?php endif;

                while ($u = $r->fetch_assoc()): 
                    $badgeClass = match($u['status']) {
                        'approved' => 'bg-success',
                        'rejected' => 'bg-danger',
                        default    => 'bg-warning text-dark'
                    };
                ?>
                    <tr>
                        <td>#<?=$u['id']?></td>
                        <td>
                            <strong><?=e($u['full_name'])?></strong><br>
                            <small class="text-muted"><?=e($u['email'])?></small>
                        </td>
                        <td><?=e($u['phone'])?></td>
                        <td><small><?=nl2br(e($u['address']))?></small></td>
                        <td><small><?=date('M d, Y h:i A', strtotime($u['created_at']))?></small></td>
                        <td>
                            <span class="badge <?=$badgeClass?>"><?=strtoupper(e($u['status']))?></span>
                        </td>
                        <td class="text-end">
                            <?php if ($u['status'] !== 'approved'): ?>
                                <form class="d-inline" method="post" action="users.php?filter=<?=e($filter)?>">
                                    <input type="hidden" name="csrf" value="<?=e(csrf())?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?=$u['id']?>">
                                    <input type="hidden" name="status" value="approved">
                                    <button class="btn btn-sm btn-success" title="Approve User">Approve</button>
                                </form>
                            <?php endif; ?>

                            <?php if ($u['status'] !== 'rejected'): ?>
                                <form class="d-inline" method="post" action="users.php?filter=<?=e($filter)?>">
                                    <input type="hidden" name="csrf" value="<?=e(csrf())?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?=$u['id']?>">
                                    <input type="hidden" name="status" value="rejected">
                                    <button class="btn btn-sm btn-outline-danger" data-confirm="Reject/Block this user?" title="Reject User">Reject</button>
                                </form>
                            <?php endif; ?>

                            <?php if ($u['status'] !== 'pending'): ?>
                                <form class="d-inline" method="post" action="users.php?filter=<?=e($filter)?>">
                                    <input type="hidden" name="csrf" value="<?=e(csrf())?>">
                                    <input type="hidden" name="op" value="update_status">
                                    <input type="hidden" name="id" value="<?=$u['id']?>">
                                    <input type="hidden" name="status" value="pending">
                                    <button class="btn btn-sm btn-outline-warning" title="Set to Pending">Pending</button>
                                </form>
                            <?php endif; ?>

                            <form class="d-inline" method="post" action="users.php?filter=<?=e($filter)?>">
                                <input type="hidden" name="csrf" value="<?=e(csrf())?>">
                                <input type="hidden" name="op" value="delete">
                                <input type="hidden" name="id" value="<?=$u['id']?>">
                                <button class="btn btn-sm btn-link text-danger p-0 ms-2" data-confirm="Permanently delete this user?" title="Delete">Delete</button>
                            </form>
                        </td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

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