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

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

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

$status = trim((string)($_GET["status"] ?? ""));
$skills = trim((string)($_GET["skills"] ?? ""));
$location = trim((string)($_GET["location"] ?? ""));
$country = trim((string)($_GET["country"] ?? ""));
$languages = trim((string)($_GET["languages"] ?? ""));
$availability = trim((string)($_GET["availability"] ?? ""));
$certificates = trim((string)($_GET["certificates"] ?? ""));
$position = trim((string)($_GET["position"] ?? ""));
$q = trim((string)($_GET["q"] ?? ""));

$allowedStatuses = ["slobodan", "pregovori", "zaposlen"];
if ($status !== "" && !in_array($status, $allowedStatuses, true)) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "invalid_status"]);
    exit;
}

$sql = "
SELECT 
    w.id,
    w.user_id,
    w.first_name,
    w.last_name,
    w.status,
    w.updated_at,
    up.skills,
    GROUP_CONCAT(DISTINCT COALESCE(s.name, s2.name) ORDER BY COALESCE(s.name, s2.name) SEPARATOR ', ') AS skill_names,
    up.location,
    up.languages,
    up.country,
    up.availability,
    up.certificates,
    up.bio,
    up.photo_url,
    up.youtube_url,
    up.desired_salary_from,
    up.desired_salary_to,
    up.video_interview,
    up.video_work,
    up.position,
    wd.consent_path,
    wd.passport_path,
    wd.diploma_path,
    wd.invitation_letter_path,
    wd.offer_letter_path
FROM workers w
LEFT JOIN user_profiles up ON up.user_id = w.user_id
LEFT JOIN user_skills us ON us.user_id = w.user_id
LEFT JOIN skills s ON s.id = us.skill_id
LEFT JOIN skills s2 ON FIND_IN_SET(CAST(s2.id AS CHAR), REPLACE(COALESCE(up.skills, ''), ' ', '')) > 0
LEFT JOIN worker_documents wd ON wd.worker_id = w.id
LEFT JOIN worker_added_by wab ON wab.worker_id = w.id
WHERE 1=1
";
$params = [];

if ($roleId === 3) {
    $sql .= " AND wab.added_by_user_id = ?";
    $params[] = $userId;
} elseif ($roleId !== 1 && $roleId !== 5) {
    $sql .= " AND (
        NOT EXISTS (
            SELECT 1 FROM matches m_any
            WHERE m_any.worker_id = w.id
        )
        OR EXISTS (
            SELECT 1 FROM matches m_vis
            WHERE m_vis.worker_id = w.id
              AND (m_vis.company_id = ? OR m_vis.matched_for = ? OR m_vis.matched_by = ?)
        )
    )";
    $params[] = $userId;
    $params[] = $userId;
    $params[] = $userId;
}

if ($status !== "") {
    $sql .= " AND w.status = ?";
    $params[] = $status;
}
if ($skills !== "") {
    $sql .= " AND (up.skills LIKE ? OR s.name LIKE ? OR s2.name LIKE ?)";
    $params[] = "%" . $skills . "%";
    $params[] = "%" . $skills . "%";
    $params[] = "%" . $skills . "%";
}
if ($location !== "") {
    $sql .= " AND up.location LIKE ?";
    $params[] = "%" . $location . "%";
}
if ($country !== "") {
    $sql .= " AND up.country LIKE ?";
    $params[] = "%" . $country . "%";
}
if ($languages !== "") {
    $sql .= " AND up.languages LIKE ?";
    $params[] = "%" . $languages . "%";
}
if ($availability !== "") {
    $sql .= " AND up.availability = ?";
    $params[] = $availability;
}
if ($certificates !== "") {
    $sql .= " AND up.certificates LIKE ?";
    $params[] = "%" . $certificates . "%";
}
if ($position !== "") {
    $sql .= " AND up.position LIKE ?";
    $params[] = "%" . $position . "%";
}
if ($q !== "") {
    $sql .= " AND (
        w.first_name LIKE ?
        OR w.last_name LIKE ?
        OR up.skills LIKE ?
        OR s.name LIKE ?
        OR s2.name LIKE ?
        OR up.location LIKE ?
        OR up.bio LIKE ?
        OR up.country LIKE ?
        OR up.languages LIKE ?
        OR up.certificates LIKE ?
    )";
    $like = "%" . $q . "%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}

$sql .= " GROUP BY
    w.id, w.user_id, w.first_name, w.last_name, w.status, w.updated_at,
    up.skills, up.location, up.languages, up.country, up.availability,
    up.certificates, up.bio, up.photo_url, up.youtube_url,
    up.desired_salary_from, up.desired_salary_to, up.video_interview, up.video_work, up.position,
    wd.consent_path, wd.passport_path, wd.diploma_path, wd.invitation_letter_path, wd.offer_letter_path
    ORDER BY w.updated_at DESC, w.id DESC";

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

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

