<?php
// ─── Payment Configuration ───────────────────────────────────────────────────
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
    header('HTTP/1.0 403 Forbidden', true, 403);
    exit;
}

// Create an app at https://developer.paypal.com/dashboard/applications to get these.
define('PAYPAL_MODE', 'sandbox'); // 'sandbox' or 'live'
define('PAYPAL_CLIENT_ID', 'PUT_YOUR_PAYPAL_CLIENT_ID_HERE');
define('PAYPAL_SECRET', 'PUT_YOUR_PAYPAL_SECRET_HERE');

// Manual BTC option — no automated on-chain verification, admin confirms and
// marks the invoice paid from the admin Invoices page.
define('BTC_WALLET_ADDRESS', 'PUT_YOUR_BTC_WALLET_ADDRESS_HERE');

function paypal_configured() {
    return PAYPAL_CLIENT_ID !== '' && PAYPAL_CLIENT_ID !== 'PUT_YOUR_PAYPAL_CLIENT_ID_HERE'
        && PAYPAL_SECRET !== '' && PAYPAL_SECRET !== 'PUT_YOUR_PAYPAL_SECRET_HERE';
}

function paypal_base_url() {
    return PAYPAL_MODE === 'live' ? 'https://api-m.paypal.com' : 'https://api-m.sandbox.paypal.com';
}

function paypal_get_access_token() {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL        => paypal_base_url() . '/v1/oauth2/token',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST       => true,
        CURLOPT_POSTFIELDS => 'grant_type=client_credentials',
        CURLOPT_USERPWD    => PAYPAL_CLIENT_ID . ':' . PAYPAL_SECRET,
        CURLOPT_HTTPHEADER => ['Accept: application/json'],
        CURLOPT_TIMEOUT    => 15,
    ]);
    $raw = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($raw, true);
    return $data['access_token'] ?? null;
}

function paypal_request($method, $path, $body = null) {
    $token = paypal_get_access_token();
    if (!$token) return ['ok' => false, 'message' => 'Could not authenticate with PayPal.'];

    $opts = [
        CURLOPT_URL            => paypal_base_url() . $path,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json', "Authorization: Bearer $token"],
    ];
    if ($method === 'POST') {
        $opts[CURLOPT_POST] = true;
        $opts[CURLOPT_POSTFIELDS] = $body !== null ? json_encode($body) : '';
    }

    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $raw = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($raw === false) return ['ok' => false, 'message' => "PayPal request failed: $err"];

    $data = json_decode($raw, true);
    if (isset($data['name']) && in_array($data['name'], ['UNPROCESSABLE_ENTITY', 'INVALID_REQUEST', 'RESOURCE_NOT_FOUND'])) {
        return ['ok' => false, 'message' => $data['message'] ?? 'PayPal request failed.', 'raw' => $data];
    }
    return ['ok' => true, 'data' => $data];
}

function paypal_create_order($amount, $currency = 'USD') {
    return paypal_request('POST', '/v2/checkout/orders', [
        'intent' => 'CAPTURE',
        'purchase_units' => [[ 'amount' => [ 'currency_code' => $currency, 'value' => number_format($amount, 2, '.', '') ] ]],
    ]);
}

function paypal_capture_order($orderId) {
    return paypal_request('POST', "/v2/checkout/orders/$orderId/capture");
}
