<?php
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();

global $config;
$input = input_json();
$device = get_or_create_device($input['mac'] ?? '');

$stripe = $config['stripe'];
if (strpos($stripe['secret_key'], 'CHANGE_ME') !== false) {
    json_response(['ok' => false, 'error' => 'Stripe secret key is not configured'], 500);
}

$successUrl = absolute_url('dashboard.php?mac=' . rawurlencode($device['mac']) . '&payment=success');
$cancelUrl = absolute_url('dashboard.php?mac=' . rawurlencode($device['mac']) . '&payment=cancel');

$params = [
    'mode' => 'payment',
    'client_reference_id' => $device['mac'],
    'success_url' => $successUrl,
    'cancel_url' => $cancelUrl,
    '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'],
];

$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'],
]);

$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($response === false || $status < 200 || $status >= 300) {
    json_response(['ok' => false, 'error' => $curlError ?: 'Stripe API error', 'stripe_status' => $status, 'stripe_response' => $response], 502);
}

$session = json_decode($response, true);
json_response(['ok' => true, 'checkout_url' => $session['url'] ?? null, 'session_id' => $session['id'] ?? null]);
