<?php







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

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

define('DS', DIRECTORY_SEPARATOR);
$root = dirname(__DIR__);
if (!is_file($root . DS . 'config.php')) {
    fwrite(STDERR, "EasyChat config is unavailable.\n");
    exit(1);
}

$options = getopt('', ['request-id:', 'admin-id:']);
$request_id = (int)($options['request-id'] ?? 0);
$admin_id = (int)($options['admin-id'] ?? 0);
if ($request_id <= 0 || $admin_id <= 0) {
    fwrite(STDERR, "Usage: php cli/outbound_contact_recovery.php --request-id=123 --admin-id=1\n");
    exit(2);
}

require_once $root . DS . 'library' . DS . 'request_context.php';
\EasyChat\Library\RequestContext::bootstrapServerDefaults([
    'HTTP_HOST' => 'localhost',
    'SCRIPT_NAME' => '/cli/outbound_contact_recovery.php',
    'HTTPS' => 'off',
    'HTTP_X_FORWARDED_PROTO' => '',
    'HTTP_X_FORWARDED_SSL' => '',
    'SERVER_PORT' => 80,
]);
require_once $root . DS . 'config.php';
require_once SITE_PATH . DS . 'core' . DS . 'autoload.php';
require_once SITE_PATH . DS . 'library' . DS . 'url_helper.php';
require_once SITE_PATH . DS . 'library' . DS . 'install_service.php';

try {
    $registry = new Registry();
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT);
    $registry->set('db', $db);
    (new EasyChat\Library\AppClock($registry))->syncDatabaseSessionTimezone();
    if (class_exists('EasyChat_Install_Service')) {
        EasyChat_Install_Service::ensureRuntimeSchema($db, easychat_db_prefix());
    }

    $manager = (new EasyChat\Model\Manager($registry))->getManagerById($admin_id);
    if (!$manager || (string)($manager['role'] ?? '') !== 'admin' || (int)($manager['status'] ?? 0) !== 1) {
        fwrite(STDERR, "Active administrator is required.\n");
        exit(3);
    }

    $result = (new EasyChat\Model\OutboundContact($registry))->compensateMaxChatTypeAttempt(
        $request_id,
        $admin_id
    );
    if (empty($result['success'])) {
        fwrite(STDERR, "Request is not eligible for MAX chat-type compensation.\n");
        exit(4);
    }

    fwrite(STDOUT, "MAX first-contact attempt compensated for request_id=" . $request_id . ".\n");
    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, "Recovery failed.\n");
    exit(1);
}
