<?php
// Captura la orden aprobada, VERIFICA monto/moneda/comprador y activa la licencia.
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/plugins.php';
require_once __DIR__ . '/../includes/paypal.php';
header('Content-Type: application/json');

if (!is_logged_in()) { http_response_code(401); echo json_encode(['error' => 'auth']); exit; }
csrf_check();
if (!paypal_enabled()) { http_response_code(503); echo json_encode(['error' => 'paypal_off']); exit; }

$u = current_user();
$slug    = $_POST['plugin'] ?? '';
$orderId = $_POST['orderID'] ?? '';
$plugin  = plugin_get($slug);

if (($_POST['agreed'] ?? '') !== '1') { http_response_code(400); echo json_encode(['error' => 'terms']); exit; }
if (!$plugin || (float)$plugin['price'] <= 0) { http_response_code(400); echo json_encode(['error' => 'bad_plugin']); exit; }
if (!preg_match('/^[A-Z0-9]{5,32}$/', $orderId)) { http_response_code(400); echo json_encode(['error' => 'bad_order']); exit; }

// Si ya la tiene, no capturamos de nuevo: devolvemos su licencia.
if (user_has_license((int)$u['id'], $slug)) {
    $st = db()->prepare("SELECT license_key FROM licenses WHERE user_id=? AND plugin_slug=? AND status='active' LIMIT 1");
    $st->execute([$u['id'], $slug]);
    echo json_encode(['ok' => true, 'license' => $st->fetchColumn(), 'already' => true]);
    exit;
}

[$code, $json] = paypal_capture_order($orderId);
if ($code !== 201 || ($json['status'] ?? '') !== 'COMPLETED') {
    http_response_code(502); echo json_encode(['error' => 'capture_failed']); exit;
}

$pu  = $json['purchase_units'][0] ?? [];
$cap = $pu['payments']['captures'][0] ?? [];
$amt = $cap['amount']['value'] ?? '';
$cur = $cap['amount']['currency_code'] ?? '';
$capId     = $cap['id'] ?? '';
$capStatus = $cap['status'] ?? '';
// custom_id puede venir a nivel de purchase_unit o de capture.
$custom = $pu['custom_id'] ?? ($cap['custom_id'] ?? '');

$expectedCustom = $u['id'] . ':' . $slug . ':premium';
$amountOk = number_format((float)$amt, 2, '.', '') === number_format((float)$plugin['price'], 2, '.', '');

if ($custom !== $expectedCustom || !$amountOk || $cur !== paypal_currency() || $capStatus !== 'COMPLETED') {
    http_response_code(400); echo json_encode(['error' => 'verify_failed']); exit;
}

// Evita registrar dos veces el mismo pago (auditoría).
if ($capId !== '') {
    $st = db()->prepare('SELECT 1 FROM orders WHERE paypal_txn=? LIMIT 1');
    $st->execute([$capId]);
    $dup = (bool)$st->fetchColumn();
} else { $dup = false; }

$key = activate_license((int)$u['id'], $slug, 'premium');

if (!$dup) {
    $payerEmail = $json['payer']['email_address'] ?? null;
    // Registro de aceptación de términos (prueba para disputas).
    $note = 'PayPal automático · Términos aceptados ' . gmdate('Y-m-d H:i:s') . ' UTC · IP ' . substr(client_ip(), 0, 45);
    $st = db()->prepare(
        'INSERT INTO orders (user_id, plugin_slug, edition, amount, paypal_email, paypal_txn, note, status, verified_at)
         VALUES (?, ?, "premium", ?, ?, ?, ?, "verified", NOW())'
    );
    $st->execute([$u['id'], $slug, $plugin['price'], $payerEmail, $capId, $note]);
}

echo json_encode(['ok' => true, 'license' => $key]);
