<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

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

$options = getopt('', ['dialog-id:', 'message-base64:', 'bot-id::', 'help']);
if (isset($options['help']) || empty($options['dialog-id']) || empty($options['message-base64'])) {
    echo "Usage: php tools/send_internal_notification.php --dialog-id=chat123 --message-base64=BASE64 [--bot-id=123]\n";
    exit(isset($options['help']) ? 0 : 1);
}

$message = base64_decode((string) $options['message-base64'], true);
if ($message === false || trim($message) === '') {
    fwrite(STDERR, "Invalid or empty message-base64 value.\n");
    exit(1);
}

try {
    $result = sendBitrixNotificationMessage(
        (string) $options['dialog-id'],
        $message,
        isset($options['bot-id']) ? (int) $options['bot-id'] : null
    );
    echo json_encode(['ok' => true, 'result' => $result], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $exception) {
    echo json_encode(['ok' => false, 'error' => $exception->getMessage()], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
    exit(1);
}
