<?php
/**
 * API DE BÚSQUEDA DE PERSONAL (STAFF)
 * Endpoint: db/search-staff-profile.php
 */
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../core/api.php';

// 1. Verificación de Sesión
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    echo json_encode([]);
    exit;
}

// 2. Sanitización
$q = $_GET['q'] ?? '';
if (strlen($q) < 2) {
    echo json_encode([]);
    exit;
}

try {
    $term = "%" . $q . "%";

    $sql = "
        SELECT 
            id, 
            first_name, 
            last_name, 
            job_title as company, 
            public_uid as badge, 
            'staff' as type 
        FROM staff 
        WHERE user_id = :uid 
          AND status = 'active' 
          AND (
              first_name LIKE :t1 OR 
              last_name LIKE :t2 OR 
              public_uid LIKE :t3 OR
              job_title LIKE :t4
          )
        LIMIT 20
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':uid' => $user_id,
        ':t1'  => $term,
        ':t2'  => $term,
        ':t3'  => $term,
        ':t4'  => $term
    ]);

    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($results);

} catch (Exception $e) {
    error_log("Search Staff Error: " . $e->getMessage());
    echo json_encode([]);
}
?>