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

// ✅ Obtener parámetro de tienda
$slug = isset($_GET['slug_tienda']) ? trim($_GET['slug_tienda']) : null;

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

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

// ✅ Consulta para obtener phone_id y access_token
$stmt = $mysqli->prepare("
    SELECT phone_id, access_token
    FROM waba_config
    WHERE slug_tienda = ?
    LIMIT 1
");
$stmt->bind_param("s", $slug);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();

if ($data) {
    echo json_encode([
        'success' => true,
        'data' => [
            'phone_id' => $data['phone_id'],
            'access_token' => $data['access_token']
        ]
    ]);
} else {
    echo json_encode(['success' => false, 'message' => '⚠️ No se encontró configuración para esta tienda']);
}

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