<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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 = $input['slug'] ?? null;
$telefono = $input['numero'] ?? null;

if (!$slug || !$telefono) {
    echo json_encode(['success' => false, 'message' => 'Faltan parámetros']);
    exit;
}

$stmt = $mysqli->prepare("SELECT id, etiqueta, fecha FROM etiquetas_contacto WHERE slug_tienda = ? AND telefono = ? ORDER BY fecha DESC");
$stmt->bind_param("ss", $slug, $telefono);
$stmt->execute();
$result = $stmt->get_result();

$etiquetas = [];
while ($row = $result->fetch_assoc()) {
    $etiquetas[] = $row;
}

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

$stmt->close();
