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

// Leer JSON desde body
$input = json_decode(file_get_contents("php://input"), true);
$id = $input['id'] ?? null;
$slug = $input['slug_tienda'] ?? null;

if (!$slug) {
    echo json_encode(['success' => false, 'message' => '❌ Falta el parámetro slug_tienda']);
    exit;
}

if ($id) {
    $stmt = $mysqli->prepare("SELECT id, nombre_flujo, contenido, es_principal, ejecutor FROM flujos_chatbot WHERE id = ? AND slug_tienda = ? AND ejecutor = 'meta';");
    $stmt->bind_param("is", $id, $slug);
} else {
    $stmt = $mysqli->prepare("SELECT id, nombre_flujo, contenido, es_principal, ejecutor FROM flujos_chatbot WHERE slug_tienda = ? AND es_principal = 1 AND ejecutor = 'meta' ORDER BY id DESC LIMIT 1");
    $stmt->bind_param("s", $slug);
}

$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    $contenido = json_decode($row['contenido'], true);
    echo json_encode([
        'success' => true,
        'id' => $row['id'],
        'nombre' => $row['nombre_flujo'],
        'contenido' => $contenido,
        'es_principal' => (int)$row['es_principal'],
        'ejecutor' => $row['ejecutor'] ?? 'qr'  // ← nuevo campo agregado
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => '❌ Flujo no encontrado'
    ]);
}

$stmt->close();
