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

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

$userId = (int)($_SESSION["user"]["id"] ?? 0);
$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);

$q = trim((string)($_GET["q"] ?? ""));
$location = trim((string)($_GET["location"] ?? ""));
$skills = trim((string)($_GET["skills"] ?? "")); // optional for agencies

$sql = "
SELECT 
    u.id,
    u.email,
    up.location,
    up.bio,
    up.photo_url,
    r.name as role
FROM users u
LEFT JOIN user_profiles up ON up.user_id = u.id
JOIN roles r ON u.role_id = r.id
WHERE u.role_id = 3
";
$params = [];

if ($roleId !== 1) {
    $sql .= " AND u.id != ?";
    $params[] = $userId;
}

if ($q !== "") {
    $sql .= " AND (u.email LIKE ? OR up.bio LIKE ? OR up.location LIKE ?)";
    $like = "%" . $q . "%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

if ($location !== "") {
    $sql .= " AND up.location LIKE ?";
    $params[] = "%" . $location . "%";
}

if ($skills !== "") {
    $sql .= " AND up.skills LIKE ?";
    $params[] = "%" . $skills . "%";
}

$sql .= " ORDER BY u.email ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

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

