<?php

require_once __DIR__ . '/functions.php';
require_once __DIR__ . '/app/billing.php';
require_once __DIR__ . '/app/audit.php';
require_once __DIR__ . '/app/saas-mail.php';

$pdo = app_db_pdo();
$user = saas_require_login();

if (!saas_can_manage_tenant_settings($user)) {
    http_response_code(403);
    exit('Kein Zugriff.');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: mandant-einstellungen.php');
    exit;
}

app_require_csrf();

$tenantId = (int)$user['tenant_id'];
$planCode = (string)($_POST['plan_code'] ?? '');
$plans = billing_plans();

if (!isset($plans[$planCode]) || $plans[$planCode]['stripe_lookup_key'] === null) {
    http_response_code(400);
    exit('Ungültiger Tarif.');
}

$priceId = billing_stripe_price_id($planCode);
if ($priceId === null) {
    http_response_code(502);
    exit('Der Tarif ist bei Stripe aktuell nicht verfügbar. Bitte später erneut versuchen.');
}

$billing = billing_fetch_or_init($pdo, $tenantId);
$baseUrl = saas_app_url('mandant-einstellungen.php');

$result = stripe_create_checkout_session(
    $priceId,
    (string)$user['email'],
    $billing['stripe_customer_id'],
    $baseUrl . '?upgrade=success',
    $baseUrl . '?upgrade=cancelled',
    ['tenant_id' => $tenantId, 'plan_code' => $planCode]
);

if (!$result['ok']) {
    app_audit_log($pdo, $tenantId, (int)$user['user_id'], 'billing.checkout_failed', 'tenant', $tenantId, ['plan_code' => $planCode, 'error' => $result['error']]);
    http_response_code(502);
    exit('Der Bezahlvorgang konnte nicht gestartet werden: ' . saas_html((string)$result['error']));
}

app_audit_log($pdo, $tenantId, (int)$user['user_id'], 'billing.checkout_started', 'tenant', $tenantId, ['plan_code' => $planCode]);

header('Location: ' . $result['url']);
exit;
