<?php

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

use ThurData\Servers\KerioEmail\App\UI\Admin\Custom\Fields\EnabledField;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\Fields\Hidden;
use ThurData\Servers\KerioEmail\App\UI\Client\Setting\Buttons\EditSettingButton;
use function ThurData\Servers\KerioEmail\Core\Helper\di;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\Column;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Interfaces\ClientArea;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ThurData\Servers\KerioEmail\Core\UI\Widget\DataTable\DataTable;
use ThurData\Servers\KerioEmail\Api\KerioWhmcs;
use ThurData\Servers\KerioEmail\App\Libs\Product\ProductManager;
use ThurData\Servers\KerioEmail\App\UI\Client\Setting\Buttons\InfoButton;
use ThurData\Servers\KerioEmail\Core\Helper\DnsHelper;
use ThurData\Servers\KerioEmail\Core\UI\HiddenSearchable;
use ThurData\Servers\KerioEmail\Core\UI\Widget\Forms\Fields\BaseField;

/**
 *
 * Created by PhpStorm.
 * User: ThurData
 * Date: 10.09.19
 * Time: 10:51
 * Class Setting
 */
class Settings extends DataTable implements ClientArea
{

    use \ThurData\Servers\KerioEmail\Core\UI\Traits\DisableButtonByColumnValue;
    /**
     * labels for statuses
     */
    const STATUS_LABEL = [
        'set'       =>  'success',
        'unset'     =>  'warning',
        'wrong'     =>  'danger',
        'multi'     =>  'danger',
        'default'   =>  'default'
    ];

    protected $id    = 'Setting';
    protected $name  = 'Setting';
    protected $title = null;

    /**
     * load columns
     */
    protected function loadHtml()
    {
        $this
            ->addColumn((new Column('domain'))
                ->setOrderable(DataProvider::SORT_ASC)
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('mxactive'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('spf'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('dmarc'))
                ->setOrderable()
                ->setSearchable(true, Column::TYPE_STRING))
            ->addColumn((new Column('dkim'))
                ->setOrderable()
                ->setSearchable(true))
            ->addColumn((new Column('selfdns'))
                ->setClass("hidden"))
            ->addColumn((new Column('selfdomain'))
                ->setClass("hidden"))
                ;
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldMxactive($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldSpf($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldDmarc($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function replaceFieldDkim($key, $row)
    {
        $status = self::STATUS_LABEL[$row[$key]] ? self::STATUS_LABEL[$row[$key]] : self::STATUS_LABEL['default'];
        $label = di('lang')->absoluteT('kerio','account','status',$row[$key]);

        $field = new EnabledField();
        $field->setRawType($status);
        $field->setRawTitle($label);

        return $field->getHtml();
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function customColumnHtmlSelfdns()
    {
        $this->addHtmlAttribute('display', 'none');
    }

    /**
     * @param $key
     * @param $row
     * @return mixed
     */
    public function customColumnHtmlSelfdomain()
    {
        $this->addHtmlAttribute('display', 'none');
    }

    /**
     * load buttons
     */
    public function initContent()
    {
        
        $this->addActionButton(new InfoButton());
        $this->addActionButton(new EditSettingButton());

    }

    /**
     * load data
     */
    public function loadData()
    {
        $maildomain = $this->getWhmcsParamByKey('domain');
        $mailserver = $this->getWhmcsParamByKey('serverhostname');
        $api = new KerioWhmcs('whmcsKerioEmail', 'Thurdata', '1.0');
        try {
            $api->login($mailserver, $this->getWhmcsParamByKey('serverusername'), $this->getWhmcsParamByKey('serverpassword'));
            $domains = $api->getDomains(['id','name','aliasList']);
            $dkimSet = $api->getDkimDnsRecord($maildomain);
        } catch (KerioApiException $error) {
            logModuleCall(
                'kerioEmail',
                __FUNCTION__,
                $error,
                'Debug Error',
                $error->getMessage()
            );
            return ['error' => $error->getMessage()];
        }

        foreach($domains as $domain) {
            if(($domain['name']) === $maildomain){ 
                $aliasList = $domain['aliasList'];
            }
        }

        $api->logout();
        $domains = [$maildomain];
        foreach($aliasList as $aliasDomain){
            array_push($domains,$aliasDomain);
        }
        // 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
         */
        $data = [];

        foreach($domains as $domain){
            in_array($domain,$clientDomains) ? $selfdomain = 1 : $selfdomain = 0;
            $dnsRecords = $dns->getRecords($domain);
            $dnsRecords['selfdns'] ? $selfDns = 1 : $selfDns = 0;
            if(empty($dnsRecords['mx'])){
                $mx = 'unset';
            } else {
                in_array($mailserver,$dnsRecords['mx']) ? $mx = 'set' : $mx = 'wrong';

                logModuleCall(
                    'kerioEmail',
                    __FUNCTION__,
                    $mailserver,
                    'Debug Error',
                    implode('', $dnsRecords['mx'])
                );

            }
            if(empty($dnsRecords['spf'])) {
                $spf = 'unset';
            } else {
                if (count($dnsRecords['spf']) > 1) {
                    $spf = 'multi';
                } else {
                    if($dnsRecords['spf'][0] === $this->spfConfig){
                        $spf = 'set';
                    } else {
                        $spf = 'wrong';
                    }
                }
            }
            if(empty($dnsRecords['dmarc'])) {
                $dmarc = 'unset';
            } else {
                if (count($dnsRecords['dmarc']) > 1) {
                    $dmarc = 'multi';
                } else {
                    if($dnsRecords['dmarc'][0] === $this->dmarcConfig){
                        $dmarc = 'set';
                    } else {
                        $dmarc = 'wrong';
                    }
                }
            }
            in_array($this->domainKey, $dnsRecords['dkim']) ? $dkim = 'set' : $dkim = 'unset';
            $tmp = [
                'id' => $domain,
                'domain' => $domain,
                'mxactive' => $mx,
                'spf' => $spf,
                'dmarc' => $dmarc,
                'dkim' => $dkim,
                'selfdns' => $selfDns,
                'selfdomain' => $selfdomain
            ];
            $data[] = $tmp;
        }
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('setting', 'ASC')->setData($data);
        $this->setDataProvider($dataProv);

    }

}