<?php
// obtener_info_twilio.php

// === CORS y headers ===
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Content-Type: application/json; charset=utf-8");
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");

// === Tomar slug (acepta ?slug= o ?slug_tienda=) ===
$slug = '';
if (!empty($_GET['slug'])) {
    $slug = trim($_GET['slug']);
} elseif (!empty($_GET['slug_tienda'])) {
    $slug = trim($_GET['slug_tienda']);
}

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

// === Query segura ===
$stmt = $mysqli->prepare("SELECT slug_tienda, account_sid, auth_token, from_whatsapp 
                            FROM twilio_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();

// === Respuesta ===
if (!$row) {
    echo json_encode([
        'success' => true,
        'data'    => null  // coherente con lo que espera tu Node
    ]);
    exit;
}

// Validación mínima
if (empty($row['account_sid']) || empty($row['auth_token']) || empty($row['from_whatsapp'])) {
    echo json_encode([
        'success' => true,
        'data'    => null,
        'message' => 'Registro incompleto'
    ]);
    exit;
}

echo json_encode([
    'success' => true,
    'data'    => [
        'account_sid'   => $row['account_sid'],
        'auth_token'    => $row['auth_token'],
        'from_whatsapp' => $row['from_whatsapp']
    ]
]);
