<?php
declare(strict_types=1);
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();
require_method(['POST']);
rate_limit('checkout', 10, 900);

$input = input_json();
$portalToken = trim((string) ($input['portal_token'] ?? ''));
if ($portalToken !== '') {
    $verifiedPortal = verify_signed_token($portalToken, 'portal');
    if (!$verifiedPortal) {
        json_response(['ok' => false, 'error' => 'Invalid or expired portal token'], 401);
    }
    $stmt = db()->prepare('SELECT * FROM devices WHERE id = ? LIMIT 1');
    $stmt->execute([$verifiedPortal['device_id']]);
    $device = $stmt->fetch();
    if (!$device) {
        json_response(['ok' => false, 'error' => 'Device not found'], 404);
    }
} else {
    $device = authenticate_device($input);
}
$stripe = config('stripe');
if (!function_exists('curl_init') || empty($stripe['secret_key']) || strpos((string) $stripe['secret_key'], 'CHANGE_ME') !== false) {
    json_response(['ok' => false, 'error' => 'Payment service is not configured'], 503);
}

$portal = portal_url($device);
$separator = strpos($portal, '?') === false ? '?' : '&';
$params = [
    'mode' => 'payment',
    'payment_method_types[0]' => 'card',
    'client_reference_id' => $device['mac'],
    'success_url' => $portal . $separator . 'payment=success&session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => $portal . $separator . 'payment=cancel',
    'line_items[0][quantity]' => 1,
    'line_items[0][price_data][currency]' => $stripe['currency'],
    'line_items[0][price_data][unit_amount]' => (int) $stripe['amount_cents'],
    'line_items[0][price_data][product_data][name]' => $stripe['product_name'],
    'metadata[mac]' => $device['mac'],
    'metadata[device_id]' => (string) $device['id'],
];

$ch = curl_init('https://api.stripe.com/v1/checkout/sessions');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => http_build_query($params),
    CURLOPT_USERPWD => $stripe['secret_key'] . ':',
    CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_TIMEOUT => 20,
]);
$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false || $status < 200 || $status >= 300) {
    error_log('[nexo] Stripe checkout failed with HTTP ' . $status);
    json_response(['ok' => false, 'error' => 'Payment service is temporarily unavailable'], 502);
}
$session = json_decode((string) $response, true);
if (empty($session['url']) || empty($session['id'])) {
    json_response(['ok' => false, 'error' => 'Invalid payment service response'], 502);
}
audit_log('payment.checkout_created', (int) $device['id'], ['session_id' => $session['id']]);
json_response(['ok' => true, 'checkout_url' => $session['url'], 'session_id' => $session['id']]);
