<?php
// ✅ Mostrar errores
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ✅ Encabezados CORS y JSON
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Max-Age: 86400");
header("Content-Type: application/json");

// ✅ Respuesta a preflight OPTIONS
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

$storeId = isset($_GET['store_id']) ? trim($_GET['store_id']) : null;

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

// ✅ Conexión a base de datos
require_once(__DIR__ . '/../config.php');

// ✅ Obtener configuración activa con endpoint
$stmt = $mysqli->prepare("
    SELECT 
        ns.id, 
        ns.store_id, 
        ns.tipo, 
        ns.numero_manual, 
        ns.endpoint,
        ns.activo, 
        us.token_api AS token_qr, 
        us.token_api_meta AS token_meta
    FROM numero_setup ns
    LEFT JOIN usuarios_tienda us 
        ON ns.store_id = us.slug_tienda
    WHERE ns.store_id = ? 
      AND (ns.activo = 1 OR (ns.numero_manual <> '' AND ns.numero_manual IS NOT NULL))
    LIMIT 1
");


$stmt->bind_param("s", $storeId);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();

if ($data) {
    echo json_encode(['success' => true, 'data' => $data]);
} else {
    echo json_encode(['success' => false, 'message' => '⚠️ No hay configuración activa de WhatsApp']);
}

$stmt->close();
$mysqli->close();
