<?php

use \MGModule\DNSManager2 as main;
use \MGModule\DNSManager2\mgLibs\custom\manager\ZoneAutomationHelper;
use \MGModule\DNSManager2\mgLibs\custom\manager\GlobalSettingHelper;
use \MGModule\DNSManager2\models\custom\globalsetting\GlobalSettingEnum;
use \MGModule\DNSManager2\mgLibs\custom\helpers;
use \MGModule\DNSManager2\models\custom\package;
use \MGModule\DNSManager2\models\custom\reverse;
use \MGModule\DNSManager2\mgLibs\custom\reverse\ReverseDNS;

defined('WHMCS6') or define('WHMCS6', isset($GLOBALS['CONFIG']['Version']) && version_compare($GLOBALS['CONFIG']['Version'], '6.0.0', '>='));


if(!defined('DS'))define('DS',DIRECTORY_SEPARATOR);
try
{
    require_once __DIR__.DIRECTORY_SEPARATOR.'loader.php';
    $loader = new main\loader();

    helpers\RegistrarDNSHelper::prepareRegisrtrar();
}
catch(Exception $ex)
{
    logModuleCall(
        'DNS Manager', __FUNCTION__, $ex->getMessage(), $ex->getMessage(), $ex->getTraceAsString()
    );
}    

add_hook('AddonActivation', 1, 'DNSManager2AddonActivationHook');
function DNSManager2AddonActivationHook($params)
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    try
    {
        main\addon::I(true);
        
        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::ADDON_ACTIVATION, $params['params']?:$params);
        $helper->run();

    } 
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('AfterModuleCreate', 1, 'DNSManager2AfterModuleCreateHook');
function DNSManager2AfterModuleCreateHook($params)
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    try
    {
        main\addon::I(true);
        
        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::PRODUCT_CREATE, $params['params']?:$params);
        $helper->run();
    } 
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('PreRegistrarRegisterDomain', 1, 'DNSManager2PreRegistrarRegistrationHook');
function DNSManager2PreRegistrarRegistrationHook( $params )
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    try
    {
        main\addon::I(true);

        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_REGISTRATION, $params['params'] ? : $params);

        if($helper->getCreator()->getPackage() !== false)
        {
            if((string)$helper->getCreator()->getPackage()->getSettings(package\setting\PackageSettingEnum::ZONE_AUTOMATION_PENDING_REGISTRATION_DOMAIN_TIME) === 'Pre')
            {
                $helper->run();

                if ( $params['params']['dnsmanagement'] ? : $params['dnsmanagement'] )
                {
                    $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_WITH_DNS_MANAGEMENT, $params['params'] ? : $params);
                    $helper->run();
                }
            }
        }
    }
    catch (Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('AfterRegistrarRegistration', 1, 'DNSManager2AfterRegistrarRegistrationHook');
function DNSManager2AfterRegistrarRegistrationHook($params) 
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    try
    {
        main\addon::I(true);

        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_REGISTRATION, $params['params'] ? : $params);

        if($helper->getCreator()->getPackage() !== false)
        {
            if((string)$helper->getCreator()->getPackage()->getSettings(package\setting\PackageSettingEnum::ZONE_AUTOMATION_PENDING_REGISTRATION_DOMAIN_TIME) !== 'Pre')
            {
                $helper->run();

                if ( $params['params']['dnsmanagement'] ? : $params['dnsmanagement'] )
                {
                    $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_WITH_DNS_MANAGEMENT, $params['params'] ? : $params);
                    $helper->run();
                }
            }
        }

    }
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('AfterRegistrarTransfer', 1, 'DNSManager2AfterRegistrarTransferHook');
function DNSManager2AfterRegistrarTransferHook($params) 
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();
    
    try
    {
        main\addon::I(true);
        
        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_TRANSFER, $params['params']?:$params);
        if($helper->getCreator()->getPackage() != false)
        {
            if((string)$helper->getCreator()->getPackage()->getSettings(package\setting\PackageSettingEnum::ZONE_AUTOMATION_PENDING_TRANSFER_DOMAIN_TIME) === 'After')
            {
                $helper->run(); 
            }  
        }
    } 
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('PreRegistrarTransferDomain', 1, 'DNSManager2PreRegistrarTransferDomainHook');
function DNSManager2PreRegistrarTransferDomainHook($params) 
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();
    
    try
    {
        main\addon::I(true);
        
        $helper = new ZoneAutomationHelper(ZoneAutomationHelper::DOMAIN_TRANSFER, $params['params']?:$params);
        if($helper->getCreator()->getPackage() != false)
        {
            if((string)$helper->getCreator()->getPackage()->getSettings(package\setting\PackageSettingEnum::ZONE_AUTOMATION_PENDING_TRANSFER_DOMAIN_TIME) === 'Pre')
            {
                $helper->run(); 
            }
        }
        
    } 
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('AddonTerminated', 1, 'DNSManager2AddonTerminatedHook');
function DNSManager2AddonTerminatedHook($params) 
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    isset($params['params'])?$params=$params['params']:'';

    try
    {
        main\addon::I(true);
        
        DNSManager2RemoveZones(main\models\custom\zone\ZoneTypeEnum::ADDON, $params['id'], $params['userid']);
        
    }
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

add_hook('AfterModuleTerminate', 1, 'DNSManager2AfterModuleTerminateHook');
function DNSManager2AfterModuleTerminateHook($params)
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    isset($params['params'])?$params=$params['params']:'';

    if($params['model'] instanceof WHMCS\Service\Addon)
    {
        $params['id'] = $params['addonId'];
        DNSManager2AddonTerminatedHook($params);
        return;
    }

    try
    {
        main\addon::I(true);
        if(GlobalSettingHelper::getSetting(GlobalSettingEnum::PREVENT_ZONE_DELETE_AFTER_TERMINATE)){
            return;
        }

        DNSManager2RemoveZones(main\models\custom\zone\ZoneTypeEnum::HOSTING, $params['serviceid'], $params['userid']);
        
    }
    catch (Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

function DNSManager2RemoveZones($type, $relid, $clientid)
{
    $rep = new main\models\custom\zone\Repository();

    $reverses = reverse\Repository::factory()->byServiceTypeAndRelidAndClient($type, $relid, $clientid)->get();

    foreach ($reverses as $reverse)
    {
        try
        {
            if ($reverse !== FALSE)
            {
                $rdns = new ReverseDNS($reverse);
                $rdns->remove();

                main\mgLibs\custom\manager\LogHelper::addSuccessLog('Remove Reverse DNS', 'Reverse DNS has been deleted', $reverse->getFullDomain(), $clientid);
            }
        }
        catch (Exception $e)
        {
            main\mgLibs\custom\manager\LogHelper::addFailLog('Remove Reverse DNS', $e->getMessage(), $reverse->getFullDomain(), $clientid);
        }

    }

    foreach($rep->getZonesWith($type, $relid, $clientid) as $zone)
    {
        try
        {
            if($zone->getModule()->zoneExists())
            {
                $zone->getModule()->terminateZone();
            }
            $zone->delete();
            main\mgLibs\custom\manager\LogHelper::addSuccessLogUsingZone('Remove Zone', '-', $zone);
            main\mgLibs\custom\manager\EmailNotificationHelper::sendClientNotificationUsingZone(main\mgLibs\custom\manager\DefaultNotifications::GENERAL_ZONE_REMOVED_NOTIFICATION, $zone, ['zone_name' => $zone->name]);
        } 
        catch (Exception $e)
        {
            main\mgLibs\custom\manager\LogHelper::addFailLogUsingZone('Remove Zone', $e->getMessage(), $zone);
            main\mgLibs\custom\manager\NotificationHelper::addProblemNotification('Zone creation failed ('. $zone->name .')');
        }
    }
}

add_hook('ClientAreaPrimaryNavbar', 1, DNSManager2ClientAreaPrimaryNavbar); 
function DNSManager2ClientAreaPrimaryNavbar($vars)
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    new main\loader();

    try 
    {
        main\addon::I(true);

        if(!empty($_SESSION['uid']) && GlobalSettingHelper::getSetting(GlobalSettingEnum::LINK_TO_DNS_MANAGER))
        {
            $navs = $vars->getChildren();
            $dom = $navs['Domains'];
            if(!$dom)
            {
                $dom = $navs['Services'];
                if (!$dom)
                {
                    return;
                }
            }
            
            $bId = main\mgLibs\lang::absoluteT('manage_dns');
            $dom->addChild($bId);
            $managerLink = $dom->getChild($bId);
            $managerLink->setUri("index.php?m=DNSManager2"); 
            $managerLink->setOrder(21);
        }
    } 
    catch(Exception $ex)
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

if(WHMCS6) 
{
  // add_hook('ClientAreaSecondarySidebar', 1, 'DNSManager2ClienAreaSidebarHook'); //dla domen
    add_hook('ClientAreaPrimarySidebar', 1, 'DNSManager2ClienAreaSidebarHook'); //dla serwisów
    
    function DNSManager2ClienAreaSidebarHook($sidebar)
    {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
        $loader = new main\loader();

        try
        {          
            $availableOnPage = [
                'productdetails',
                'domaindetails',
                'domaincontacts',
                'domainregisterns',
                'domaingetepp',
                'domaindns'
            ];
                  
            main\addon::I(true);
            if(isset($_GET['action']) && in_array($_GET['action'], $availableOnPage) && (isset($_GET['id']) || isset($_GET['domainid']))) 
            {

                if($_GET['action'] == 'productdetails')
                {
                    $dnsManagerLinkName = main\mgLibs\lang::absoluteT('dns_manager');

                    $showDNSManagerButton = GlobalSettingHelper::getSetting(GlobalSettingEnum::SHOW_DNSMANAGERBUTTON);

                    if($showDNSManagerButton == 'on') {
                        $thisService = new main\models\whmcs\service\service($_GET['id']);
                        $zone = \MGModule\DNSManager2\models\custom\zone\Repository::factory()
                            ->byClientID($_SESSION['uid'])
                            ->byName($thisService->domain)
                            ->one();

                        if ($zone !== false) {
                            $sidebar->getChild('Service Details Actions')->addChild($dnsManagerLinkName);
                            $managerLink = $sidebar->getChild('Service Details Actions')->getChild($dnsManagerLinkName);
                            $managerLink->setUri("index.php?m=DNSManager2&mg-action=editZone&zone_id=" . $zone->id);
                            $managerLink->setOrder(100);
                        }
                    }

                    $actions = $sidebar->getChild('Service Details Actions');
                } 
                else 
                {
                    $id = ($_GET['id'])?: $_GET['domainid'];
                    $ob = \MGModule\DNSManager2\models\whmcs\domains\domain::factory($id);
                    $actions = $sidebar->getChild('Domain Details Actions');
                    
                    if(empty($actions))
                    {
                        $actions = $sidebar->getChild('Domain Details Management');
                    }
                }

                if(empty($actions)) 
                {
                    return ;
                }
                
                $domain = $ob->domain;
                
                $zone = \MGModule\DNSManager2\models\custom\zone\Repository::factory()
                    ->byClientID($_SESSION['uid'])
                    //->byRelID($_GET['id'])
                    ->byName($domain)
                    ->one();

                if($zone == false)
                {
                    return ;
                }

                if(empty($actions)) 
                {
                    return ;
                }

                $actions->addChild(
                    'manage_dns',
                    array(
                        'name' => 'manage_dns',
                        'label' => main\mgLibs\lang::absoluteT('manage_dns'),
                        'uri' => 'index.php?m=DNSManager2&mg-action=editZone&zone_id=' . $zone->id,
                        'order' => 99,
                    )    
                );
            }
        } 
        catch (Exception $ex)
        {
            main\mgLibs\error\register::register($ex);
            main\addon::dump($ex);
        }
    }
}

add_hook('ClientAreaPage', 1, 'DNSManager2ClientAreaPageHook');
function DNSManager2ClientAreaPageHook($params) 
{
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();

    try
    {
            $availableOnPage = [
                'productdetails',
                'domaindetails',
                'domaincontacts',
                'domainregisterns',
                'domaingetepp',
                'domaindns'
            ];

        if(in_array($params['clientareaaction'], $availableOnPage)) 
        {

            $zone = \MGModule\DNSManager2\models\custom\zone\Repository::factory()
                ->byClientID($_SESSION['uid'])
                //->byRelID($_GET['id'])
                ->byName($params['domain'])
                ->one();

            if($zone !== false)
            {
                return array(
                    'dns_manager_link' => 'index.php?m=DNSManager2&mg-action=editZone&zone_id=' . $zone->id,
                    'dns_manager_is_active' => true
                );
            }
        }
    } 
    catch(Exception $ex) 
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }
}

//WHMCS Client Merge
function DNSManager2ClientMerge($vars){
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'loader.php';
    $loader = new main\loader();
    try
    {
        main\addon::I(true);
        helpers\ClientMergeHelper::merge($vars['fromUserID'], $vars['toUserID']);
    } 
    catch(Exception $ex) 
    {
        main\mgLibs\error\register::register($ex);
        main\addon::dump($ex);
    }  
}
add_hook('AfterClientMerge', 1, 'DNSManager2ClientMerge');


try {
    
\MGModule\DNSManager2\mgLibs\custom\helpers\TransferHelper::transferZone($_REQUEST);
} catch (\Exception $ex) {
    
}