<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/StripeClient.php';
require_once __DIR__ . '/../includes/FreeTier.php';

dbnToolsRequireMethod('POST');
dbnToolsRequireAuth();

$user = dbnToolsAuthenticatedUser();
$userId = (int)($user['user_id'] ?? 0);
if ($userId <= 0) {
    dbnToolsError('User session missing user_id.', 401, 'bad_session');
}

$row = FreeTier::row($userId);
$customerId = (string)($row['stripe_customer_id'] ?? '');
if ($customerId === '') {
    // No Stripe customer yet — happens if user never checked out.
    dbnToolsError('No Stripe customer on record. Subscribe first.', 400, 'no_customer');
}

try {
    $stripe = new StripeClient();
    $baseUrl = (dbnToolsIsHttps() ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'tools.dobetternorge.no');
    $session = $stripe->createPortalSession($customerId, $baseUrl . '/billing.php');
    $url = (string)($session['url'] ?? '');
    if ($url === '') {
        dbnToolsError('Stripe did not return a portal URL.', 502, 'stripe_no_url');
    }
    dbnToolsRespond(['ok' => true, 'url' => $url]);
} catch (Throwable $e) {
    error_log('[stripe-portal] ' . $e->getMessage());
    dbnToolsError('Could not open billing portal: ' . $e->getMessage(), 500, 'stripe_failed');
}
