<?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;

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

// Obtener flujo original
$stmt = $mysqli->prepare("SELECT nombre_flujo, contenido FROM flujos_chatbot WHERE id = ? AND slug_tienda = ?");
$stmt->bind_param("is", $id, $slug);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    $nuevo_nombre = $row['nombre_flujo'] . ' (Clonado)';
    $contenido = $row['contenido'];


    $insert = $mysqli->prepare("INSERT INTO flujos_chatbot (slug_tienda, nombre_flujo, contenido, es_principal) VALUES (?, ?, ?, 0)");
    $insert->bind_param("sss", $slug, $nuevo_nombre, $contenido);
    if ($insert->execute()) {
        echo json_encode(['success' => true, 'message' => '✅ Flujo clonado con éxito']);
    } else {
        echo json_encode(['success' => false, 'message' => '❌ No se pudo clonar']);
    }
    $insert->close();
} else {
    echo json_encode(['success' => false, 'message' => '❌ Flujo original no encontrado']);
}

$stmt->close();
