<?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']) {

            // 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 TPL vars
        $this->tplView->domainError = false;
        $this->tplView->domainHasAddons = false;
        $this->tplView->transferOptions = false;
        $this->tplView->domainNameSuggest = false;
        $this->tplView->domainStatus = '-2';
        $this->tplView->submitButton = 'disabled';
        $this->tplView->extraAttributes = false;
        $this->tplView->domainName = $_REQUEST['name'].".".$_REQUEST['tld'];
        $this->tplView->requestTld = $_REQUEST['tld'];

        // 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);

        // 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;
        }

        // Check if we are actually bothering to check the domain availability
        if ($this->settings->get('Check Domain Availability') == 1) {

            $this->tplView->checkingAvailablility = true;

            // 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
                $response = $plugin->checkDomain($params);

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

                // Parse the results
                if(@$response['result'] || @$plugin->supportsNamesuggest) {

                    // 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;

                        // Get the default nameservers
                        $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;

                        // Get the default nameservers
                        $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;
                        }
                    }
                } else {

                    // Enable namesuggest in the temaplte
                    $this->tplView->domainNameSuggest = true;
                    $this->tplView->domainStatus = '0';

                    // 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;

                        // Get the default nameservers
                        $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;

                        // Get the default nameservers
                        $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 not checking avilability
            $this->tplView->checkingAvailablility = false;

            // 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;
                    }
                }
                // Unlock the submit button here to prevent ordering a domain with no pricing
                $this->tplView->submitButton = "";
            }
        }

        // Handle domain addons here
        $domainAddons = $this->getAddons();
        if(count($domainAddons) != 0) {
            $this->tplView->domainHasAddons = true;
            $this->tplView->domainAddons = $domainAddons;
        }

        // Handle transfer & self manage settings
        $this->tplView->allowTransfer = (isset($advancedSettings['allowTransfer']))?true:false;
        $this->tplView->allowManage = (isset($advancedSettings['allowSelfManage']))?true:false;

        // Get the default nameservers
        $serverGateway = new ServerGateway();
        $this->tplView->defaultNameservers = $serverGateway->getDefaultNameservers();

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


    }
}

?>