<?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\UI\ResponseTemplates\HtmlDataJsonResponse;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\Core\Helper\DnsHelper;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\DataProviders\BaseDataProvider;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 10.09.19
 * Time: 13:06
 * Class SettingDataProvider
 */
class InfoSettingDataProvider extends BaseDataProvider
{

    public function read()
    {
        $domain = $this->getWhmcsParamByKey('domain');
        $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'] === $domain){ 
                $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 = 1 : $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 && $this->domainKey == $dkim){
                $dnsok = 'success';
            } else {
            	$dnsok = 'warning';
            }
        } else {
            $dnsok = 'danger';
        }
        $this->data = [
            'dnsmessage' => 'DNS Informationen für',
            'infomaildomain' => $maildomain,
            'mxactive' => $mx,
            'spf' => $spf,
            'dmarc' => $dmarc,
            'dkim' => $dkim,
            'mxthurdata' => $this->mxthurdata,
            'spfthurdata' => $this->spfConfig,
            'dmarcthurdata' => $this->dmarcConfig,
            'dkimthurdata' => $this->domainKey,
            'dkimname' => $this->dkimName,
            'selfdns' => $selfDns,
            'dnsok' => $dnsok,
            'mxmulti' => $mxmulti,
            'dkimmulti' => $dkimmulti,
            'dmarcmulti' => $dmarcmulti,
            'spfmulti' => $spfmulti,
            'tfaenabled' => $tfaenabled,
            'chatenabled' => $chatenabled,
            'dkimsigenabled' => $dkimsigenabled
        ];
    }

    public function create()
    {

    }

    public function updateStatus()
    {

    }

    public function update()
    {

    }
}
