<?php

namespace ModulesGarden\ProxmoxAddon\App\Services\Vps;

use ModulesGarden\ProxmoxAddon\App\Models\KeyPair;
use ModulesGarden\ProxmoxAddon\App\Services\ApiService;
use ModulesGarden\ProxmoxAddon\App\Services\Utility;
use ModulesGarden\ProxmoxAddon\Core\UI\Traits\WhmcsParams;
use ModulesGarden\ProxmoxAddon\App\Enum\Vps\CustomField;
use ModulesGarden\ProxmoxAddon\Core\Traits\Smarty;


class ContainerService
{
    use ApiService;
    use WhmcsParams;
    use HostingService;
    use Smarty;
    use ProductService;

    public function hostname()
    {
        $this->setHostingId($this->getWhmcsParamByKey("serviceid"));
        if ($this->configuration()->isQemu())
        {
            $domain    = $this->getWhmcsCustomField(CustomField::HOSTNAME,  $this->getWhmcsParamByKey('domain')) ;
            $nameForVm = $this->configuration()->getClientNameForContainer();
            if ($nameForVm == "emptyHostnameOnly" && empty($domain))
            { // Yes  [only when hostname is empty]
                $domain = $this->getWhmcsParamByKey('clientsdetails')['companyname'] ? $this->getWhmcsParamByKey('clientsdetails')['companyname'] : $this->getWhmcsParamByKey('clientsdetails')['lastname'] . $this->getWhmcsParamByKey('clientsdetails')['firstname'];
                $domain = trim(preg_replace('/[^A-Za-z0-9\.]/', '', Utility::replaceSpecialChars($domain)), '.');
                $this->hosting()->update(["domain" => $domain]);
            }
            else
            {
                if ($nameForVm == "overwriteHostname")
                { //Yes [overwrite hostname]
                    $domain = $this->getWhmcsParamByKey('clientsdetails')['companyname'] ? $this->getWhmcsParamByKey('clientsdetails')['companyname'] : $this->getWhmcsParamByKey('clientsdetails')['lastname'] . $this->getWhmcsParamByKey('clientsdetails')['firstname'];
                    $domain = trim(preg_replace('/[^A-Za-z0-9\.]/', '', Utility::replaceSpecialChars($domain)), '.');
                    $this->hosting()->update(["domain" => $domain]);
                }
                else
                {
                    if ($nameForVm == "overwriteHostnameWithPrefix" || $nameForVm == "0")
                    { //NO
                        if (empty($domain) || $nameForVm == "overwriteHostnameWithPrefix")
                        {
                            $domain = $this->configuration()->getContainerPrefix() . $this->getWhmcsParamByKey('serviceid');
                            $this->hosting()->update(["domain" => $domain]);
                        }
                    }
                }
            }
            return $domain;
        }
        else
        {
            if ($this->configuration()->isLxc())
            {
                if ($this->configuration()->isRandomHostname())
                {
                    $domain = parse_url($GLOBALS['CONFIG']['Domain']);
                    return $this->getWhmcsParamByKey('serviceid') . '.' . $domain['host'];
                }
                else
                {
                    return  $this->getWhmcsCustomField(CustomField::HOSTNAME,  $this->getWhmcsParamByKey('domain'));
                }
            }
        }
    }

    public function description()
    {
        if (!$this->params['model'])
        {
            $this->params['model'] = \WHMCS\Service\Service::where("id", $this->params['serviceid'])->first();
        }
        $vars = [
            'client_name'  => $this->getWhmcsParamByKey('clientsdetails')['firstname'] . ' ' . $this->getWhmcsParamByKey('clientsdetails')['lastname'] . (($this->getWhmcsParamByKey('clientsdetails')['companyname']) ? (' (' . $this->getWhmcsParamByKey('clientsdetails')['companyname'] . ')') : ''),
            'client_id'    => $this->getWhmcsParamByKey('userid'),
            'client_email' => $this->getWhmcsParamByKey('clientsdetails')['email'],
            'product_name' => $this->hosting()->product->name,
            'product_id'   => $this->getWhmcsParamByKey('pid'),
            'service_id'   => $this->getWhmcsParamByKey('serviceid'),
            'service_domain'  => $this->hosting()->domain,
            'service_dedicated_ip'  => $this->hosting()->dedicatedip,
            'service_assigned_ips'  => $this->hosting()->assignedips
        ];
        return $this->getSmarty()->fetchString($this->configuration()->getDescription(), $vars);
    }

    /**
     * @return KeyPair
     */
    public function makeKeyPairs()
    {
        //delete
        KeyPair::ofHostingId($this->getWhmcsParamByKey('serviceid'))->delete();
        $keyPairs = KeyPair::make();
        $keyPairs->setHostingId($this->getWhmcsParamByKey('serviceid'))
            ->save();
        return $keyPairs;
    }

}