<?php
declare(strict_types=1);

namespace App\Services;

use App\Config\Config;

class MercadoPagoService
{
    public static function createSubscription(int $tenantId, int $planId, float $amount, string $externalRef): array
    {
        $token = \App\Services\SettingsService::get('mercadopago.access_token', Config::get('mercadopago.access_token'));
        $body = ['external_reference' => $externalRef, 'auto_recurring' => ['transaction_amount' => $amount, 'currency_id' => 'BRL']];
        $ch = curl_init('https://api.mercadopago.com/preapproval');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $token, 'Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $resp = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ['status' => (int)$status, 'body' => $resp ? json_decode($resp, true) : []];
    }
}
