<?php

declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');

require_once __DIR__ . '/../session_guards.php';
require_once __DIR__ . '/cpanel_addon_lib.php';

if (ob_get_level() > 0) {
    ob_end_clean();
}

header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
ignore_user_abort(true);

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    jsonError(405, 'method-not-allowed');
}

try {
    startUserGuardSession();

    if (authenticatedUserSubId() === '') {
        jsonError(403, 'unauthorized');
    }

    if (!hasValidSessionCsrf('user_portal', requestCsrfToken())) {
        jsonError(419, 'invalid-csrf');
    }

    $domain = addonNormalizeDomain((string) ($_POST['domain'] ?? ''));
    if ($domain === null) {
        jsonError(422, 'invalid-domain');
    }

    $result = addonPerformCpanelAddonDomain($domain);
    if (!$result['ok']) {
        jsonError(502, $result['error'] !== '' ? $result['error'] : 'cpanel-operation-failed');
    }

    echo json_encode(['ok' => true], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    error_log('addon-domain-api: json encode failed');
    jsonError(500, 'server-error');
} catch (Throwable $e) {
    error_log('addon-domain-api: server-error ' . get_class($e));
    jsonError(500, 'server-error');
}
