<?php
// CORS completo
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;
}

date_default_timezone_set('America/Bogota');
require_once(__DIR__ . '/../config.php');

$input = json_decode(file_get_contents("php://input"), true);

$slug = $input['slug'] ?? null;
$telefono = $input['numero'] ?? null;
$nota = $input['nota'] ?? null;

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

// Insertar siempre una nueva nota (registro histórico)
$stmt = $mysqli->prepare("INSERT INTO notas_contactos (slug_tienda, telefono, nota, fecha) VALUES (?, ?, ?, NOW())");
$stmt->bind_param("sss", $slug, $telefono, $nota);
$success = $stmt->execute();

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Nota registrada correctamente']);
} else {
    echo json_encode(['success' => false, 'message' => 'Error al insertar nota: ' . $stmt->error]);
}

$stmt->close();
