<?php

namespace ModulesGarden\Servers\OpenXchange\App\UI\Client\MXRecords\Pages;

use ModulesGarden\Servers\OpenXchange\Core\UI\Interfaces\ClientArea;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\Column;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataTable;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\Servers\OpenXchange\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;

class MxRecordsPage extends DataTable implements ClientArea
{
    protected $id    = 'forwarders';
    protected $name  = 'forwarders';
    protected $title = null;

    /**
     * load columns
     */
    protected function loadHtml()
    {
        $this
        ->addColumn((new Column('name'))
            ->setOrderable(DataProvider::SORT_ASC)
            ->setSearchable(true, Column::TYPE_STRING))
        ->addColumn((new Column('ttl'))
            ->setOrderable()
            ->setSearchable(true))
        ->addColumn((new Column('priority'))
            ->setOrderable()
            ->setSearchable(true, Column::TYPE_INT))
        ->addColumn((new Column('value'))
            ->setOrderable()
            ->setSearchable(true));
    }

    /**
     * load buttons
     */
    public function initContent()
    {

    }

    /**
     * load data
     */
    public function loadData()
    {
        $hosting  = \WHMCS\Service\Service::find($_REQUEST['id']);
        $hostname = $hosting->serverModel->hostname;
        $username = $hosting->serverModel->username;

        $i    = 1;
        $data = [];

        for($i; $i < 5; $i++)
        {
            $data[] = [
                'name' => '@ or leave blank',
                'ttl' => 3600,
                'recordType' => 'MX',
                'priority' => 10,
                'value' => $this->prepareValue($hostname, $i, $username)
            ];
        }
        
        $dataProv = new ArrayDataProvider();
        $dataProv->setDefaultSorting('mailbox', 'ASC')->setData($data);
        $this->setDataProvider($dataProv);
    }

    private function prepareValue($hostname, $i, $username)
    {
        if (strpos($hostname, 'eu.appsuite.cloud') !== false || strpos($hostname, 'provisioning.eu.appsuite.cloud') !== false)
        {
            return 'mx00'.$i.'.cloudeu.xion.oxcs.net';
        }
        elseif (strpos($hostname, 'us.appsuite.cloud') !== false || strpos($hostname, 'provisioning.us.appsuite.cloud') !== false)
        {
            return 'mx00'.$i.'.cloudus.xion.oxcs.net';
        }
        else
        {
            return 'mx00'.$i.'.'.$username;
        }
    }
}
