<?php

namespace MGModule\DNSManager2\controllers\addon\admin;

use Exception;
use MGModule\DNSManager2 as main;
use MGModule\DNSManager2\mgLibs\custom;
use MGModule\DNSManager2\mgLibs\custom\AjaxResponse;
use MGModule\DNSManager2\mgLibs\custom\dns\record\Record;
use MGModule\DNSManager2\mgLibs\custom\dns\utils\IP;
use MGModule\DNSManager2\mgLibs\custom\helpers\RecordSetHelper;
use MGModule\DNSManager2\mgLibs\custom\helpers\ZoneLogger\Manager as ZoneLoggerManager;
use MGModule\DNSManager2\mgLibs\custom\manager\ClientHelper;
use MGModule\DNSManager2\mgLibs\custom\manager\DefaultNotifications;
use MGModule\DNSManager2\mgLibs\custom\manager\EmailNotificationHelper;
use MGModule\DNSManager2\mgLibs\custom\manager\GlobalSettingHelper;
use MGModule\DNSManager2\mgLibs\custom\manager\LogHelper;
use MGModule\DNSManager2\mgLibs\custom\manager\ZoneCreator;
use MGModule\DNSManager2\models\custom\globalsetting\GlobalSettingEnum;
use MGModule\DNSManager2\models\custom\reverse;
use MGModule\DNSManager2\models\custom\set;
use MGModule\DNSManager2\models\custom\zone;
use \MGModule\DNSManager2\models\custom\package;
use \MGModule\DNSManager2\models\custom\globalsetting;
use MGModule\DNSManager2\models\custom\zone\Repository as ZoneRepository;
use MGModule\DNSManager2\mgLibs\custom\manager\additionalMethods\DefaultIPHelper;
use MGModule\DNSManager2\models\custom\zone\ZoneTypeEnum;

class zones extends main\mgLibs\process\abstractController{

    public function indexJSON($input, $vars = array()) {
        return AjaxResponse::I()->refreshPage($this->indexHTML($input, $vars))->toArray();
    }

    function indexHTML($input, $vars = array()) {
        return array(
            'tpl'   => 'main',
            'vars' => $vars
        );
    }

    function refreshZonesTableJSON($input, $vars = array()) {
        $query = "SELECT dns_manager2_zone.id AS id, dns_manager2_zone.name AS name, CONCAT(tblclients.firstname, ' ', tblclients.lastname) AS client, 
                          dns_manager2_zone.clientid AS clientid, dns_manager2_server.name AS server_name, dns_manager2_zone.type AS type,
                            dns_manager2_zone.relid AS relid, dns_manager2_zone.serverid AS serverid, dns_manager2_zone.status AS status ,
                            dns_manager2_zone.connected_with_type as connectedWithType, dns_manager2_zone.connected_with_relid as connectedWithRelid,
       						dns_manager2_zone.is_locked as is_locked
                    FROM dns_manager2_zone
                    LEFT JOIN dns_manager2_server ON dns_manager2_server.id = dns_manager2_zone.serverid
                    LEFT JOIN tblclients ON tblclients.id = dns_manager2_zone.clientid";  
        
        $columns = array('id','name', 'client', 'type', 'server_name', 'status', 'connectedWithType', 'connectedWithRelid');
        $helper = new main\mgLibs\custom\RawQueryTableHelper($query, $input, $columns);
        
        $data = $helper->getDataTableArray();

        foreach($helper->get() as $zone)
            $data['data'][] = $this->dataTablesParseRow('row', ['zone' => $zone]);

        return $data;
    }

    public function editZoneJSON($input, $vars = array()) {
        $zone = new zone\Zone($input['id']);
        $module = $zone->getModule();
        $module->zoneExists();

        $vars['counter'] = 0;
        $vars['id'] = $zone->id;
        $vars['zone_name'] = $zone->name;
        $vars['records'] = array_merge($module->getRecords(), $this->getPTRRecords($zone));

        foreach($vars['records'] as &$record) {
            $record->encode();
        }

        usort($vars['records'], static function ( $a, $b )
        {
            if( $a->type === 'SOA' ) return -1;
            if( $b->type === 'SOA' ) return 1;
            return (int)($a->type > $b->type);
        });

        $vars['available_record_types'] = $module->getAvailableRecordTypes();
        $vars['ttl_disabled'] = !$module->isTTLEnabled();
        $vars['show_full_record_name'] = GlobalSettingHelper::getSetting(GlobalSettingEnum::SHOW_FULL_RECORD_NAME);

        return AjaxResponse::I()->modal('edit-zone', $vars)->toArray();
    }
    
    public function addNewRecordJSON($input, $vars = array()) {
        $class = 'MGModule\DNSManager2\mgLibs\custom\dns\record\type\\' . $input['new_record_type'];
        if(class_exists($class)) {
            $zone = new zone\Zone($input['id']);
            $package = $zone->getPackage();
            if(!$package)
            {
                return AjaxResponse::I()->addRawError(main\mgLibs\lang::T('package_not_found'))->toArray();
            }
            $packageSettings = $package->getSettings('default_ttl');
            $packageSettings = unserialize($packageSettings);

            $vars['ttl_default_value'] = $packageSettings[$input['new_record_type']];
            if(empty($vars['ttl_default_value']))
                $vars['ttl_default_value'] = 14440;
            $vars['ttl_disabled'] = $input['ttl_disabled'] == 1;
            $vars['counter'] = $input['records_counter'];
            $vars['record_type'] = $input['new_record_type'];
            $vars['record_obj'] = new $class();
            $vars['record_fields'] = get_object_vars($vars['record_obj']);

            $settingRepo = new main\models\custom\package\setting\Repository();
            $vars['recordsAllowedIp'] = $settingRepo->byKey('records_allowed_ip')->get()[0] == 'on';
            $vars['recordsBlacklist'] = $settingRepo->byKey('records_blacklist')->get()[0] == 'on';
            $helper = new ClientHelper($_SESSION['uid']);

            if($vars['recordsAllowedIp']) {
                $allowedIps = $helper->getPackageAllowedIps(intval($zone->relid), intval($zone->type));
                $allowedIps = IP::getAvailableIpList(json_decode($allowedIps['allowed_ips']));

                $vars['allowed_ipv4'] = IP::getOnlyIpv4($allowedIps);
                $vars['allowed_ipv4_flag'] = is_array($vars['allowed_ipv4']) && !empty($vars['allowed_ipv4']) && $vars['allowed_ipv4'][0] != null;
                $vars['allowed_ipv6'] = IP::getOnlyIpv6($allowedIps);
                $vars['allowed_ipv6_flag'] = is_array($vars['allowed_ipv6']) && !empty($vars['allowed_ipv6']) && $vars['allowed_ipv6'][0] != null;
            }

            if($vars['recordsBlacklist']) {
                $ipBlacklist = $helper->getPackageIpBlacklist(intval($zone->relid), intval($zone->type));
                $ipBlacklist = IP::getAvailableIpList(json_decode($ipBlacklist['ip_blacklist']));

                $vars['ipv4_blacklist'] = IP::getOnlyIpv4($ipBlacklist);
                $vars['ipv4_blacklist_flag'] = is_array($vars['ipv4_blacklist']) && !empty($vars['ipv4_blacklist']) && $vars['ipv4_blacklist'][0] != null;
                $vars['ipv6_blacklist'] = IP::getOnlyIpv6($ipBlacklist);
                $vars['ipv6_blacklist_flag'] = is_array($vars['ipv6_blacklist']) && !empty($vars['ipv6_blacklist']) && $vars['ipv6_blacklist'][0] != null;
            }
            if($input['type'] == 'PTR') {
                $vars['value'] = $zone->name;
            }

            AjaxResponse::I()->new_record = main\mgLibs\smarty::I()->view('new-record', 
                $vars, 
                main\addon::getModuleTemplatesDir().DS.'pages' . DS . main\addon::I()->page);
        } else {
            AjaxResponse::I()->addRawError(main\mgLibs\lang::T('cannot_find_class'). ' ' .$class);
        }
        
        return AjaxResponse::I()->toArray();
    }
    
    public function addNewRecordSaveJSON($input, $vars = array()) {
        $module = zone\Zone::factory($input['id'])->getModule();
        try {
            $zone = new zone\Zone($input['id']);
            $helper = new ClientHelper($_SESSION['uid']);
            $ipBlacklist = IP::getAvailableIpList(json_decode($helper->getPackageIpBlacklist(intval($zone->relid), intval($zone->type))['ip_blacklist']));
            $type = $input['add_record'][$input['records_counter']]['type'];
            if($type == 'A' || $type == 'AAAA') {
                $input['add_record'][$input['records_counter']]['field']['address'] =
                    $input['add_record'][$input['records_counter']]['field']['address'] ? : $input['add_record'][$input['records_counter']]['field']['0'];
            }
            $ip = $input['add_record'][$input['records_counter']]['field']['address'];

            //todo check if blacklist opt is on
            if($ip && !empty($ipBlacklist) && in_array($ip, $ipBlacklist) && $ipBlacklist[0] != null)
                return AjaxResponse::I()->addError('ip_on_blacklist')->toArray();

            $zoneLoggerManager = new ZoneLoggerManager();
            foreach($input['add_record'] as $counter => $record_data) {
                $record = $this->createRecordFromInput($record_data);
                //todo przenieść kiedyś do addRecord
                $module->validateRecord($record);
                $record->nameToAbsolute($zone->name);

                $module->addRecord($record);
                $zoneLoggerManager->logAddRecordToZone($zone, $record);
            }

            EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_ALTERED_NOTIFICATION, $input['id'], ['zone_name' => $zone->name]);
//            LogHelper::addSuccessLogUsingZoneID('Edit Zone', '', $input['id']);
            
            return $this->editZoneJSON($input, $vars);
        } catch (Exception $exc) {
            LogHelper::addFailLogUsingZoneID('Edit Zone', $exc->getMessage(), $input['id']);
            AjaxResponse::I()->addRawError($exc->getMessage());
            return AjaxResponse::I()->toArray();
        }
    }
    
    public function editZoneSaveJSON($input, $vars = array())
    {
        $zone = zone\Zone::factory($input['id']);
        $module = $zone->getModule();

        try
        {
            $module->moduleConvertInputFormData($input);
            $oldRecords = RecordSetHelper::formatRecordsToIndexById($module->getRecords());
            if(!$module->customEditRecords($input))
            {
                foreach($input['edit_record'] as $counter => $record_data)
                {
                    $record = $this->createRecordFromInput($record_data);
                    $record->nameToAbsolute($zone->name);
                    $module->editRecord($record);

                    $editRecordHelper  = new custom\helpers\ZoneLogger\Actions\EditRecord($record, $oldRecords[$record->line]);
                    $zoneLoggerManager = new ZoneLoggerManager();
                    $zoneLoggerManager->logEditRecordsInZone($zone, $editRecordHelper);
                }
            }

            if(count($input['edit_record']) > 0) {
                $zone = new zone\Zone($input['id']);
                EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_ALTERED_NOTIFICATION, $input['id'], ['zone_name' => $zone->name]);
//                LogHelper::addSuccessLogUsingZoneID('Edit Zone', '', $input['id']);
            }
            
            AjaxResponse::I()->addInfo('changes_saved');
        } catch (Exception $exc) {
            LogHelper::addFailLogUsingZoneID('Edit Zone', $exc->getMessage(), $input['id']);
            AjaxResponse::I()->addRawError($exc->getMessage());
            return AjaxResponse::I()->toArray();
        }
        
        return AjaxResponse::I()->toArray();
    }

    public function lockZoneJSON( $input, $vars = [] )
    {
        try
        {
            /** @var zone\Zone $zone */
            $zone = zone\Zone::factory($input['id']);
            $zone->setLocked();
        }
        catch (Exception $exc)
        {
            LogHelper::addFailLogUsingZoneID('Lock Zone', $exc->getMessage(), $input['id']);
            AjaxResponse::I()->addRawError($exc->getMessage());

            return AjaxResponse::I()->toArray();
        }
        AjaxResponse::I()->addInfo('Zone Locked');

        return AjaxResponse::I()->refreshPage($this->indexHTML($input, $vars))->toArray();
    }

    public function unlockZoneJSON( $input, $vars = [] )
    {
        try
        {
            /** @var zone\Zone $zone */
            $zone = zone\Zone::factory($input['id']);
            $zone->setUnlocked();
        }
        catch (Exception $exc)
        {
            LogHelper::addFailLogUsingZoneID('Lock Zone', $exc->getMessage(), $input['id']);
            AjaxResponse::I()->addRawError($exc->getMessage());

            return AjaxResponse::I()->toArray();
        }
        AjaxResponse::I()->addInfo('Zone Unlocked');

        return AjaxResponse::I()->refreshPage($this->indexHTML($input, $vars))->toArray();
    }

    public function removeZoneRecordJSON($input, $vars = array()) {

        $record_data = array_pop($input['record']);
        
        if(empty($record_data))
        {
            $record_data = array_pop($input['edit_record']);
        }
        
        $module = zone\Zone::factory($input['id'])->getModule();
        
        $record = $this->createRecordFromInput($record_data);
        
        try {
            $zone = new zone\Zone($input['id']);
            $module->deleteRecord($record);

            $zoneLoggerManager = new ZoneLoggerManager();
            $zoneLoggerManager->logRemoveRecordFromZone($zone, $record);

            EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_ALTERED_NOTIFICATION, $input['id'], ['zone_name' => $zone->name]);
//            LogHelper::addSuccessLogUsingZoneID('Edit Zone', '', $input['id']);
        } catch (Exception $exc) {
            LogHelper::addFailLogUsingZoneID('Edit Zone', $exc->getMessage(), $input['id']);
            throw $exc;
        }
        
        AjaxResponse::I()->addInfo('record_removed');
        return $this->editZoneJSON($input, $vars);
    }

    //dodac parametr moduł dns
    private function createRecordFromInput($input) {
        $record = Record::tryToCreateFromArray($input);
        $record->rdata->setDataFromArray($input['field']);
        $record->decode();
        return $record;
    }
    
    public function removeZoneJSON($input, $vars = array()) { //ZAPYTAC MARUSZA O SZCZEGOLY - KIEDYS
        $zone = new zone\Zone($input['id']);
        $module = $zone->getModule();
        
        custom\helpers\StatusHelper::removeZoneStatus($input['id']);
        
        try {
            $module->terminateZone();
            $zoneLoggerManager = new ZoneLoggerManager();
            $zoneLoggerManager->logTerminateZoneAction($zone);
            EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_REMOVED_NOTIFICATION, $input['id'], ['zone_name' => $zone->name]);
        } catch (Exception $exc) {
            LogHelper::addFailLogUsingZone('Remove Zone', $exc->getMessage(), $zone);
            throw $exc;
        }

        $zone->setThatNotExist();
        
        AjaxResponse::I()->addInfo("zone_removed_from_server");
        return AjaxResponse::I()->toArray();
    }
    
    public function createZoneJSON($input, $vars = array())
    {
        $zone = new zone\Zone($input['id']);
        if(!$zone->getServer() || !$zone->getServer()->isEnabled())
        {
            AjaxResponse::I()->addError("server_disabled_or_not_exists", ['server' => $zone->getServer() ? $zone->getServer()->name : '']);
            return AjaxResponse::I()->toArray();
        }
        try
        {
            $module = $zone->getModule();
            if(!$module->zoneExists())
            {
                $zone->getModule()->activateZone();
                
                $setHelper = new main\mgLibs\custom\helpers\RecordSetHelper($zone, new main\mgLibs\custom\helpers\ZoneLogger\Manager());
                $setHelper->addRecordSet();

                EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_CREATED_NOTIFICATION, $input['id'], ['zone_name' => $zone->name]);
            }
            
            $zone->setThatExist();

//            LogHelper::addSuccessLogUsingZoneID('Add Zone', '', $input['id']);
        }
        catch(Exception $exc)
        {
            LogHelper::addFailLogUsingZone('Add Zone', $exc->getMessage(), $zone);
            throw $exc;
        }
        
        AjaxResponse::I()->addInfo("zone_created");
        return AjaxResponse::I()->toArray();
    }
    
    public function synchronizeZoneJSON($input, $vars = array()) {
        $zone = new zone\Zone($input['id']);

        try {
            $module = $zone->getModule();
            if (!$module->zoneExists()) {
                $zone->setThatNotExist();
                //$module->activateZone();
                //EmailNotificationHelper::sendClientNotificationUsingZoneID(DefaultNotifications::GENERAL_ZONE_CREATED_NOTIFICATION, $input['id']);
            } else {
                $zone->setThatExist();
            }
            
            LogHelper::addSuccessLogUsingZoneID('Synchronize Zone', '', $input['id']);
        } catch (Exception $exc) {
            LogHelper::addFailLogUsingZone('Synchronize Zone', $exc->getMessage(), $zone);
            throw $exc;
        }
        
        AjaxResponse::I()->addInfo("zone_synchronized");
        return AjaxResponse::I()->toArray();
    }
    
    public function removeZoneFromWHMCSJSON($input, $vars = array()) {
        zone\Zone::factory($input['id'])->delete();
        
        custom\helpers\StatusHelper::removeZoneStatus($input['id']);

        AjaxResponse::I()->refreshPage($this->indexHTML($input, $vars));
        AjaxResponse::I()->addInfo("zone_removed_from_whmcs");
        return AjaxResponse::I()->toArray();
    }
    
    public function switchRelatedItemJSON($input, $vars = array()) {
        $zone =  new zone\Zone($input['id']);
        $vars['id'] = $input['id'];
        $vars['items'] = $this->getClientRelatedItems($zone->clientid);
        $vars['type'] = $zone->type;
        $vars['relid'] = $zone->relid;
        
        return AjaxResponse::I()->modal('switch-item', $vars)->toArray();
    }
    
    public function switchRelatedItemSaveJSON($input, $vars = array()) {
        list($type, $relid) = explode('|', $input['relateditem']);
        $zone = new zone\Zone($input['id']);
        $zone->type = $type;
        $zone->relid = $relid;
        $zone->save();
        
        return AjaxResponse::I()->addInfo('success')->toArray();
    }
    
    private function getClientRelatedItems($clientid) {
        $helper = new ClientHelper($clientid);
        $groups = $helper->getGroups();

        $out = array();
        foreach($groups as $name => $group) {
            $item = current($group);
            $out[] = array(
                'name' => $name,
                'type' => $item['type'],
                'relid' => $item['relid'],
                'ips_available' => IP::getAvailableIpList(json_decode($item['ips_available'])),
                'ip_blacklist' => IP::getAvailableIpList(json_decode($item['blacklist']))
            );
        }
        
        return $out;
    }
    
    public function exportZoneToFileJSON($input, $vars = array())
    {
        $zone = new zone\Zone($input['id']);
        $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'singleZones');

        $vars['id'] = $zone->id;
        $vars['zone_name'] = $zone->name;
        $vars['isWritable'] = $fileManager->isStorageWritable();
        $vars['isReadable'] = $fileManager->isStorageReadable();
        $vars['storagePath'] = $fileManager->getStoragePath();
        
        $vars['newFileName'] = main\mgLibs\custom\helpers\ImportExportFileHelper::generateNewExportFileName($zone->name);
       
        return AjaxResponse::I()->modal('export-zone', $vars)->toArray();
    }
    
    public function confirmExportToFileJSON($input, $vars = array())
    {
        try
        {
            main\mgLibs\custom\helpers\ImportExportFileHelper::exportZoneToFile($input['id'], 'zonesFilesStorage'.DIRECTORY_SEPARATOR.'singleZones', $input['fileName']);
        }
        catch(\Exception $exc)
        {
            LogHelper::addFailLogUsingZoneID('Export Zone', $exc->getMessage(), $input['id']);
            throw $exc;
        }
               
        return AjaxResponse::I()->addInfo('zoneSuccessfullyExported')->toArray();
    }
    
    public function importZoneFromFileJSON($input, $vars = array())
    {
        try
        {
            $zone = new zone\Zone($input['id']); 
            $fileManager = new main\mgLibs\custom\FileManager('zonesFilesStorage'.DIRECTORY_SEPARATOR.'singleZones');
            
            $filesList = main\mgLibs\custom\helpers\ImportExportFileHelper::listFilesForZone($zone, $fileManager);
            
            $vars['isReadable'] = $fileManager->isStorageReadable();
            $vars['storagePath'] = $fileManager->getStoragePath();  
        }
        catch(\Exception $exc)
        {
            LogHelper::addFailLogUsingZoneID('Import Zone', $exc->getMessage(), $input['id']);
            throw $exc;
        }
        
        $vars['id'] = $zone->id;
        $vars['filesList'] = $filesList;
       
        return AjaxResponse::I()->modal('import-zone', $vars)->toArray();        
    }
    
    public function confirmImportFromFileJSON($input, $vars = array())
    {
        try
        {
            $zone = new zone\Zone($input['id']);
            $backupZone = main\mgLibs\custom\helpers\ImportExportFileHelper::loadFileContent('zonesFilesStorage'.DIRECTORY_SEPARATOR.'singleZones', $input['fileNameForImport']);
            $zoneUpdateHelper = new main\mgLibs\custom\helpers\ZoneUpdateHelper($zone, $backupZone, new ZoneLoggerManager($zone->clientid));
            $zoneUpdateHelper->update();
        }
        catch(\Exception $exc)
        {
            LogHelper::addFailLogUsingZoneID('Import Zone', $exc->getMessage(), $input['id']);
            throw $exc;            
        }
        
        return AjaxResponse::I()->addInfo('zoneSuccessfullyImported')->toArray();       
    }
    
    private function getClients()
    {
        $clients    = ClientHelper::getAllClients(); 
        return $clients;
    }
    
    private function getAdminSets()
    {
        $adminSets   = set\Repository::factory()->adminOnly()->get();
        return $adminSets;
    }
    
    private function getClientSets($clientid)
    {
        $clientSets = set\Repository::factory()->byUserId((int)$clientid)->get();
        return $clientSets;
    }
    
    public function addZoneJSON($input, $vars = array())
    {
        $adminSets   = $this->getAdminSets();

        $vars['adminSets']  = $adminSets;
        
        return AjaxResponse::I()->modal('add-zone', $vars)->toArray();
    }
    
    public function addZoneSaveJSON($input, $vars = array())
    {
        $item = explode("|" , $input['relateditem']);
        $input['type']  = $item[0];
        $input['relid'] = $item[1];
		$ip = $input['zone_ip'];
		$helper = new ClientHelper($_SESSION['uid']);

        try
        {
            $allowedIps = IP::getAvailableIpList(json_decode($helper->getPackageAllowedIps($item[1], $item[0])['allowed_ips']));
            if ( is_array($allowedIps) && !empty($allowedIps) && $allowedIps[0] != null)
            {
                if ( !in_array($ip, $allowedIps) )
                {
                    return AjaxResponse::I()->addError('not_allowed_ip')->toArray();
                }
            }

            $ipBlacklist = json_decode($helper->getPackageIpBlacklist($item[1], $item[0])['ip_blacklist']);
            if (in_array($ip, $ipBlacklist) && !empty($ipBlacklist) && $ipBlacklist[0] != null)
            {
                return AjaxResponse::I()->addError('ip_on_blacklist')->toArray();
            }

            $creator = new ZoneCreator($input['zone_name'], $input['type'], $input['relid'], $input['zone_ip'], $input['client']);
            $creator->setZoneLoggerManager(new ZoneLoggerManager($_SESSION['uid']));
            $ret = $creator->create($input['recordSet']);

            if(is_string($ret))
            {
                return AjaxResponse::I()->addRawError($ret)->toArray();
            }

            AjaxResponse::I()->addInfo('zone_created_successfully');
        }
        catch(Exception $exc)
        {
            return AjaxResponse::I()->addRawError($exc->getMessage())->toArray();
        }

        return AjaxResponse::I()->refreshPage($this->indexHTML($input))->toArray();
    }

    private function tryGetDefaultIP($domainID, $typeID){
        if($domainID == null)
            return '';

        switch($typeID){
            case ZoneTypeEnum::DOMAIN:
                $domain = new main\models\whmcs\domains\domain($domainID);
                break;
             case ZoneTypeEnum::HOSTING:
                 $domain = new main\models\whmcs\service\service($domainID);
                 break;
            case ZoneTypeEnum::ADDON:
                $domain = (new main\models\whmcs\hostingaddon\hostingaddon($domainID))->getHostingModel();
                break;
        }

        $defaultIPMethods = new DefaultIPHelper();

        $ip = $defaultIPMethods->getDefaultIpBySpecificDomain($domain, $typeID);
        if($ip)
            return $ip;
        else
            return '';
    }

    public function getClientServicesJSON($input, $vars = array())
    {
        $clientInput    = explode("|" , $input['client']);
        $clientid       = $clientInput[0];
        $currentName    = $clientInput[1];

        $gropus         = $this->getClientRelatedItems($clientid);

        if(empty($input['relateditem']))
        {
            $type = $gropus[0]['type'];
            $relid = $gropus[0]['relid'];

            $input['relateditem'] = [
                'type' => $type ? $type : 0,
                'relid' => $relid ? $relid : 0,
            ];

            $vars['defaultIP'] = $this->tryGetDefaultIP($relid, $type);
        }

        if(!empty($input['relateditem'])){
            $item = explode('|', $input['relateditem']);
            $zoneSetting = custom\helpers\ZoneSettings::getZoneItemSettingForType($item[0]);

            $vars['relateditem']   = [
                'type' => $item[0],
                'relid' => $item[1],
            ];

            $adminSets      = $this->getReletedSets($item[1], $item[0]);

            if($item[1] != 0)
                $vars['defaultIP'] = $this->tryGetDefaultIP($item[1], $item[0]);

        }else{
            $adminSets      = $this->getReletedSets($gropus[0]['relid'], $gropus[0]['type']);
        }
        $clientSets     = $this->getClientSets($clientid);
        $sets           = array_merge($adminSets,$clientSets);

        if($zoneSetting)
        {
            $relId = $vars['relateditem']['relid'];
            $relType = $vars['relateditem']['type'];
            $vars['zoneDomainItems'] = custom\helpers\ZoneSettings::getProperlyItems($clientid, $relId, $relType);
        }

        $vars['currentClient']  = $currentName;
        $vars['currentId']      = $clientid;
        $vars['items']          = $gropus;
        $vars['sets']           = $sets;

        AjaxResponse::I()->modal('add-zone', $vars);

        return AjaxResponse::I()->toArray();
    }
    
    private function getReletedSets($productID = null, $type = null){

        if(is_null($productID) || $productID == 0){
            return [];
        }
        $zone = new \MGModule\DNSManager2\models\custom\zone\Zone();
        $zone->relid = $productID;
        $zone->type = $type;
        $zone->clientid = $zone->getRelatedItem()->clientID();
        $item = $zone->getPackage()->getAdminSets();;       
        if(is_array($item)){
            $setsArray = [];
            
            foreach($item as $itemID){
                $setsArray[] = \MGModule\DNSManager2\models\custom\set\Repository::factory()->byID($itemID)->one();
            }
            return $setsArray;
        }
        return [];
    }
    
    
    public function setRecordsJSON($input, $vars = array())
    {
        if(!array_filter($input['zone']['checked']))
        {
            return AjaxResponse::I()->addError('select_one_at_least')->toArray();
        }
        $adminSets      = $this->getAdminSets();
        $vars['sets']   = $adminSets;
        
        return AjaxResponse::I()->modal('set-records', $vars)->toArray();
    }

    public function setRecordsSaveJSON($input, $vars = array())
    {
        if(!$input['setRecord'])
        {
            return AjaxResponse::I()->addError('no_record_set_selected')->toArray();
        }
        $zones = $input['zone']['checked']; 
        $wipe  = $input['wipe'];
        $mainTask   = custom\TaskManager::addTask('DnsRecord:main',array('recordId' => $input['setRecord'] , 'zones' => $zones, 'wipe' => $wipe));
        
        AjaxResponse::I()->addInfo('set_added_successfully');
        
        return AjaxResponse::I()->refreshPage($this->indexHTML($input))->toArray();
    }
    
    //mass remove
    
    public function massRemoveZonesJSON($input, $vars = []){

        if(!array_filter($input['zone']['checked']))
        {
            return AjaxResponse::I()->addError('select_one_at_least')->toArray();
        }
        $sets = [];
        foreach($input['zone']['checked'] as $index => $value){
            if($value == "on"){
                $sets[] = $index; 
            }
        }
        $vars['sets']   = json_encode($sets);
        
        return AjaxResponse::I()->modal('mass-remove-records', $vars)->toArray();
    
    }
    
    public function massRemoveZonesFromWHMCSJSON($input, $vars = []){

        if(!array_filter($input['zone']['checked']))
        {
            return AjaxResponse::I()->addError('select_one_at_least')->toArray();
        }
        $sets = [];
        foreach($input['zone']['checked'] as $index => $value){
            if($value == "on"){
                $sets[] = $index; 
            }
        }
        $vars['sets']   = json_encode($sets);
        
       return AjaxResponse::I()->modal('mass-remove-for-whmcs-records', $vars)->toArray();
    
    }

    private function getPTRRecords($zone) {
        $out = array();
        foreach(reverse\Repository::factory()->from($zone->getServer()->id, $zone->name)->byClientID($zone->clientid)->get() as $data) {
            $ptr = new main\mgLibs\custom\dns\record\Record();
            $ptr->name  = custom\dns\utils\ReverseDNSHelper::reverseRecordName($data->ip) . '.' . $data->name;
            $ptr->type  = 'PTR';
            $ptr->ttl   = $data->ttl;
            $ptr->ip    = $data->ip;
            $ptr->createRDATAObject('PTR');
            $ptr->rdata->setFirstProperty(empty($data->sub)?$data->from:$data->sub . '.' . $data->from);
            $out[] = $ptr;
        }
        return $out;
    }
    
}

