<?php
require_once 'paypal_client.php';

// Leer datos del body
$input = json_decode(file_get_contents('php://input'), true);

try {
    $accessToken = generateAccessToken();
    if (!$accessToken) {
        throw new Exception("Error obteniendo el Access Token");
    }

    // Obtener datos dinámicos del carrito
    $cartItem = $input['cart'][0];
    $name = isset($cartItem['name']) ? $cartItem['name'] : 'Zenith Premium Tier';
    $subtotal = isset($cartItem['subtotal']) ? $cartItem['subtotal'] : '4000.00';
    $comision = isset($cartItem['comision']) ? $cartItem['comision'] : '50.00';
    $impuesto = isset($cartItem['impuesto']) ? $cartItem['impuesto'] : '200.00';
    $total = isset($cartItem['total']) ? $cartItem['total'] : '4250.00';

    $payload = [
        "intent" => "CAPTURE",
        "purchase_units" => [
            [
                "description" => $name . " - Pago Seguro",
                "amount" => [
                    "currency_code" => "USD",
                    "value" => $total,
                    "breakdown" => [
                        "item_total" => ["currency_code" => "USD", "value" => $subtotal],
                        "tax_total"  => ["currency_code" => "USD", "value" => $impuesto],
                        "handling"   => ["currency_code" => "USD", "value" => $comision]
                    ]
                ],
                "items" => [
                    [
                        "name" => $name,
                        "description" => "Suscripción / Entrada",
                        "unit_amount" => ["currency_code" => "USD", "value" => $subtotal],
                        "quantity" => "1",
                        "category" => "DIGITAL_GOODS"
                    ]
                ]
            ]
        ]
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $BASE_URL . '/v2/checkout/orders');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json'
    ]);

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

    handleResponse($response, $httpCode);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => $e->getMessage()]);
}
