<?php
/**
 * GET /api/admin/users_list.php
 * Admin-only. Query params: account_type=personal|business|admin, status=active|suspended|pending,
 * search=<email or name>, page=<int>
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

require_login();
require_role(['admin']);

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

$pdo = Database::connect();

$where = [];
$params = [];

if (!empty($_GET['account_type'])) {
    $where[] = 'u.account_type = ?';
    $params[] = $_GET['account_type'];
}
if (!empty($_GET['status'])) {
    $where[] = 'u.status = ?';
    $params[] = $_GET['status'];
}
if (!empty($_GET['search'])) {
    $where[] = '(u.email LIKE ? OR pp.full_name LIKE ? OR bp.business_name LIKE ?)';
    $term = '%' . $_GET['search'] . '%';
    array_push($params, $term, $term, $term);
}
if (isset($_GET['is_featured_vendor']) && $_GET['is_featured_vendor'] !== '') {
    $where[] = 'u.is_featured_vendor = ?';
    $params[] = $_GET['is_featured_vendor'] === '1' ? 1 : 0;
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$countStmt = $pdo->prepare("
    SELECT COUNT(*) FROM users u
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    $whereSql
");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$sql = "
    SELECT u.id, u.email, u.phone, u.account_type, u.status, u.created_at, u.is_featured_vendor,
           COALESCE(pp.full_name, bp.business_name) AS display_name
    FROM users u
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    $whereSql
    ORDER BY u.created_at DESC
    LIMIT $perPage OFFSET $offset
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$users = $stmt->fetchAll();
foreach ($users as &$u) {
    $u['is_featured_vendor'] = (bool) $u['is_featured_vendor'];
}

send_json(true, 'OK', [
    'users' => $users,
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
