<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Credenciales y configuración
$access_token = '...';
$waba_phone_id = '...';

// Asegúrate de que 'uploads/' esté dentro del directorio público
$uploadDir = __DIR__ . '/uploads/';
$publicBaseUrl = 'https://server40.vps.webdock.cloud/api_gold/uploads/';

if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
    chown($uploadDir, 'www-data');
    chgrp($uploadDir, 'www-data');
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Archivo no recibido o con error']);
    exit;
}

$tmp = $_FILES['file']['tmp_name'];
$filename = 'img_' . uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$localPath = $uploadDir . $filename;
$urlPublica = $publicBaseUrl . $filename;

if (!move_uploaded_file($tmp, $localPath)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Falló al mover archivo al servidor']);
    exit;
}

// Enviar media a WhatsApp Cloud API
$ch = curl_init("https://graph.facebook.com/v19.0/{$waba_phone_id}/media");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => ["Authorization: Bearer $access_token"],
    CURLOPT_POSTFIELDS => [
        'messaging_product' => 'whatsapp',
        'file' => new CURLFile($localPath, mime_content_type($localPath)),
        'type' => mime_content_type($localPath)
    ]
]);

$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($response, true);

if ($code === 200 && isset($result['id'])) {
    echo json_encode([
        'success' => true,
        'media_id' => $result['id'],
        'url' => $urlPublica,
        'file' => $filename
    ]);
} else {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Error al subir a Meta',
        'meta_response' => $result
    ]);
}
