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

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

if (!$slug || !$id) {
    echo json_encode(['success' => false, 'message' => 'Datos incompletos']);
    exit;
}

// 🔍 Obtener el ejecutor del flujo a activar
$stmt = $mysqli->prepare("SELECT ejecutor 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()) {
    echo json_encode(['success' => false, 'message' => 'Flujo no encontrado']);
    exit;
}

$ejecutor = $row['ejecutor'];
$stmt->close();

// 🚫 Desactivar todos los flujos con el mismo ejecutor
$stmt1 = $mysqli->prepare("UPDATE flujos_chatbot SET es_principal = 0 WHERE slug_tienda = ? AND ejecutor = ?");
$stmt1->bind_param("ss", $slug, $ejecutor);
$stmt1->execute();
$stmt1->close();

// ✅ Activar el flujo seleccionado
$stmt2 = $mysqli->prepare("UPDATE flujos_chatbot SET es_principal = 1 WHERE id = ? AND slug_tienda = ?");
$stmt2->bind_param("is", $id, $slug);
$stmt2->execute();
$stmt2->close();

echo json_encode(['success' => true, 'message' => '✅ Flujo activado correctamente']);
