<?php
// Crea una orden de PayPal en el servidor (monto tomado del manifiesto, no del cliente).
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; }

if (($_POST['agreed'] ?? '') !== '1') { http_response_code(400); echo json_encode(['error' => 'terms']); exit; }

$u = current_user();
$slug = $_POST['plugin'] ?? '';
$plugin = plugin_get($slug);
if (!$plugin || (float)$plugin['price'] <= 0) {
    http_response_code(400); echo json_encode(['error' => 'bad_plugin']); exit;
}
if (user_has_license((int)$u['id'], $slug)) {
    http_response_code(409); echo json_encode(['error' => 'owned']); exit;
}

[$code, $json] = paypal_create_order((int)$u['id'], $slug, 'premium', $plugin['price']);
if ($code === 201 && !empty($json['id'])) {
    echo json_encode(['id' => $json['id']]);
} else {
    http_response_code(502);
    echo json_encode(['error' => 'create_failed']);
}
