<?php

namespace idoit\Module\Console\Steps\Addon;

use idoit\Module\Console\Steps\Message\Messages;
use idoit\Module\Console\Steps\Step;
use isys_component_database;
use isys_component_database_mysqli;

class BundleInstall implements Step
{
    /**
     * @var isys_component_database
     */
    private isys_component_database $systemDb;

    /**
     * @var string
     */
    private string $dbName;

    /**
     * @var array
     */
    private array $addons = [];

    /**
     * @param isys_component_database $systemDb
     * @param string                  $addons
     * @param string                  $dbName
     *
     * @throws \Exception
     */
    public function __construct(isys_component_database $systemDb, string $addons, string $dbName)
    {
        $this->systemDb = $systemDb;
        $this->dbName = $dbName;

        $addons = (strlen($addons) > 0) ? explode(',', $addons) : [];
        $this->addons = array_map('trim', $addons);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'Install Addon bundle';
    }

    /**
     * @param Messages $messages
     *
     * @return bool
     */
    public function process(Messages $messages)
    {
        $result = $this->systemDb->query(sprintf("SELECT isys_mandator__id as tenantId FROM isys_mandator
            WHERE isys_mandator__db_name = '%s'", $this->systemDb->escape_string($this->dbName)));
        $tenantId = $this->systemDb->fetch_row_assoc($result)['tenantId'];

        if (!\isys_module_manager::bundleInstall($this->systemDb, $this->addons, $tenantId)) {
            return false;
        }

        return true;
    }

    /**
     * Undo the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function undo(Messages $messages)
    {
        return true;
    }
}
