<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';

require_login();

header('Content-Type: application/json');

$q = isset($_GET['q']) ? trim($_GET['q']) : '';

if (mb_strlen($q) < 2) {
    echo json_encode(array());
    exit;
}

$pdo = db();

try {
    // Buscamos coincidencias en Nombre o SKU
    $stmt = $pdo->prepare("
        SELECT id, name, sku, price, description, unit 
        FROM products 
        WHERE is_active = 1 
          AND (name LIKE ? OR sku LIKE ? OR REPLACE(REPLACE(sku, '.', ''), '-', '') LIKE ?) 
        ORDER BY name ASC 
        LIMIT 20
    ");
    
    $searchTerm = '%' . $q . '%';
    $compactSkuTerm = '%' . preg_replace('/[^A-Za-z0-9]/', '', $q) . '%';
    $stmt->execute(array($searchTerm, $searchTerm, $compactSkuTerm));
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted = array();
    foreach ($results as $row) {
        $formatted[] = array(
            'id'    => (int)$row['id'], // Ahora usamos el ID local
            'name'  => $row['name'],
            'sku'   => !empty($row['sku']) ? $row['sku'] : 'S/S',
            'price' => (float)$row['price'],
            'unit'  => !empty($row['unit']) ? $row['unit'] : 'unidad'
        );
    }

    echo json_encode($formatted);

} catch (Throwable $e) {
    // Si hay error devolvemos array vac��o para no romper el JS
    echo json_encode(array());
}