<?php
require_once 'config/db.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

requireLogin();
requireAdmin();

$search = trim($_GET['search'] ?? '');
$filter_role = $_GET['role'] ?? '';

$where = "WHERE 1=1";
$params = []; $types = "";
if ($search) {
    $like = "%$search%";
    $where .= " AND (username LIKE ? OR full_name LIKE ? OR email LIKE ?)";
    $params[] = $like; $params[] = $like; $params[] = $like; $types .= "sss";
}
if ($filter_role && in_array($filter_role, ['admin','staff'])) {
    $where .= " AND role = ?";
    $params[] = $filter_role; $types .= "s";
}

$users = fetchAll($conn,
    "SELECT id, username, full_name, role, email, phone, is_active, created_at
     FROM users $where ORDER BY created_at DESC",
    $params, $types);

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

<div class="row mb-4">
    <div class="col-lg-8">
        <h3><i class="fas fa-users"></i> Users Management</h3>
    </div>
    <div class="col-lg-4 text-end">
        <a href="/cash_lending/add-user.php" class="btn btn-primary">
            <i class="fas fa-plus"></i> Add New User
        </a>
    </div>
</div>

<!-- Search & Filter -->
<div class="card mb-3">
    <div class="card-body py-2">
        <form method="GET" class="d-flex gap-2 flex-wrap align-items-center">
            <input type="text" class="form-control" name="search" placeholder="Search name, username or email…"
                   value="<?php echo htmlspecialchars($search); ?>" style="max-width:260px;">
            <select class="form-select" name="role" style="max-width:140px;" onchange="this.form.submit()">
                <option value="">All Roles</option>
                <option value="admin" <?php echo $filter_role==='admin'?'selected':''; ?>>Admin</option>
                <option value="staff" <?php echo $filter_role==='staff'?'selected':''; ?>>Staff</option>
            </select>
            <button type="submit" class="btn btn-outline-primary"><i class="fas fa-search"></i> Search</button>
            <?php if ($search || $filter_role): ?>
                <a href="/cash_lending/users.php" class="btn btn-outline-secondary"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
            <small class="text-muted ms-auto"><?php echo count($users); ?> user(s)</small>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h5 class="mb-0">System Users</h5>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($users)): ?>
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Full Name</th>
                            <th>Role</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users as $user): ?>
                            <tr>
                                <td><code><?php echo htmlspecialchars($user['username']); ?></code></td>
                                <td><strong><?php echo htmlspecialchars($user['full_name']); ?></strong></td>
                                <td>
                                    <span class="badge <?php echo $user['role'] === 'admin' ? 'bg-danger' : 'bg-info'; ?>">
                                        <?php echo ucfirst($user['role']); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($user['email'] ?? '—'); ?></td>
                                <td><?php echo htmlspecialchars($user['phone'] ?? '—'); ?></td>
                                <td>
                                    <?php if ($user['is_active']): ?>
                                        <span class="badge bg-success">Active</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">Inactive</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="/cash_lending/edit-user.php?id=<?php echo $user['id']; ?>" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteUser(<?php echo $user['id']; ?>)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state p-5">
                <i class="fas fa-inbox"></i>
                <h5>No Users Found</h5>
                <a href="/cash_lending/add-user.php" class="btn btn-primary mt-3">
                    <i class="fas fa-plus"></i> Add User
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function deleteUser(id) {
    if (!confirmDelete('Are you sure you want to delete this user?')) {
        return;
    }

    fetch('/cash_lending/api/delete-user.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'id=' + id
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccess('User deleted successfully');
            setTimeout(() => location.reload(), 1000);
        } else {
            showError(data.message || 'Error deleting user');
        }
    })
    .catch(error => {
        showError('An error occurred');
        console.error('Error:', error);
    });
}
</script>

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