<?php
header('Content-Type: application/json');

// Simple PayPal order creation for verification (uses AUTHORIZE intent)
// Requires auth-system/paypal_config.php to be configured with client id/secret
require_once __DIR__ . '/paypal_config.php';

$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) {
    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'];

// Create an order with intent AUTHORIZE for a small amount (sandbox verification)
$payload = [
    'intent' => 'AUTHORIZE',
    'purchase_units' => [[
        'amount' => [
            'currency_code' => 'INR',
            'value' => '1.00'
        ]
    ]]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $mode . '/v2/checkout/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
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 creating PayPal order']);
    curl_close($ch);
    exit;
}
curl_close($ch);

$order = json_decode($res, true);
if (isset($order['id'])) {
    echo json_encode(['success' => true, 'orderID' => $order['id'], 'order' => $order]);
} else {
    echo json_encode(['success' => false, 'message' => 'Could not create PayPal order', 'raw' => $order]);
}

?>
