<?php
// -----------------------------
// ✅ CONFIGURACIÓN CORS GLOBAL
// -----------------------------
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Max-Age: 86400"); // cache de preflight
} else {
    header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header("Content-Type: application/json");

// -----------------------------
// ✅ RESPUESTA A PETICIÓN OPTIONS (preflight)
// -----------------------------
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit(0);
}

// -----------------------------
// 🔐 TOKEN DE ACCESO A META
// -----------------------------
$access_token = 'EAARmH62CC6cBPOlZCejMaOwSo83yW5P3JpxAMMrXIXzmOX7JzvF9lqU8Jl9fckXLfk2KZCHFgOIoQWYvf2DnxCLEP4YeC2JNDFKIWNbAZBYf7KcsatI65FAi1aI3xnpOHwbDSnrACZC46fZB5GGCKGc4KxpClZBdpFTg3bCXx2U2ZCjg7uhYp1JvqJ4T9MY8AZDZD';

// -----------------------------
// ❌ Validación de media_id
// -----------------------------
if (!isset($_GET['media_id'])) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'missing_media_id',
        'message' => 'No se proporcionó media_id'
    ]);
    exit();
}

$media_id = $_GET['media_id'];

// -----------------------------
// 📡 Consulta a Meta API
// -----------------------------
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v19.0/{$media_id}?fields=status");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $access_token]);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// -----------------------------
// 📦 Procesar respuesta
// -----------------------------
$data = json_decode($response, true);

if ($httpcode >= 200 && $httpcode < 300 && isset($data['status'])) {
    echo json_encode([
        'success' => true,
        'media_id' => $media_id,
        'status' => $data['status']
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $data['error']['message'] ?? 'No se pudo obtener estado del media',
        'debug' => $data
    ]);
}
