<?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: POST, 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;
}

// ✅ Leer JSON
$input = json_decode(file_get_contents('php://input'), true);
$slug = isset($input['slug_tienda']) ? trim($input['slug_tienda']) : null;

if (!$slug) {
    echo json_encode(['success' => false, 'message' => '❌ Falta el slug de la tienda']);
    exit;
}

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

// ✅ Consultar token
$stmt = $mysqli->prepare("SELECT token_api FROM usuarios_tienda WHERE slug_tienda = ?");
$stmt->bind_param("s", $slug);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) {
    echo json_encode([
        'success' => true,
        'token_api' => $row['token_api']
    ], JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(['success' => false, 'message' => '❌ No se encontró la tienda']);
}

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