<?php
// Cargar configuración central
require_once __DIR__ . '/config.php';

// Obtener la URL base según el entorno
$BASE_URL = PAYPAL_ENV === 'sandbox' ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';

/**
 * Genera un Access Token usando las credenciales definidas en config.php
 */
function generateAccessToken() {
    global $BASE_URL;

    $auth = base64_encode(PAYPAL_CLIENT_ID . ':' . PAYPAL_CLIENT_SECRET);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $BASE_URL . '/v1/oauth2/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Basic ' . $auth,
        'Content-Type: application/x-www-form-urlencoded'
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200) {
        error_log("Failed to generate Access Token: " . $response);
        return null;
    }

    $data = json_decode($response, true);
    return $data['access_token'];
}

/**
 * Maneja la respuesta de la API y la devuelve al frontend
 */
function handleResponse($response, $httpCode) {
    http_response_code($httpCode);
    header('Content-Type: application/json');
    echo $response;
    exit;
}
