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

// CORS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    http_response_code(200);
    exit;
}

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

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

$input = json_decode(file_get_contents("php://input"), true);
$id = $input['id'] ?? null;
$slug = $input['slug_tienda'] ?? null;
$nuevo_nombre = trim($input['nuevo_nombre'] ?? '');

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

// Verificar duplicado
$check = $mysqli->prepare("SELECT COUNT(*) FROM flujos_chatbot WHERE slug_tienda = ? AND nombre_flujo = ? AND id != ?");
$check->bind_param("ssi", $slug, $nuevo_nombre, $id);
$check->execute();
$check->bind_result($count);
$check->fetch();
$check->close();

if ($count > 0) {
    echo json_encode(['success' => false, 'message' => '❌ Ya existe un flujo con ese nombre']);
    exit;
}


$stmt = $mysqli->prepare("UPDATE flujos_chatbot SET nombre_flujo = ? WHERE id = ? AND slug_tienda = ?");
$stmt->bind_param("sis", $nuevo_nombre, $id, $slug);
if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => '✅ Nombre actualizado']);
} else {
    echo json_encode(['success' => false, 'message' => '❌ No se pudo actualizar']);
}
$stmt->close();
