<?php
// ============================================================
// Integración PayPal (Smart Buttons + Orders v2, verificación server-side).
// El pago se crea Y se captura en el servidor: el cliente no puede falsear el monto.
// ============================================================
if (!defined('APP_LOADED')) { http_response_code(403); exit('No autorizado.'); }

function paypal_enabled(): bool {
    return defined('PAYPAL_CLIENT_ID') && PAYPAL_CLIENT_ID !== ''
        && defined('PAYPAL_SECRET') && PAYPAL_SECRET !== '';
}

function paypal_api_base(): string {
    return (defined('PAYPAL_ENV') && PAYPAL_ENV === 'live')
        ? 'https://api-m.paypal.com'
        : 'https://api-m.sandbox.paypal.com';
}

function paypal_currency(): string {
    return defined('PAYPAL_CURRENCY') ? PAYPAL_CURRENCY : 'USD';
}

// Petición cURL genérica. Devuelve [httpCode, arrayJson].
function paypal_request(string $method, string $path, array $headers = [], ?string $body = null): array {
    $ch = curl_init(paypal_api_base() . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    $resp = curl_exec($ch);
    $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    if ($resp === false) return [0, ['error' => $err]];
    $json = json_decode($resp, true);
    return [$code, is_array($json) ? $json : []];
}

// Token OAuth2 (client_credentials), cacheado durante la request.
function paypal_token(): ?string {
    static $tok = null;
    if ($tok !== null) return $tok ?: null;
    $auth = base64_encode(PAYPAL_CLIENT_ID . ':' . PAYPAL_SECRET);
    [$code, $json] = paypal_request('POST', '/v1/oauth2/token', [
        'Authorization: Basic ' . $auth,
        'Content-Type: application/x-www-form-urlencoded',
    ], 'grant_type=client_credentials');
    $tok = ($code === 200 && !empty($json['access_token'])) ? $json['access_token'] : '';
    return $tok ?: null;
}

// Crea una orden CAPTURE. custom_id = "userId:slug:edition" para verificarlo al capturar.
function paypal_create_order(int $userId, string $slug, string $edition, string $amount): array {
    $token = paypal_token();
    if (!$token) return [0, ['error' => 'no_token']];
    $p = function_exists('plugin_get') ? plugin_get($slug) : null;
    $name = $p['name'] ?? $slug;
    $payload = json_encode([
        'intent' => 'CAPTURE',
        'purchase_units' => [[
            'custom_id'   => $userId . ':' . $slug . ':' . $edition,
            'description' => substr($name . ' ' . ucfirst($edition), 0, 127),
            'amount' => [
                'currency_code' => paypal_currency(),
                'value'         => number_format((float)$amount, 2, '.', ''),
            ],
        ]],
        'application_context' => [
            'brand_name'          => 'infinity3113',
            'shipping_preference' => 'NO_SHIPPING',
            'user_action'         => 'PAY_NOW',
        ],
    ]);
    return paypal_request('POST', '/v2/checkout/orders', [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ], $payload);
}

// Captura una orden ya aprobada por el comprador.
function paypal_capture_order(string $orderId): array {
    $token = paypal_token();
    if (!$token) return [0, ['error' => 'no_token']];
    return paypal_request('POST', '/v2/checkout/orders/' . rawurlencode($orderId) . '/capture', [
        'Authorization: Bearer ' . $token,
        'Content-Type: application/json',
    ], '{}');
}

// Activa (o devuelve) la licencia del usuario para el plugin. Idempotente.
function activate_license(int $userId, string $slug, string $edition = 'premium'): string {
    $st = db()->prepare("SELECT license_key FROM licenses WHERE user_id=? AND plugin_slug=? AND status='active' LIMIT 1");
    $st->execute([$userId, $slug]);
    $existing = $st->fetchColumn();
    if ($existing) return $existing;
    do {
        $key = gen_license_key($slug);
        $c = db()->prepare('SELECT 1 FROM licenses WHERE license_key=?');
        $c->execute([$key]);
    } while ($c->fetchColumn());
    $ins = db()->prepare(
        'INSERT INTO licenses (user_id, plugin_slug, edition, license_key, status, activated_by)
         VALUES (?, ?, ?, ?, "active", NULL)'
    );
    $ins->execute([$userId, $slug, $edition, $key]);
    return $key;
}
