<?php
declare(strict_types=1);

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

ini_set('display_errors', '0');
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../core/api.php';
global $pdo;

$user_id = $_SESSION['user_id'] ?? null;
$q = filter_input(INPUT_GET, 'q', FILTER_SANITIZE_SPECIAL_CHARS) ?? '';
$filter = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_FULL_SPECIAL_CHARS) ?? 'all'; 

$user_id = (int)$user_id;

if (!$user_id || strlen($q) < 2) {
    echo json_encode([]);
    exit;
}

if (!$pdo) {
    http_response_code(500); 
    echo json_encode(['success' => false, 'error' => 'ERROR INTERNO: Fallo en la conexi¨®n a la base de datos']); 
    exit;
}

try {
    $pdo->exec("SET NAMES 'utf8mb4'");

    $searchTerm = trim($q) . '*';
    
    // Nota: Se asume que las columnas tienen ¨ªndices FULLTEXT activos.
    $matchColsClients = "first_name, last_name, company, email, phone, mobile";
    $matchColsLeads   = "first_name, last_name, company, email, phone";

    // --- CONSULTA PARA CLIENTES ---
    $sqlClients = "
        SELECT 
            id, 
            'client' as source_type,
            first_name, 
            last_name, 
            company, 
            email, 
            phone, 
            mobile, 
            street_address, 
            city, 
            state_province, 
            zip_code
        FROM clients 
        WHERE user_id = :uid1 
        AND MATCH({$matchColsClients}) AGAINST(:term1 IN BOOLEAN MODE)
        LIMIT 10
    ";

    $sqlLeads = "
        SELECT 
            id, 
            'lead' as source_type,
            first_name, 
            last_name, 
            company, 
            email, 
            phone, 
            mobile, 
            street_address, 
            city, 
            state_province, 
            zip_code
        FROM leads 
        WHERE user_id = :uid2 
        AND MATCH({$matchColsLeads}) AGAINST(:term2 IN BOOLEAN MODE)
        LIMIT 10
    ";

    $finalSQL = '';
    $params = [];
    
    if ($filter === 'clients') {
        $finalSQL = $sqlClients;
        $params = [
            ':uid1'  => $user_id,
            ':term1' => $searchTerm
        ];
    } elseif ($filter === 'leads') {
        $finalSQL = $sqlLeads;
        $params = [
            ':uid2'  => $user_id,
            ':term2' => $searchTerm
        ];
    } else {
        $finalSQL = "({$sqlClients}) UNION ALL ({$sqlLeads}) LIMIT 20";
        $params = [
            ':uid1'  => $user_id,
            ':term1' => $searchTerm,
            ':uid2'  => $user_id,
            ':term2' => $searchTerm 
        ];
    }
    
    $stmt = $pdo->prepare($finalSQL);
    
    $stmt->execute($params);
    
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $finalResponse = [];

    foreach($results as $row) {
        $fullName = trim(($row['first_name'] ?? '') . ' ' . ($row['last_name'] ?? ''));
        if (empty($fullName)) {
            $fullName = $row['company'] ?? 'Sin Nombre';
        }

        $displayLabel = $fullName;
        if (!empty($row['company']) && stripos($fullName, $row['company']) === false) {
            $displayLabel .= ' (' . $row['company'] . ')';
        }

        $mainPhone = !empty($row['mobile']) ? $row['mobile'] : $row['phone'];
        
        $finalResponse[] = [
            'id' => (int)$row['id'],
            'type' => $row['source_type'],
            
            'label' => $displayLabel, 
            'value' => $fullName,    
            'sub_text' => $row['email'] ?: $mainPhone, 

            'full_data' => [
                'first_name' => $row['first_name'],
                'last_name'  => $row['last_name'],
                'company'    => $row['company'],
                'email'      => $row['email'],
                'phone'      => $mainPhone,
                'phone_sec'  => $row['phone'],
                'address'    => $row['street_address'],
                'city'       => $row['city'],
                'state'      => $row['state_province'],
                'zip'        => $row['zip_code']
            ]
        ];
    }
    
    echo json_encode(['success' => true, 'data' => $finalResponse]);

} catch (\PDOException $e) {
    error_log("Database Error in contact-search.php: " . $e->getMessage());
    http_response_code(500); 
    echo json_encode(['success' => false, 'error' => 'Error en la base de datos al buscar contactos']);
} catch (\Exception $e) {
    error_log("General Error in contact-search.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno del servidor']);
}