<?php

require_once 'modules/admin/views/public/SignupView.php';
require_once 'modules/admin/models/Package.php';
require_once 'modules/billing/models/Currency.php';
include_once 'modules/admin/models/PluginGateway.php';
include_once 'modules/admin/models/ServerGateway.php';

/**
* @package Admin
*/
class ViewdomainSearchResults extends SignupView
{
    var $permission     = '';
    var $showHeader = false;
    var $currencys    = null;

    /**
    * @return int possible return values:
    *       -1:    Domain name already has an account in this system
    *       0:     Domain available
    *       1:     Domain already registered
    *       2:     Registrar Error, domain extension not recognized or supported
    *       3:     Domain invalid
    *       5:     Could not contact registry to look up domain
    */

    function dispatch()
    {

        $this->initialize();

        // Init some vars
        $this->templateInit();
        $this->currencys = new Currency($this->user);

        // Check the domain
        if(!@$_REQUEST['name'] || !@$_REQUEST['tld'] || !@$_REQUEST['product'] || !@$_REQUEST['searchType']) {

            // Set error and stop execution
            $this->tplView->domainError = $this->lang("Please ensure that you have entered a domain to search for.");
            $this->tplView->display('domainSearchResults.tpl.php');
            exit;
        }

        // Preset some global TPL vars
        $this->tplView->domainError = false;
        $this->tplView->searchType = $_REQUEST['searchType'];
        $this->tplView->domainName = htmlentities($_REQUEST['name'].".".$_REQUEST['tld']);
        $this->tplView->requestTld = $_REQUEST['tld'];
        $this->tplView->domainNameSuggest = false;
        $this->tplView->domainStatus = '-2';
        $this->tplView->transferCheckList = $this->settings->get('Force Transfer Checklist');

        // Start logging
        $this->logger->log(4, "Checking Domain ('".$_REQUEST['name']."', '".$_REQUEST['tld']."')");

        // Get the TLD's from the product
        $package = new Package($_REQUEST['product']);
        $tldData = unserialize($package->pricing);
        $tldData = @$tldData['pricedata'];
        $tldPlugin = @$tldData[$_REQUEST['tld']]['registrar'];
        $advancedSettings = @unserialize($package->advanced);

        // We handling a registration or a transfer?
        if($_REQUEST['searchType'] == 'register') {

            // Set the namesuggest return
            $maxNameSuggestResults = (isset($advancedSettings['maxNamesuggest']))?$advancedSettings['maxNamesuggest']:'5';
            $namesuggestTLds = array();
            $i = 1;
            // Loop the TLD's and add all other's to this array. Max of 10
            foreach($tldData AS $key => $value) {
                if($key != $_REQUEST['tld'] && $i != 10 && @$value['registrar'] == $tldPlugin) {
                    $namesuggestTLds[] = $key;
                }
                ++$i;
            }

            // Work out if we are even checking the domain information or just pretending its valid
            if ($this->settings->get('Check Domain Availability') == 1) {

		// Check if we have a plugin defined for the domain, if not use cWHOIS
                if(@$tldPlugin) {

                    // Check the domain with the plugins function
                    $this->logger->log(4, "Checking domain using ".$tldPlugin);

                    // Load the plugin
                    $pluginGateway = new PluginGateway();
                    $plugin = $pluginGateway->getPluginByName('registrars', $tldPlugin);

                    $registrarVariables = $plugin->getVariables();

                    $params = array();

                    foreach ($registrarVariables as $key => $var) {
                        $settingname = "plugin_".$tldPlugin."_".$key;
                        $params = array_merge($params, array( $key => $this->settings->get($settingname) ));
                    }

                    // Build the params
                    $params = array_merge(
                        $params, array(
                            'tld'   => $_REQUEST['tld'],
                            'sld'   => $_REQUEST['name'],
                            'namesuggest' => $namesuggestTLds
                        )
                    );

                    // Get the response & catch any exceptions
                    try {
                        $response = $plugin->checkDomain($params);
                    } catch (Exception $e) {
                        $this->tplView->domainError = $e->getMessage();
                        $this->tplView->display('domainSearchResults.tpl.php');
                        return;
                    }

                    if (!isset($advancedSettings['enableNamesuggest']) || $advancedSettings['enableNamesuggest'] == 0) {
                        $plugin->supportsNamesuggest = false;
                    }

                    // Parse the results
                    if(@$response['result'] || @$plugin->supportsNamesuggest) {
                        if ( isset($advancedSettings['enableNamesuggest']) && $advancedSettings['enableNamesuggest'] == 1) {
                            $this->tplView->domainNameSuggest = true;
                        }
                        // See if we have namesuggest or not
                        if(@$response['result'][1] && $plugin->supportsNamesuggest) {
                            $domainStatus = $response['result'];
                        } else {
                            // We are just doing a standard lookup so work out the result
                            if(@$response[0]) {
                            // Old format of return
                                $domainStatus = @$response[0];
                            } else {
                                $domainStatus = @$response['result'][0]['status'];
                            }
                        }
                    } else {

                        // See if the plugin supports name suggest, if not it returns the status as an array
                        if(@$plugin->supportsNamesuggest == false) {
                            // Old format of return
                            $domainStatus = @$response[0];
                        } else {
                            // Log & set an error
                            $this->logger->log(4, "CheckDomain::callfunction FAILED result: " . print_r($response, true));
                            $this->tplView->domainError = $this->lang("There was an error contacting the registrar, please try again!");
                        }
                    }
                } else {

                    // Process with cWHOIS
                    $this->logger->log(4, "Checking domain using cWhois");

                    // Load cWHOIS
                    include 'newedge/classes/cWhois/cwhois.php';
                    $GLOBALS['dtd'] = $dtd; // cwhois searches this in the global scope...
                    $Reg="*";
                    $domainStatus = cWhois($_REQUEST['name'], '.' . $_REQUEST['tld'], $Reg);
                }

                // Parse the domain status here rather than tiwce above
                if(@is_array($domainStatus)) {

                    // Loop the domains to find the domain we actually searched for
                    // OpenSRS doesnt always return the domains in the order we asked for them
                    $actualIndex = 0;
                    $runningIndex = 0;
                    foreach($domainStatus AS $key) {
                        if($key['tld'] == $_REQUEST['tld']) {
                                $actualIndex = $runningIndex;
                        }
                        ++$runningIndex;
                    }

                    // We need to work out the status of the main domain
                    if(@$domainStatus[$actualIndex]['status'] == 1) {
                        $this->tplView->domainStatus = '1';


                        // Get transfer & self manage settings
                        $transfer = (isset($advancedSettings['allowTransfer']))?true:false;
                        $manage = (isset($advancedSettings['allowSelfManage']))?true:false;

                        // Handle the manage & transfer options
                        if($transfer && $manage) {
                            $this->tplView->allowTransfer = true;
                            $this->tplView->allowManage = true;
                            $this->tplView->transferOptions = true;

                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        } elseif($transfer && !$manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = true;
                            $this->tplView->allowManage = false;
                            // Unlock the submit button
                            $this->tplView->submitButton = "";

                        } elseif(!$transfer && $manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = false;
                            $this->tplView->allowManage = true;
                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        }
                        // Build array for TLD Pricing
                        $this->tplView->domainPricing = array();
                        if(is_array($tldData[$_REQUEST['tld']])) {
                            foreach ($tldData[$_REQUEST['tld']] AS $key) {
                                if(is_array($key)) {
                                    if(@$key['transfer'] !== ''){
                                        $key['transfer'] = $this->currencys->format($this->currency, @$key['transfer'], true, false, "NONE", true);
                                    }
                                    $this->tplView->domainPricing[] = $key;
                                }
                            }
                        }
                    } else {
                        $this->tplView->domainStatus = '0';
                    }
                    if ( $this->tplView->domainNameSuggest == true ) {
                        // Loop the returned domains
                        $i = 1;
                        $this->tplView->nameSuggestReturn = array();
                        $this->tplView->extraAttributesReturn = array();
                        foreach($domainStatus AS $key) {

                            // We only want to handle 5
                            if($i <= $maxNameSuggestResults || $key['tld'] == $_REQUEST['tld']) {

                                $workingArray = array();
                                $workingArray['tld'] = $key['tld'];
                                $workingArray['status'] = $key['status'];

                                // Handle the pricing
                                $pricingArray = array();
                                if(@is_array($tldData[$key['tld']])) {
                                    foreach ($tldData[$key['tld']] AS $keys) {
                                        if(is_array($keys)) {
                                            if(@$keys['price'] !== ''){
                                                $keys['price'] = $this->currencys->format($this->currency, @$keys['price'], true, false, "NONE", true);
                                            }
                                            $pricingArray[] = $keys;
                                        }
                                    }
                                }
                                $workingArray['price'] = @$pricingArray;
                                $workingArray['fromPrice'] = @$pricingArray[0]['price'];
                                $workingArray['searchedFor'] = false;


                                // Add to the array
                                if(@$workingArray['price'][0]) {
                                    // Add the searched for TLD first
                                    if($workingArray['tld'] == $_REQUEST['tld']) {
                                        $workingArray['searchedFor'] = true;
                                        $this->tplView->nameSuggestReturn = array_pad($this->tplView->nameSuggestReturn, -(count($this->tplView->nameSuggestReturn) + 1), $workingArray);
                                    } else {
                                        // Add it normally
                                        $this->tplView->nameSuggestReturn[] = $workingArray;
                                    }
                                    // Handle the extra attributes
                                    $extraAttributes = $package->getExtraAttributes($workingArray['tld']);

                                    // DO we have any?
                                    if(@is_array($extraAttributes)) {
                                        $this->tplView->extraAttributes = true;
                                        $attributesArray = array();
                                        $attributesArray['tld'] = $workingArray['tld'];
                                        if($workingArray['tld'] == $_REQUEST['tld']) {
                                            $attributesArray['visible'] = true;
                                        } else {
                                            $attributesArray['visible'] = false;
                                        }
                                        $attributesArray['attributes'] = $extraAttributes;
                                        $this->tplView->extraAttributesReturn[] = $attributesArray;
                                    }
                                    // Increment counter
                                    ++$i;
                                }
                            }
                        }
                        // Check we havent ended up with more than 5 entries
                        unset($this->tplView->nameSuggestReturn[5]);
                        // Unlock the submit button
                        $this->tplView->submitButton = "";
                    }

                } else {
                    // Parse a standard return
                    if(@$domainStatus == 0) {
                        // Domain is available
                        $this->tplView->domainStatus = '0';
                        // Build array for TLD Pricing
                        $this->tplView->domainPricing = array();
                        if(is_array($tldData[$_REQUEST['tld']])) {
                            foreach ($tldData[$_REQUEST['tld']] AS $key) {
                                if(is_array($key)) {
                                    if(@$key['price'] !== ''){
                                        $key['price'] = $this->currencys->format($this->currency, @$key['price'], true, false, "NONE", true);
                                    }
                                    $this->tplView->domainPricing[] = $key;
                                }
                            }
                            // Unlock the submit button here to prevent ordering a domain with no pricing
                            $this->tplView->submitButton = "";
                        }
                        // Get the extra attributes
                        $extraAttributes = $package->getExtraAttributes($_REQUEST['tld']);
                        // Do we have any?
                        if(@is_array($extraAttributes)) {
                            $this->tplView->extraAttributes = true;
                            $attributesArray = array();
                            $attributesArray['tld'] = $_REQUEST['tld'];
                            $attributesArray['visible'] = true;
                            $attributesArray['attributes'] = $extraAttributes;
                            $this->tplView->extraAttributesReturn[] = $attributesArray;
                        }

                    } elseif(@$domainStatus == 1) {

                        // Domain is not available. Check if we are doing duplicates
                        $this->tplView->domainStatus = '1';
                        // Get transfer & self manage settings
                        $transfer = (isset($advancedSettings['allowTransfer']))?true:false;
                        $manage = (isset($advancedSettings['allowSelfManage']) && $_REQUEST['bundling'] == true)?true:false;

                        // Handle the manage & transfer options
                        if($transfer && $manage) {
                            $this->tplView->allowTransfer = true;
                            $this->tplView->allowManage = true;
                            $this->tplView->transferOptions = true;

                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        } elseif($transfer && !$manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = true;
                            $this->tplView->allowManage = false;

                            // Unlock the submit button
                            $this->tplView->submitButton = "";
                        } elseif(!$transfer && $manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = false;
                            $this->tplView->allowManage = true;

                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        }

                        // Build array for TLD Pricing
                        $this->tplView->domainPricing = array();
                        foreach ($tldData[$_REQUEST['tld']] AS $key) {
                            if(is_array($key)) {
                                if(@$key['transfer'] !== ''){
                                    $key['transfer'] = $this->currencys->format($this->currency, @$key['transfer'], true, false, "NONE", true);
                                }
                                $this->tplView->domainPricing[] = $key;
                            }
                        }

                    } elseif(@$domainStatus == 3 || @$domainStatus == 2) {
                        $this->tplView->domainError = $this->lang("There was an error with the domain you entered, please try again!");
                    } else {
                        $this->tplView->domainError = $this->lang("There was an error contacting the registrar, please try again!");
                    }
                }
            } else {
                // Set the domain status to available manually
                $this->tplView->domainStatus = '0';
                // Build array for TLD Pricing
                $this->tplView->domainPricing = array();
                if(is_array($tldData[$_REQUEST['tld']])) {
                    foreach ($tldData[$_REQUEST['tld']] AS $key) {
                        if(is_array($key)) {
                            if(@$key['price'] !== ''){
                                $key['price'] = $this->currencys->format($this->currency, @$key['price'], true, false, "NONE", true);
                            }
                            $this->tplView->domainPricing[] = $key;
                        }
                    }
                }
            }

        } elseif($_REQUEST['searchType'] == 'transfer') {
            // Work out if we are even checking the domain information or just pretending its valid
            if ($this->settings->get('Check Domain Availability') == 1) {

		// Check if we have a plugin defined for the domain, if not use cWHOIS
                if(@$tldPlugin) {

                    // Check the domain with the plugins function
                    $this->logger->log(4, "Checking domain using ".$tldPlugin);

                    // Load the plugin
                    $pluginGateway = new PluginGateway();
                    $plugin = $pluginGateway->getPluginByName('registrars', $tldPlugin);

                    $registrarVariables = $plugin->getVariables();

                    $params = array();

                    foreach ($registrarVariables as $key => $var) {
                        $settingname = "plugin_".$tldPlugin."_".$key;
                        $params = array_merge($params, array( $key => $this->settings->get($settingname) ));
                    }

                    // Build the params
                    $params = array_merge(
                        $params, array(
                            'tld'   => $_REQUEST['tld'],
                            'sld'   => $_REQUEST['name']
                        )
                    );

                    // Get the response & catch any exceptions
                    try {
                        $response = $plugin->checkDomain($params);
                    } catch (Exception $e) {
                        $this->tplView->domainError = $e->getMessage();
                        $this->tplView->display('domainSearchResults.tpl.php');
                        return;
                    }

                    // on transfer, we aren't showing name suggestions
                    $plugin->supportsNamesuggest = false;

                    // Parse the results
                    if(@$response['result'] || @$plugin->supportsNamesuggest) {
                        if ( isset($advancedSettings['enableNamesuggest']) && $advancedSettings['enableNamesuggest'] == 1) {
                            $this->tplView->domainNameSuggest = true;
                        }
                        // See if we have namesuggest or not
                        if(@$response['result'][1] && $plugin->supportsNamesuggest) {
                            $domainStatus = $response['result'];
                        } else {
                            // We are just doing a standard lookup so work out the result
                            if(@$response[0]) {
                            // Old format of return
                                $domainStatus = @$response[0];
                            } else {
                                $domainStatus = @$response['result'][0]['status'];
                            }
                        }
                    } else {

                        // See if the plugin supports name suggest, if not it returns the status as an array
                        if(@$plugin->supportsNamesuggest == false) {
                            // Old format of return
                            $domainStatus = @$response[0];
                        } else {
                            // Log & set an error
                            $this->logger->log(4, "CheckDomain::callfunction FAILED result: " . print_r($response, true));
                            $this->tplView->domainError = $this->lang("There was an error contacting the registrar, please try again!");
                        }
                    }
                } else {

                    // Process with cWHOIS
                    $this->logger->log(4, "Checking domain using cWhois");

                    // Load cWHOIS
                    include 'newedge/classes/cWhois/cwhois.php';
                    $GLOBALS['dtd'] = $dtd; // cwhois searches this in the global scope...
                    $Reg="*";
                    $domainStatus = cWhois($_REQUEST['name'], '.' . $_REQUEST['tld'], $Reg);
                }

                // Parse the domain status here rather than tiwce above
                if(@is_array($domainStatus)) {

                    // Loop the domains to find the domain we actually searched for
                    // OpenSRS doesnt always return the domains in the order we asked for them
                    $actualIndex = 0;
                    $runningIndex = 0;
                    foreach($domainStatus AS $key) {
                        if($key['tld'] == $_REQUEST['tld']) {
                                $actualIndex = $runningIndex;
                        }
                        ++$runningIndex;
                    }

                    // We need to work out the status of the main domain
                    if(@$domainStatus[$actualIndex]['status'] == 1) {
                        $this->tplView->domainStatus = '1';


                        // Get transfer & self manage settings
                        $transfer = (isset($advancedSettings['allowTransfer']))?true:false;
                        $manage = (isset($advancedSettings['allowSelfManage']))?true:false;

                        // Handle the manage & transfer options
                        if($transfer && $manage) {
                            $this->tplView->allowTransfer = true;
                            $this->tplView->allowManage = true;
                            $this->tplView->transferOptions = true;

                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        } elseif($transfer && !$manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = true;
                            $this->tplView->allowManage = false;
                            // Unlock the submit button
                            $this->tplView->submitButton = "";

                        } elseif(!$transfer && $manage) {
                            $this->tplView->allowTransfer = false;
                            $this->tplView->transferOptions = false;
                            $this->tplView->allowManage = true;
                            if ( isset($serverNameServers) ) {
                                $this->tplView->defaultNameservers = $serverNameServers['data'];
                            } else {
                                $serverGateway = new ServerGateway();
                                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
                            }
                        }
                        // Build array for TLD Pricing
                        $this->tplView->domainPricing = array();
                        if(is_array($tldData[$_REQUEST['tld']])) {
                            foreach ($tldData[$_REQUEST['tld']] AS $key) {
                                if(is_array($key)) {
                                    if(@$key['transfer'] !== ''){
                                        $key['transfer'] = $this->currencys->format($this->currency, @$key['transfer'], true, false, "NONE", true);
                                    }
                                    $this->tplView->domainPricing[] = $key;
                                }
                            }
                        }
                    } else {
                        $this->tplView->domainStatus = '0';
                    }
                    if ( $this->tplView->domainNameSuggest == true ) {
                        // Loop the returned domains
                        $i = 1;
                        $this->tplView->nameSuggestReturn = array();
                        $this->tplView->extraAttributesReturn = array();
                        foreach($domainStatus AS $key) {

                            // We only want to handle 5
                            if($i <= $maxNameSuggestResults || $key['tld'] == $_REQUEST['tld']) {

                                $workingArray = array();
                                $workingArray['tld'] = $key['tld'];
                                $workingArray['status'] = $key['status'];

                                // Handle the pricing
                                $pricingArray = array();
                                if(@is_array($tldData[$key['tld']])) {
                                    foreach ($tldData[$key['tld']] AS $keys) {
                                        if(is_array($keys)) {
                                            if(@$keys['price'] !== ''){
                                                $keys['price'] = $this->currencys->format($this->currency, @$keys['price'], true, false, "NONE", true);
                                            }
                                            $pricingArray[] = $keys;
                                        }
                                    }
                                }
                                $workingArray['price'] = @$pricingArray;
                                $workingArray['fromPrice'] = @$pricingArray[0]['price'];
                                $workingArray['searchedFor'] = false;


                                // Add to the array
                                if(@$workingArray['price'][0]) {
                                    // Add the searched for TLD first
                                    if($workingArray['tld'] == $_REQUEST['tld']) {
                                        $workingArray['searchedFor'] = true;
                                        $this->tplView->nameSuggestReturn = array_pad($this->tplView->nameSuggestReturn, -(count($this->tplView->nameSuggestReturn) + 1), $workingArray);
                                    } else {
                                        // Add it normally
                                        $this->tplView->nameSuggestReturn[] = $workingArray;
                                    }
                                    // Handle the extra attributes
                                    $extraAttributes = $package->getExtraAttributes($workingArray['tld']);

                                    // DO we have any?
                                    if(@is_array($extraAttributes)) {
                                        $this->tplView->extraAttributes = true;
                                        $attributesArray = array();
                                        $attributesArray['tld'] = $workingArray['tld'];
                                        if($workingArray['tld'] == $_REQUEST['tld']) {
                                            $attributesArray['visible'] = true;
                                        } else {
                                            $attributesArray['visible'] = false;
                                        }
                                        $attributesArray['attributes'] = $extraAttributes;
                                        $this->tplView->extraAttributesReturn[] = $attributesArray;
                                    }
                                    // Increment counter
                                    ++$i;
                                }
                            }
                        }
                        // Check we havent ended up with more than 5 entries
                        unset($this->tplView->nameSuggestReturn[5]);
                        // Unlock the submit button
                        $this->tplView->submitButton = "";
                    }

                } else {
                    // Parse a standard return
                    if(@$domainStatus == 0) {
                        // Domain is available, so we can't transfer
                        $this->tplView->domainStatus = '0';
                        $this->tplView->submitButton = "";

                    } elseif(@$domainStatus == 1) {
                        // Domain is not available, that means we can transfer it.
                        $this->tplView->domainStatus = '1';

                        // Build array for TLD Pricing
                        $this->tplView->domainPricing = array();
                        if(is_array($tldData[$_REQUEST['tld']])) {
                            foreach ($tldData[$_REQUEST['tld']] AS $key) {
                                if(is_array($key)) {
                                    if(@$key['transfer'] !== ''){
                                        $key['transfer'] = $this->currencys->format($this->currency, @$key['transfer'], true, false, "NONE", true);
                                    }
                                    $this->tplView->domainPricing[] = $key;
                                }
                            }
                            // Unlock the submit button here to prevent ordering a domain with no pricing
                            $this->tplView->submitButton = "";
                        }
                        // Get the extra attributes
                        $extraAttributes = $package->getExtraAttributes($_REQUEST['tld']);
                        // Do we have any?
                        if(@is_array($extraAttributes)) {
                            $this->tplView->extraAttributes = true;
                            $attributesArray = array();
                            $attributesArray['tld'] = $_REQUEST['tld'];
                            $attributesArray['visible'] = true;
                            $attributesArray['attributes'] = $extraAttributes;
                            $this->tplView->extraAttributesReturn[] = $attributesArray;
                        }


                    } elseif(@$domainStatus == 3 || @$domainStatus == 2) {
                        $this->tplView->domainError = $this->lang("There was an error with the domain you entered, please try again!");
                    } else {
                        $this->tplView->domainError = $this->lang("There was an error contacting the registrar, please try again!");
                    }
                }
            } else {
                // Set the domain status to available manually
                $this->tplView->domainStatus = '0';
                // Build array for TLD Pricing
                $this->tplView->domainPricing = array();
                if(is_array($tldData[$_REQUEST['tld']])) {
                    foreach ($tldData[$_REQUEST['tld']] AS $key) {
                        if(is_array($key)) {
                            if(@$key['price'] !== ''){
                                $key['price'] = $this->currencys->format($this->currency, @$key['price'], true, false, "NONE", true);
                            }
                            $this->tplView->domainPricing[] = $key;
                        }
                    }
                }
            }

            // Handle domain addons here
            $domainAddons = $this->getAddons();
            if(count($domainAddons) != 0) {
                $this->tplView->domainHasAddons = true;
                $this->tplView->domainAddons = $domainAddons;
            }
        } elseif($_REQUEST['searchType'] == 'selfmanage') {
            // Check to see if we have a hosting product with this domain, and show the proper name servers
            $this->tplView->domainStatus = 1;
            if ( isset($_REQUEST['hosting_product']) && $_REQUEST['hosting_product'] != '' ) {
                $tempPackage = new Package($_REQUEST['hosting_product']);
                $servers = new ServerGateway();
                $serversList = $servers->getServersGridList();
                $serversList = $serversList['data'];
                $packageServers = $tempPackage->getProductServerIds();

                // Check we have some servers, now find one we can use
                if(is_array($serversList)) {
                    foreach($serversList as $server) {
                        // Check this server is assigned
                        if(isset($packageServers[$server['id']])) {
                            //check if serverid is not over quota
                            if($server['rawQuota'] == 0 || $server['rawQuota'] > $server['rawAmount']) {
                                $serverNameServers = $servers->getNameServers($server['id']);
                                break;
                            }
                        }
                    }
                }
            }

            // add them to the template
            if ( isset($serverNameServers) ) {
                $this->tplView->defaultNameservers = $serverNameServers['data'];
            } else {
                $serverGateway = new ServerGateway();
                $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();
            }
        } else {
            // Not sure what happened but we aren't doing a valid action so error
            $this->tplView->domainError = $this->lang("An unknown search error occurred.");
            $this->tplView->display('domainSearchResults.tpl.php');
            exit;
        }

        // don't show addons if we are self manage
        if ( $_REQUEST['searchType'] != 'selfmanage' ) {
            // Handle domain addons here
            $domainAddons = $this->getAddons();
            if(count($domainAddons) != 0) {
                $this->tplView->domainHasAddons = true;
                $this->tplView->domainAddons = $domainAddons;
            }
        }

        $this->tplView->customFields = $this->getCustomFields('package', $package);

        // Get customer country by his IP address or the default country if can't find it
        $this->tplView->DefaultCountry = $this->settings->get("Default Country");
        $ip = NE_Network::getRemoteAddr();
        if($ip !== false){
            $CountryCode = NE_Network::getCountryCodeFromIP($ip);
            if($CountryCode !== false){
                $countries = new Countries($this->user);
                $validCountryCode = $countries->validCountryCode($CountryCode, true);
                if($validCountryCode !== false){
                    $this->tplView->DefaultCountry = $validCountryCode;
                }
            }
        }

        // Output the template
        $this->tplView->display('domainSearchResults.tpl.php');
    }
}