<?php
// This is the main entry point for the P2P exchange Telegram bot. It sets
// up the Longman Telegram Bot library, registers custom command paths and
// handles incoming webhook or getUpdates requests. Before running this
// script, ensure you have installed composer dependencies and created the
// required database schema (see database.sql).

require __DIR__ . '/vendor/autoload.php';

use Bot\Config;
use Bot\Database;
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Request;
use Bot\Services\DepositWatcherService;
use Bot\Services\WithdrawalProcessor;


// Fetch configuration via Config::getValue.  Config::get() returns an
// instance with a flexible getValue method for nested keys.  Using this
// helper avoids treating the configuration object as an array.

$cfg = Config::get();

// Validate essential configuration
$botToken = $cfg->getValue('telegram_token');
$botUser  = $cfg->getValue('bot_username');
if (!$botToken || !$botUser) {
    throw new RuntimeException('Missing TELEGRAM_BOT_TOKEN or TELEGRAM_BOT_USERNAME environment variables.');
}

// Initialise Telegram API object
$telegram = new Telegram($botToken, $botUser);
//$telegram->useGetUpdatesWithoutDatabase(true);

// Set custom command paths. Commands are stored in src/Commands.
$telegram->addCommandsPath(__DIR__ . '/src/Commands');

// Enable database integration using an external PDO instance.  This
// connection is provided by our Database wrapper and used for admin
// commands.  If your .env does not define DB_HOST etc. this step is
// silently skipped.
$dbHost = $cfg->getValue('db.host');
if ($dbHost) {
    $pdo = Database::connection();
    $telegram->enableExternalMySql($pdo);
}
//$db = Database::connection();

// Register bot admins (optional) from comma-separated list in .env
$adminIds = $cfg->getValue('admin_ids', []);
foreach ($adminIds as $adminId) {
    if (!empty($adminId) && is_numeric($adminId)) {
        $telegram->enableAdmin((int) $adminId);
    }
}

// Determine action: when called from the command line we allow
// setting/deleting webhooks.  Otherwise we default to handling
// incoming updates via long polling.  Supported actions:
//  * set:webhook   - Set the webhook URL specified by WEBHOOK_URL in .env
//  * delete:webhook - Remove the currently configured webhook
//  * handle        - Poll for updates (default)
$action = $argv[1] ?? 'handle';

switch ($action) {
    case 'set:webhook':
        $webhookUrl = $cfg->getValue('webhook_url');
        if (!$webhookUrl) {
            fwrite(STDERR, "Missing WEBHOOK_URL in .env\n");
            exit(1);
        }
        $result = $telegram->setWebhook($webhookUrl);
        echo $result->isOk() ? "Webhook set: {$webhookUrl}\n" : $result->printError();
        break;

    case 'delete:webhook':
        $result = $telegram->deleteWebhook();
        echo $result->isOk() ? "Webhook removed\n" : $result->printError();
        break;

    case 'watch:deposits':
        $watcher = new DepositWatcherService();
        $count = $watcher->syncAll();
        echo "Processed {$count} deposit events.\n";
        break;

    case 'withdraw:process':
        $processor = new WithdrawalProcessor();
        $count = $processor->processQueue();
        echo "Processed {$count} withdrawals.\n";
        break;

    case 'handle':
    default:
        // Use handleGetUpdates() for long polling.  If using webhooks via
        // nginx/apache, call set:webhook and let your web server route
        // requests to this script instead.
        try {
            $response = $telegram->handleGetUpdates();
            if ($response !== null && !$response->isOk()) {
                $response->printError();
            }
        } catch (Longman\TelegramBot\Exception\TelegramException $e) {
            error_log($e->getMessage());
        }
        break;
}
