<?php

namespace ModulesGarden\ProxmoxAddon\App\Helper;

use ModulesGarden\ProxmoxAddon\App\Models\Doe\SubmoduleSettings;
use ModulesGarden\ProxmoxAddon\Core\Helper;
use ModulesGarden\ProxmoxAddon\Core\Models\Whmcs\DomainPricing;

/**
 * Description of AbstractAvailableExtensions
 *
 * @author Rafał Ossowski <rafal.os@modulesgarden.com>
 */
class AbstractAvailableExtensions
{
    protected $submoduleConfigKey = null;
    protected $tlds = [];

    /**
     * @var DomainPricing
     */
    protected $domainPricing;

    public function __construct(DomainPricing $domainPricing)
    {
        $this->domainPricing = $domainPricing;
    }

    public function isExist($name)
    {
        return in_array($name, $this->tlds, true);
    }

    public function removeTldsById($ids)
    {
        if (is_array($ids))
        {
            $names = $this->getDomainPricingById($ids);

            foreach ($names as $name)
            {
                $this->unsetTld($name['tld']);
            }
        }
        else
        {
            $name = $this->getDomainPricingById($ids);
            $this->unsetTld($name['tld']);
        }

        return $this;
    }

    protected function getDomainPricingById($ids)
    {
        if (is_array($ids))
        {
            return $this->domainPricing
                ->select("{$this->domainPricing->getTable()}.extension as tld")
                ->whereIn("{$this->domainPricing->getTable()}.id", $ids)
                ->get()
                ->toArray();
        }
        else
        {
            return $this->domainPricing
                ->select("{$this->domainPricing->getTable()}.extension as tld")
                ->where("{$this->domainPricing->getTable()}.id", "LIKE", (int)$ids)
                ->first()
                ->toArray();
        }

        return null;
    }

    protected function unsetTld($name)
    {
        if ($key = array_search($name, $this->tlds, true))
        {
            unset($this->tlds[$key]);
        }

        return $this;
    }

    public function removeTldsByName($names)
    {
        if (is_array($names))
        {
            foreach ($names as $name)
            {
                $this->unsetTld($name);
            }
        }
        else
        {
            $this->unsetTld($names);
        }

        return $this;
    }

    public function getAllowedTldList()
    {
        return array_diff($this->getTlds(), $this->loadDisabledTldList());
    }

    public function getTlds()
    {
        return $this->tlds;
    }

    protected function loadDisabledTldList()
    {
        $model   = Helper\di(SubmoduleSettings::class);
        $setting = $model->query()->getQuery()->select('value')
            ->where('submodule', '=', $this->submoduleConfigKey)
            ->where('setting', '=', 'disabledTlds')->value('value');

        if ($setting)
        {
            return json_decode($setting) ?: [];
        }

        return [];
    }
}
