<?php
header('Content-Type: application/json');
require_once __DIR__ . '/paypal_config.php';

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
$authId = $data['authorization_id'] ?? null;

if (!$authId) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing authorization_id']);
    exit;
}

$mode = (get_paypal_mode() === 'live') ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com';
$clientId = get_paypal_client_id();
$secret = isset($paypal_secret) ? $paypal_secret : '';

if (!$clientId || !$secret) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'PayPal credentials not configured']);
    exit;
}

// Get access token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mode . '/v1/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $clientId . ':' . $secret);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'Accept-Language: en_US'
]);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo json_encode(['success' => false, 'message' => 'Error fetching PayPal token']);
    curl_close($ch);
    exit;
}
curl_close($ch);

$tokenData = json_decode($result, true);
if (!isset($tokenData['access_token'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid PayPal token response', 'raw' => $tokenData]);
    exit;
}

$accessToken = $tokenData['access_token'];

// Fetch authorization details
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mode . '/v2/payments/authorizations/' . urlencode($authId));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $accessToken
]);
$res = curl_exec($ch);
if (curl_errno($ch)) {
    echo json_encode(['success' => false, 'message' => 'Error fetching authorization']);
    curl_close($ch);
    exit;
}
curl_close($ch);

$auth = json_decode($res, true);
if (isset($auth['id'])) {
    $status = strtoupper($auth['status'] ?? '') ;
    // Accept AUTHORIZED or COMPLETED as verification
    if ($status === 'AUTHORIZED' || $status === 'COMPLETED') {
        echo json_encode(['success' => true, 'status' => $status, 'authorization' => $auth]);
    } else {
        http_response_code(422);
        echo json_encode(['success' => false, 'status' => $status, 'message' => 'Authorization not in expected state', 'authorization' => $auth]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Could not fetch authorization', 'raw' => $auth]);
}

?>
