<?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'];
$billing = billing_fetch_or_init($pdo, $tenantId);

if ($billing['stripe_customer_id'] === null) {
    http_response_code(400);
    exit('Für diesen Mandanten gibt es noch keine Zahlungsmethode zu verwalten.');
}

$result = stripe_create_billing_portal_session($billing['stripe_customer_id'], saas_app_url('mandant-einstellungen.php'));

if (!$result['ok']) {
    http_response_code(502);
    exit('Das Kundenportal konnte nicht geöffnet werden: ' . saas_html((string)$result['error']));
}

app_audit_log($pdo, $tenantId, (int)$user['user_id'], 'billing.portal_opened', 'tenant', $tenantId);

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