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

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

// Leer slug_tienda desde JSON o POST clásico
$input = json_decode(file_get_contents("php://input"), true);
$slug_tienda = $input['slug_tienda'] 
    ?? $_POST['slug_tienda'] 
    ?? $_GET['slug_tienda'] 
    ?? null;

if (!$slug_tienda) {
    echo json_encode(['success' => false, 'message' => 'Falta slug_tienda']);
    exit;
}

$stmt = $mysqli->prepare("
    SELECT id, nombre_flujo, ejecutor, es_principal 
    FROM flujos_chatbot 
    WHERE slug_tienda = ?
");
$stmt->bind_param("s", $slug_tienda);
$stmt->execute();
$result = $stmt->get_result();

$flujos = [];
while ($row = $result->fetch_assoc()) {
    $flujos[] = $row;
}

echo json_encode(['success' => true, 'flujos' => $flujos]);
