<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$q = trim($_GET["q"] ?? "");
$type = trim($_GET["type"] ?? "all"); // all, workers, agencies, companies

if (strlen($q) < 2) {
    echo json_encode(["success" => true, "data" => []]);
    exit;
}

$sqls = [];
$params = [];

if ($type === "all" || $type === "workers") {
    $sqls[] = "SELECT 'worker' as type, id, first_name as name, location, 'worker' as role FROM workers WHERE first_name LIKE ? OR last_name LIKE ?";
    $params[] = $params[] = "%$q%";
}

if ($type === "all" || $type === "agencies" || $type === "companies") {
    $sqls[] = "SELECT 'user' as type, u.id, u.email as name, r.name as role FROM users u JOIN roles r ON u.role_id = r.id WHERE (u.role_id = 3 OR u.role_id = 4) AND u.email LIKE ?";
    $params[] = "%$q%";
}

$sql = implode(" UNION ", $sqls) . " ORDER BY name LIMIT 20";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
echo json_encode(["success" => true, "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
?>

