<?php

namespace ModulesGarden\Servers\ZimbraEmail\App\Traits;


use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\CustomField;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\CustomFieldValue;
use ModulesGarden\Servers\ZimbraEmail\Core\Models\Whmcs\Hosting;

/**
 *
 * Created by PhpStorm.
 * User: Tomasz Bielecki ( tomasz.bi@modulesgarden.com )
 * Date: 10.09.19
 * Time: 10:43
 * Class HostingService
 */
trait HostingService
{
    /**
     * @return mixed
     */
    public function getHostingId()
    {
        if (!$this->hostingId)
        {
            $this->hostingId = $this->getWhmcsParamByKey("serviceid");
        }
        return $this->hostingId;
    }

    /**
     * @param mixed $hostingId
     */
    public function setHostingId($hostingId)
    {
        $this->hostingId = $hostingId;
        return $this;
    }

    /**
     * @return Hosting
     */
    public function hosting()
    {
        if ($this->hosting instanceof Hosting)
        {
            return $this->hosting;
        }
        return $this->hosting = Hosting::where("id", $this->getHostingId())->firstOrFail();
    }

    public function isActive()
    {
        return Hosting::ofId($this->getHostingId())->active()->count() == 1;
    }

    public function isSupportedModule()
    {
        return Hosting::ofServerType($this->getHostingId(), "proxmoxVPS")->count() == 1;
    }

    private function getCustomFieldId($fieldName)
    {
        return CustomField::select("id")
            ->where("type", "product")
            ->where("relid", $this->hosting()->packageid)
            ->where("fieldname", "like", $fieldName . "%")
            ->value("id");
    }

    public function customFieldUpdate($name, $value = '')
    {
        $fieldId = $this->getCustomFieldId($name);
        //Update
        if (CustomFieldValue::where('fieldid', $fieldId)->where("relid", $this->getHostingId())->count())
        {
            return CustomFieldValue::where('fieldid', $fieldId)->where("relid", $this->getHostingId())->update(['value' => $value]);
        }
        //Create
        $customFiledValue = new CustomFieldValue();
        $customFiledValue->fill([
            'fieldid' => $fieldId,
            'relid'   => $this->getHostingId(),
            'value'   => $value
        ]);
        return $customFiledValue->save();
    }
}