<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['super_admin']);

$db = getDBConnection();

// Handle toggle active
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_id'])) {
    if (validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $toggleId = (int)$_POST['toggle_id'];
        $currUser = (int)getSession('user_id');
        if ($toggleId !== $currUser) { // Can't disable yourself
            $cur = (int)dbVal($db, "SELECT is_active FROM users WHERE id=?", [$toggleId]);
            $db->prepare("UPDATE users SET is_active=? WHERE id=?")->execute([$cur ? 0 : 1, $toggleId]);
        }
    }
    header('Location: users.php');
    exit;
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    if (validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $delId = (int)$_POST['delete_id'];
        if ($delId !== (int)getSession('user_id')) {
            $db->prepare("DELETE FROM users WHERE id=?")->execute([$delId]);
        }
    }
    header('Location: users.php');
    exit;
}

$search  = trim($_GET['q'] ?? '');
$page    = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page - 1) * $perPage;

$where  = $search ? "WHERE username LIKE ? OR full_name LIKE ? OR role LIKE ?" : '';
$params = $search ? ["%{$search}%", "%{$search}%", "%{$search}%"] : [];

$total      = (int)dbVal($db, "SELECT COUNT(*) FROM users {$where}", $params);
$totalPages = (int)ceil($total / $perPage);
$users      = dbRows($db,
    "SELECT * FROM users {$where} ORDER BY FIELD(role,'super_admin','exn','sdo','je','mr'), full_name LIMIT {$perPage} OFFSET {$offset}",
    $params);

$pageTitle = 'Manage Users';
include __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-people-fill me-2"></i>Manage Users</h1>
    </div>
    <a href="<?= BASE_URL ?>/modules/admin/user_form.php" class="btn btn-erp">
        <i class="bi bi-person-plus-fill me-2"></i>Add User
    </a>
</div>

<!-- Search -->
<div class="erp-card mb-3">
    <form method="GET" class="d-flex gap-2">
        <input type="text" name="q" class="form-control" placeholder="Search users..." value="<?= h($search) ?>">
        <button type="submit" class="btn btn-erp"><i class="bi bi-search"></i></button>
        <?php if ($search): ?>
        <a href="users.php" class="btn btn-outline-secondary"><i class="bi bi-x"></i></a>
        <?php endif; ?>
    </form>
</div>

<div class="erp-card">
    <div class="table-responsive">
        <table class="table table-hover" style="font-size:.84rem;">
            <thead class="table-dark">
                <tr>
                    <th>#</th><th>Full Name</th><th>Username</th>
                    <th>Role</th><th>Division</th><th>Phone</th>
                    <th>Status</th><th>Created</th><th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($users)): ?>
                <tr><td colspan="9" class="text-center text-muted py-4">No users found.</td></tr>
                <?php endif; ?>
                <?php foreach ($users as $i => $u): ?>
                <tr>
                    <td class="text-muted"><?= $offset+$i+1 ?></td>
                    <td class="fw-semibold"><?= h($u['full_name']) ?></td>
                    <td><code><?= h($u['username']) ?></code></td>
                    <td><?= roleBadge($u['role']) ?></td>
                    <td class="text-muted"><?= h($u['division'] ?? '—') ?></td>
                    <td class="text-muted"><?= h($u['phone'] ?? '—') ?></td>
                    <td>
                        <?php if ($u['is_active']): ?>
                        <span class="badge bg-success">Active</span>
                        <?php else: ?>
                        <span class="badge bg-danger">Disabled</span>
                        <?php endif; ?>
                    </td>
                    <td class="text-muted" style="font-size:.76rem;"><?= date('d M Y', strtotime($u['created_at'])) ?></td>
                    <td>
                        <div class="d-flex gap-1 flex-wrap">
                            <a href="<?= BASE_URL ?>/modules/admin/user_form.php?id=<?= $u['id'] ?>"
                               class="btn btn-sm btn-outline-primary" title="Edit">
                                <i class="bi bi-pencil-fill"></i>
                            </a>

                            <?php if ($u['id'] !== (int)getSession('user_id')): ?>
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                                <input type="hidden" name="toggle_id" value="<?= $u['id'] ?>">
                                <button type="submit" class="btn btn-sm <?= $u['is_active']?'btn-outline-warning':'btn-outline-success' ?>"
                                        title="<?= $u['is_active']?'Disable':'Enable' ?>">
                                    <i class="bi <?= $u['is_active']?'bi-toggle-on':'bi-toggle-off' ?>"></i>
                                </button>
                            </form>
                            <form method="POST" class="d-inline"
                                  onsubmit="return confirm('Delete user <?= h(addslashes($u['full_name'])) ?>? This cannot be undone.')">
                                <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">
                                <input type="hidden" name="delete_id" value="<?= $u['id'] ?>">
                                <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                    <i class="bi bi-trash-fill"></i>
                                </button>
                            </form>
                            <?php else: ?>
                            <span class="text-muted" style="font-size:.75rem;">(You)</span>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php if ($totalPages > 1): ?>
<div class="d-flex align-items-center justify-content-between mt-3 flex-wrap gap-2">
    <span class="text-muted" style="font-size:.82rem;">Showing <strong><?= $offset+1 ?>–<?= min($offset+$perPage,$total) ?></strong> of <strong><?= $total ?></strong> users</span>
    <nav>
        <ul class="pagination pagination-sm mb-0">
            <li class="page-item <?= $page<=1?'disabled':'' ?>">
                <a class="page-link" href="?q=<?= h($search) ?>&page=<?= $page-1 ?>"><i class="bi bi-chevron-left"></i></a>
            </li>
            <?php
            $start = max(1, $page-2); $end = min($totalPages, $page+2);
            if ($start > 1): ?><li class="page-item"><a class="page-link" href="?q=<?= h($search) ?>&page=1">1</a></li><?php if($start>2): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; endif;
            for ($p = $start; $p <= $end; $p++): ?>
            <li class="page-item <?= $p==$page?'active':'' ?>">
                <a class="page-link" href="?q=<?= h($search) ?>&page=<?= $p ?>"><?= $p ?></a>
            </li>
            <?php endfor;
            if ($end < $totalPages): if($end<$totalPages-1): ?><li class="page-item disabled"><span class="page-link">…</span></li><?php endif; ?><li class="page-item"><a class="page-link" href="?q=<?= h($search) ?>&page=<?= $totalPages ?>"><?= $totalPages ?></a></li><?php endif; ?>
            <li class="page-item <?= $page>=$totalPages?'disabled':'' ?>">
                <a class="page-link" href="?q=<?= h($search) ?>&page=<?= $page+1 ?>"><i class="bi bi-chevron-right"></i></a>
            </li>
        </ul>
    </nav>
</div>
<?php endif; ?>

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