<?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, tax_treatment, tax_rate, dte_unit_code, default_income_center_id, export_name, export_description 
        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',
            'description' => $row['description'] ?? '',
            'tax_treatment' => $row['tax_treatment'] ?? 'afecto',
            'tax_rate' => isset($row['tax_rate']) ? (float)$row['tax_rate'] : 19,
            'dte_unit_code' => $row['dte_unit_code'] ?? '',
            'default_income_center_id' => isset($row['default_income_center_id']) ? (int)$row['default_income_center_id'] : null,
            'export_name' => $row['export_name'] ?? '',
            'export_description' => $row['export_description'] ?? ''
        );
    }

    echo json_encode($formatted);

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