<?php
// db/search-contacts.php

// 1. Configuración de seguridad para no romper el JSON con errores de texto
ini_set('display_errors', 0); 
error_reporting(E_ALL);
header('Content-Type: application/json; charset=utf-8');

// 2. Conexión a Base de Datos Centralizada
require_once __DIR__ . '/../core/api.php';

// Verificar que la variable $pdo se haya cargado correctamente (asumiendo que api.php la define)
if (!isset($pdo)) {
    echo json_encode(['status' => 'error', 'message' => 'Error: La variable $pdo no está definida en la conexión.']);
    exit;
}

$query = $_GET['q'] ?? '';
$type = $_GET['type'] ?? 'client';

// Si es muy corto, devolvemos vacío
if (strlen(trim($query)) < 2) {
    echo json_encode(['status' => 'success', 'data' => []]);
    exit;
}

$searchResults = [];

try {
    $searchTerm = "%" . trim($query) . "%";

    if ($type === 'client') {
        // Buscamos en Clientes
        $sql = "SELECT id, first_name, last_name, email, phone, mobile, 
                CONCAT(first_name, ' ', last_name) as full_name 
                FROM clients 
                WHERE CONCAT(first_name, ' ', last_name) LIKE :q 
                OR email LIKE :q 
                OR phone LIKE :q 
                OR mobile LIKE :q
                LIMIT 15";
    } else {
        // Búsqueda para Leads (Prospectos)
        $sql = "SELECT id, first_name, last_name, company, email, phone, mobile, 
                CONCAT(first_name, ' ', last_name) as full_name 
                FROM leads 
                WHERE CONCAT(first_name, ' ', last_name) LIKE :q 
                OR company LIKE :q 
                OR email LIKE :q 
                LIMIT 15";
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute(['q' => $searchTerm]);
    
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Preferir teléfono fijo, si no hay, usar móvil
        $phone = !empty($row['phone']) ? $row['phone'] : (!empty($row['mobile']) ? $row['mobile'] : '');
        
        $searchResults[] = [
            'id' => $row['id'],
            'name' => $row['full_name'] . (isset($row['company']) && $row['company'] ? ' (' . $row['company'] . ')' : ''),
            'email' => $row['email'],
            'phone' => $phone
        ];
    }

    echo json_encode(['status' => 'success', 'data' => $searchResults]);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => 'Error SQL: ' . $e->getMessage()]);
}
?>