<?php

namespace ThurData\Servers\KerioEmail\App\UI\Client\Setting\Providers;

use ThurData\Servers\KerioEmail\App\Enums\Kerio;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\Helper\DnsHelper;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\Core\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 18.09.19
 * Time: 09:35
 * Class EditSettingDataProvider
 */
class EditSettingDataProvider extends BaseDataProvider
{

    /**
     *
     */
    public function read()
    {
        $maildomain = $this->actionElementId;
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $dkimSet = $api->getDkimDnsRecord($maildomain);
            $features = $api->getDomains(['id','name','isDkimEnabled','twoFAEnabled','isInstantMessagingEnabled']);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }
        $api->logout();
        // find own domain
        foreach($features as $feature) {
            if($feature['name'] === $maildomain){ 
                $domainID = $feature['id'];
                $feature['twoFAEnabled'] == true ? $tfaenabled = 'on' : $tfaenabled = 'off' ;
                $feature['isDkimEnabled'] == true ? $dkimsigenabled = 'on' : $dkimsigenabled = 'off';
                $feature['isInstantMessagingEnabled'] == true ? $chatenabled = 'on' : $chatenabled = 'off';
            }
        }
        // format dkim response
        $dkimArray = explode(PHP_EOL,$dkimSet['detail']);
        $dkimValue = explode(":",$dkimArray[1]);
        $this->domainKey = ltrim($dkimValue[1]);
        $dkimName = explode(":",$dkimArray[0]);
        $this->dkimName = ltrim($dkimName[1]);

        // get settings from product configuration
        $productManager = new ProductManager();
        $productManager->loadById($this->getWhmcsParamByKey('pid'));
        $this->spfConfig = $productManager->get('spf_string');
        $this->dmarcConfig = $productManager->get('dmarc_string');
        $clientDomains = localAPI('GetClientsDomains', array('clientid' => $this->getWhmcsParamByKey('userid')));

        $dns = new DnsHelper();

        /**
         * format model to array
         */
        in_array($maildomain,$clientDomains) ? $selfdomain = 1 : $selfdomain = 0;
        $dnsRecords = $dns->getRecords($maildomain);
        $dnsRecords['selfdns'] ? $selfDns = $dnsRecords['selfdns'] : $selfDns = 0;
        $this->mxthurdata = $this->getWhmcsParamByKey('serverhostname');
        if(empty($dnsRecords['mx'])){
            $mx = 'unset';
            $mxmulti = false;
        } else {
            count($dnsRecords['mx']) > 1 ? $mxmulti = true : $mxmulti = false;
            $mx = implode(' ',$dnsRecords['mx']);
        }
        if(empty($dnsRecords['spf'])) {
            $spf = 'unset';
            $spfmulti = false;
        } else {
            count($dnsRecords['spf']) > 1 ? $spfmulti = true : $spfmulti = false;
            $spf = implode(' ',$dnsRecords['spf']);
        }
        if(empty($dnsRecords['dmarc'])) {
            $dmarc = 'unset';
            $dmarcmulti = false;
        } else {
            count($dnsRecords['dmarc']) > 1 ? $dmarcmulti = true : $dmarcmulti = false;
            $dmarc = implode(' ',$dnsRecords['dmarc']);
        }
        $dkim = 'unset';
        if(empty($dnsRecords['dkim'])) {
            $dkimmulti = false;
        } else {
            count($dnsRecords['dkim']) > 1 ? $dkimmulti = true : $dkimmulti = false;
            foreach($dnsRecords['dkim'] as $dkimRecord) {
                if($dkimRecord[0] == $this->dkimName) {
                    $dkim = $dkimRecord[1];
                }
            }
        }
        if(in_array($this->mxthurdata, $dnsRecords['mx'])){
            if($this->spfConfig == $spf && $this->dmarcConfig == $dmarc && in_array($this->domainKey, $dnsRecords['dkim'])){
                $dnsok = 'success';
            } else {
                $dnsok = 'warning';
            }
        } else {
            $dnsok = 'danger';
        }
        $this->data = [
            'editmaildomain' => $maildomain,
            'editmxactive' => $mx,
            'editspf' => $spf,
            'editdmarc' => $dmarc,
            'dkimname' => $this->dkimName,
            'editdkim' => $dkim,
            'editmxthurdata' => $this->mxthurdata,
            'editspfthurdata' => $this->spfConfig,
            'editdmarcthurdata' => $this->dmarcConfig,
            'editdkimthurdata' => $this->domainKey,
            'zoneid' => $selfDns,
            'dnsok' => $dnsok,
            'mxmulti' => $mxmulti,
            'dkimmulti' => $dkimmulti,
            'dmarcmulti' => $dmarcmulti,
            'spfmulti' => $spfmulti,
            'tfaenabled' => $tfaenabled,
            'chatenabled' => $chatenabled,
            'dkimsigenabled' => $dkimsigenabled,
            'domainid' => $domainID
        ];
    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function update()
    {
        $fieldToProtection = [
            'editmaildomain',
            'zoneid',
            'editmxactive',
            'editspf',
            'editdmarc',
            'editdkim',
            'dkimname',
            'tfaenabled',
            'chatenabled',
            'dkimsigenabled',
            'domainid'
        ];

        foreach ($this->formData as $field => &$value)
        {
            $value = in_array($field, $fieldToProtection) ? htmlentities($value) : $value;
        }

        $maildomain = $this->actionElementId;
        $domain = $this->getWhmcsParamByKey('domain');
        if ($maildomain == $domain) {
            $this->formData['dkimsigenabled'] == 'on' ? $attr['isDkimEnabled'] = true : $attr['isDkimEnabled'] = false;
            $this->formData['tfaenabled'] == 'on' ? $attr['twoFAEnabled'] = true : $attr['twoFAEnabled'] = false;
            $this->formData['chatenabled'] == 'on' ? $attr['isInstantMessagingEnabled'] = true : $attr['isInstantMessagingEnabled'] = false;

		logModuleCall(
			'kerioEmail',
			__FUNCTION__,
			$this->formData['domainid'],
			'Debug API',
			$attr
		);

            $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
            try {
                $api->login($this->getWhmcsParamByKey('serverhostname'), $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
                $result = $api->modifyDomain($this->formData['domainid'], $attr);
            } catch (KerioApiException $error) {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $error,
                    'Debug Error',
                    $error->getMessage()
                );
                return (new HtmlDataJsonResponse())->setMessageAndTranslate('updateHasBeenFailed')->setStatusError();
            }
            $api->logout();
        }
        if ($this->formData['zoneid'] > 0 ){
            $dnsParams = array(
                'maildomain' => $this->formData['editmaildomain'],
                'mx' => $this->formData['editmxactive'],
                'spf' => $this->formData['editspf'],
                'dmarc' => $this->formData['editdmarc'],
                'dkim' => $this->formData['editdkim'],
                'dkimname' => $this->formData['dkimname']
            );

            $dns = new DnsHelper();

            $result = $dns->updateDNS($this->formData['zoneid'],$dnsParams);
            if($result != 'success') {
                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $result,
                    'Debug result updateDNS zoneID: ' . $this->formData['zoneid'],
                    $dnsParams
                );
                return (new HtmlDataJsonResponse())->setMessageAndTranslate('updateHasBeenFailed')->setStatusError();
            }
        }
        return (new HtmlDataJsonResponse())->setMessageAndTranslate('settingHasBeenUpdated')->setStatusSuccess();
    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function updateStatus()
    {

    }

    /**
     * @return HtmlDataJsonResponse
     */
    public function changePassword()
    {

    }
}