<?php

namespace ModulesGarden\HostingQuotaNotifications\App\Helper\Modules;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Models\EmailTemplates;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\Configuration;
use ModulesGarden\HostingQuotaNotifications\Core\Models\Whmcs\EmailTemplate;
use ModulesGarden\HostingQuotaNotifications\Core\ModuleConstants;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\Forms\Fields\SelectLang;

/**
 * Class Multibrand
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class Multibrand
{

    CONST MULTIBRAND = 'Multibrand';
    CONST MB_SEND_EMAIL = 'mbsendemail';

    public static function isActive()
    {
        $activesAddonsString = Configuration::where('setting', '=', 'ActiveAddonModules')->value('value');
        $activesAddonsArray  = explode(',', $activesAddonsString);

        if (in_array(SELF::MULTIBRAND, $activesAddonsArray))
        {

            require_once ModuleConstants::getFullPathWhmcs() . DS . 'modules' . DS . 'addons' . DS . SELF::MULTIBRAND . DS . 'Loader.php';
            new \MGModule\Multibrand\Loader();

            return true;
        }
        return false;
    }

    public static function updateVars(&$command, &$params)
    {

        if (!self::isMbSendEmailExist())
        {
            return;
        }

        $template = EmailTemplate::where('name', '=', $params['messagename'])->first();

        // TODO przerobić gdy Paweł poprawi API multibranda do wysylania maila
        $command                 = SELF::MB_SEND_EMAIL;
        $params['brandid']       = self::getBrandId($params['id']);
        $params['customvars']    = base64_encode(serialize($params['customvars']));
        $params['custommessage'] = $template->message;
        $params['customsubject'] = $template->subject;
        $params['customtype']    = $template->type;

    }

    public static function getBrandId($hostingid)
    {
        $service = new \MGModule\Multibrand\Core\Whmcs\Services\Hosting\Hosting($hostingid);
        $brand   = $service->getBrand();

        return $brand->id;
    }

    public static function isMbSendEmailExist()
    {
        if (file_exists(self::getMBSendEmailFilePath()))
        {
            return true;
        }
        return false;
    }

    public static function getMbSendEmailFunctionPath()
    {
        return DS . 'includes' . DS . 'api' . DS . SELF::MB_SEND_EMAIL . '.php';
    }

    public static function getMBSendEmailFilePath()
    {
        return ModuleConstants::getFullPathWhmcs() . self::getMbSendEmailFunctionPath();
    }
}
