#!/usr/bin/env php
<?php

use Console\ApplicationFactory;
use Console\Commands\CacheClearCommand;
use Console\Commands\CustomerCountsCommand;
use Console\Commands\PulseSendEventsCommand;
use Console\Commands\ScheduleListCommand;
use Console\Commands\ScheduleRunCommand;
use Console\Commands\VersionCommand;
use Console\Commands\ImagesWarmupCacheCommand;
use Console\Commands\ImagesCacheClearCommand;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Openguru\OpenCartFramework\QueryBuilder\Connections\MySqlConnection;
use Openguru\OpenCartFramework\Support\Arr;
use Symfony\Component\Console\Application;

if (PHP_SAPI !== 'cli') {
    die("This script can only be run from CLI.\n");
}

$baseDir = __DIR__;
$debug = true;

if (is_readable($baseDir . '/oc_telegram_shop.phar')) {
    require_once "phar://{$baseDir}/oc_telegram_shop.phar/vendor/autoload.php";
    require_once $baseDir . '/../../../admin/config.php';
} elseif (is_dir("$baseDir/oc_telegram_shop")) {
    require_once "$baseDir/oc_telegram_shop/vendor/autoload.php";
    require_once '/web/upload/admin/config.php';
} else {
    throw new RuntimeException('Unable to locate application directory.');
}

date_default_timezone_set('UTC');

// Get Settings from Database
$host = DB_HOSTNAME;
$username = DB_USERNAME;
$password = DB_PASSWORD;
$port = (int) DB_PORT;
$dbName = DB_DATABASE;
$prefix = DB_PREFIX;
$dsn = "mysql:host=$host;port=$port;dbname=$dbName";
$pdo = new PDO($dsn, $username, $password);
$connection = new MySqlConnection($pdo);
$raw = $connection->select("SELECT value FROM `{$prefix}setting` WHERE `key` = 'module_telecart_settings'");
$json = json_decode($raw[0]['value'], true, 512, JSON_THROW_ON_ERROR);
$items = Arr::mergeArraysRecursively($json, [
    'app' => [
        'shop_base_url' => HTTPS_CATALOG, // for catalog: HTTPS_SERVER, for admin: HTTPS_CATALOG
        'language_id' => 1,
    ],
    'paths' => [
        'images' => DIR_IMAGE,
    ],
    'logs' => [
        'path' => DIR_LOGS,
    ],
    'database' => [
        'host' => DB_HOSTNAME,
        'database' => DB_DATABASE,
        'username' => DB_USERNAME,
        'password' => DB_PASSWORD,
        'prefix' => DB_PREFIX,
        'port' => (int) DB_PORT,
    ],
    'store' => [
        'oc_store_id' => 0,
        'oc_default_currency' => 'RUB',
        'oc_config_tax' => false,
    ],
    'orders' => [
        'oc_customer_group_id' => 1,
    ],
    'telegram' => [
        'mini_app_url' => rtrim(HTTPS_CATALOG, '/') . '/image/catalog/tgshopspa/#/',
    ],
]);

// Create logger
$logger = new Logger('TeleCart_CLI', [], [], new DateTimeZone('UTC'));
$logger->pushHandler(
    new RotatingFileHandler(
        DIR_LOGS . '/telecart.log', 14, $debug ? Logger::DEBUG : Logger::INFO
    ),
);

// Creates TeleCart application.
$app = ApplicationFactory::create($items);
$app->setLogger($logger);
$app->boot();

// Creates Console and bind commands.
$console = new Application('TeleCart', module_version());
$console->add($app->get(VersionCommand::class));
$console->add($app->get(ScheduleRunCommand::class));
$console->add($app->get(ScheduleListCommand::class));
$console->add($app->get(PulseSendEventsCommand::class));
$console->add($app->get(ImagesWarmupCacheCommand::class));
$console->add($app->get(ImagesCacheClearCommand::class));
$console->add($app->get(CacheClearCommand::class));
$console->add($app->get(CustomerCountsCommand::class));
$console->run();
