<?php
require_once 'paypal_client.php';

$input = json_decode(file_get_contents('php://input'), true);

try {
    if (!isset($input['orderID'])) {
        throw new Exception("orderID no proporcionado");
    }

    $orderID = $input['orderID'];

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

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $BASE_URL . '/v2/checkout/orders/' . $orderID . '/capture');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    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()]);
}
