<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/logger.php';
require_once __DIR__ . '/../src/bitrix.php';

header('Content-Type: text/html; charset=utf-8');

try {
    $result = installCrestApp();

    logMessage('info', 'Application install requested', [
        'result' => $result,
        'request' => $_REQUEST,
    ]);

    echo '<h3>Application installed</h3>';
    echo '<pre>';
    print_r($result);
    echo '</pre>';

    echo '<script src="//api.bitrix24.com/api/v1/"></script>';
    echo '<script>
        BX24.init(function () {
            BX24.installFinish();
        });
    </script>';
} catch (Throwable $exception) {
    logMessage('error', 'Application install failed', [
        'error' => $exception->getMessage(),
        'trace' => $exception->getTraceAsString(),
    ]);

    http_response_code(500);
    echo '<h3>Install failed</h3>';
    echo '<pre>' . htmlspecialchars($exception->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") . '</pre>';
}
