<?php
// ✅ Mostrar errores
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

// Leer datos JSON
$input = json_decode(file_get_contents("php://input"), true);
$slug = $input['slug'] ?? '';
$numero = $input['numero'] ?? '';

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

// Conexión
require_once(__DIR__ . '/../config.php');
$mysqli->set_charset("utf8");

if ($mysqli->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Error de conexión']);
    exit;
}

// Consulta
$sql = "SELECT id, nota, fecha FROM notas_contactos WHERE slug_tienda = ? AND telefono = ? ORDER BY fecha DESC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("ss", $slug, $numero);
$stmt->execute();

$resultado = $stmt->get_result();

$notas = [];
while ($row = $resultado->fetch_assoc()) {
    $notas[] = [
        'id' => $row['id'],
        'nota' => $row['nota'],
        'fecha' => $row['fecha']
    ];
}

echo json_encode(['success' => true, 'notas' => $notas]);
$mysqli->close();
