<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/billing.php';
require_once __DIR__ . '/kyc_helpers.php';

$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
$db = getDatabaseConnection();
requireKycVerified($db, $user['id']);

$plan = getPlanByCode($_GET['plan'] ?? null);
 
$accessToken = getenv('MP_ACCESS_TOKEN');
if (!$accessToken) {
    http_response_code(500);
    echo 'Mercado Pago no está configurado. Falta MP_ACCESS_TOKEN en .env';
    exit;
}
 
function mpRequest($method, $path, $payload = null) {
    $token = getenv('MP_ACCESS_TOKEN');
    $url = 'https://api.mercadopago.com' . $path;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
    $headers = [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json'
    ];
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    }
    $resp = curl_exec($ch);
    if ($resp === false) {
        $err = curl_error($ch);
        curl_close($ch);
        throw new Exception('MP request failed: ' . $err);
    }
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $data = json_decode($resp, true);
    if ($status >= 400) {
        $msg = isset($data['message']) ? $data['message'] : ('HTTP ' . $status);
        throw new Exception('Mercado Pago API error: ' . $msg);
    }
    return $data;
}

try {
    $reason    = getenv('MP_REASON') ?: ('Suscripción ' . $plan['name']);
    $amount    = (float)($plan['mp_amount'] ?? 0);
    if ($amount <= 0) {
        $amount = floatval(getenv('MP_PLAN_AMOUNT') ?: '15000');
    }
    $currency  = getenv('MP_PLAN_CURRENCY') ?: 'COP';
    $freq      = intval($plan['mp_frequency'] ?? (getenv('MP_PLAN_FREQUENCY') ?: 1));
    $freqType  = $plan['mp_frequency_type'] ?? (getenv('MP_PLAN_FREQUENCY_TYPE') ?: 'months');

    $success = rtrim(getenv('BASE_URL') ?: '', '/') . '/subscription?message=' . urlencode('Suscripción autorizada. Actualizando...');
    $payload = [
        'payer_email' => $user['email'],
        'back_url' => $success ?: (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '/subscription'),
        'reason' => $reason,
        'auto_recurring' => [
            'frequency' => $freq,
            'frequency_type' => $freqType,
            'transaction_amount' => $amount,
            'currency_id' => $currency
        ],
        // Mapea la suscripción al user id y plan
        'external_reference' => $user['id'] . '|' . $plan['code']
    ];

    $preapproval = mpRequest('POST', '/preapproval', $payload);
    if (!empty($preapproval['init_point'])) {
        header('Location: ' . $preapproval['init_point']);
        exit;
    }
    throw new Exception('Respuesta inválida de Mercado Pago');
} catch (Throwable $e) {
    error_log('MP Preapproval error: ' . $e->getMessage());
    http_response_code(500);
    echo 'No se pudo crear la suscripción en Mercado Pago.';
}
