<?php
// CORS y headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");
date_default_timezone_set('America/Bogota');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

// Conexión
require_once(__DIR__ . '/../config.php');
$mysqli->set_charset("utf8mb4");

// Leer slug de query
$slug = isset($_GET['slug']) ? trim($_GET['slug']) : '';
if ($slug === '') {
    echo json_encode(['success'=>false,'message'=>'Falta parámetro: slug']); 
    exit;
}

$stmt = $mysqli->prepare("
    SELECT 
        id,
        phone_id,
        access_token,
        slug_tienda,
        token_webhook,
        business_id,
        id_app
    FROM waba_config 
    WHERE slug_tienda = ? 
    LIMIT 1
");
if (!$stmt) { 
    echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); 
    exit; 
}
$stmt->bind_param("s", $slug);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

if ($row) {
    // Asegurar claves aunque vengan NULL
    $row['business_id'] = $row['business_id'] ?? '';
    $row['id_app']      = $row['id_app'] ?? '';
    echo json_encode(['success'=>true,'data'=>$row]);
} else {
    echo json_encode(['success'=>true,'data'=>null,'message'=>'Sin configuración para este slug']);
}
