<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
header("Access-Control-Max-Age: 86400");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

require_once(__DIR__ . '/../config.php');

$input = json_decode(file_get_contents('php://input'), true);
$slug_tienda = trim($input['slug_tienda'] ?? '');
$busqueda    = trim($input['q'] ?? '');

if ($slug_tienda === '') {
    echo json_encode(['success' => false, 'message' => 'slug_tienda es obligatorio']);
    exit;
}

$params = [$slug_tienda];
$where  = "WHERE slug_tienda = ?";
if ($busqueda !== '') {
    $busc = "%" . $busqueda . "%";
    $where .= " AND (empresa LIKE ? OR ciudad LIKE ? OR email LIKE ?)";
    $params[] = $busc; $params[] = $busc; $params[] = $busc;
}

$sql = "SELECT id, slug_tienda, empresa, pais, direccion, direccion_2, codigo_postal, ciudad,
               contacto_nombre, email, tel_pais_iso, tel_codigo, tel_numero, estado,
               created_at, updated_at
        FROM proveedores
        $where
        ORDER BY created_at DESC
        LIMIT 200";

$stmt = $mysqli->prepare($sql);
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => 'Error prepare: ' . $mysqli->error]);
    exit;
}

$types = str_repeat('s', count($params));
$stmt->bind_param($types, ...$params);
$stmt->execute();
$res = $stmt->get_result();

$data = [];
while ($row = $res->fetch_assoc()) $data[] = $row;

$stmt->close();
$mysqli->close();

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