<?php
require_once 'modules/admin/models/PackageTypeGateway.php';
require_once 'modules/admin/views/public/SignupView.php';
require_once 'modules/billing/models/Currency.php';
require_once 'modules/admin/models/PackageAddonGateway.php';

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


    function dispatch()
    {

        $this->initialize();

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

        // Check if we were given a product to configure
        if( !isset($_REQUEST['product']) || !isset($_REQUEST['priceTerm']) ) {
            // Redirect back to the first step
            include("modules/admin/views/public/Signup_0_PackageGroup.php");
            ViewSignup_0_PackageGroup::dispatch();
            return;
        }

        // Get the package & Group
        $package = new Package(@$_REQUEST['product']);
        $productGroup = PackageTypeGateway::getPackageTypes($package->planid);
        $productGroup = $productGroup->fetch();

        if ( isset($_GET['product']) && $_GET['product'] > 0 && $package->allowdirectlink == 0 ) {
            // Redirect back to the first step
            include("modules/admin/views/public/Signup_0_PackageGroup.php");
            ViewSignup_0_PackageGroup::dispatch();
            return;
        }
        
        // Set some hidden vars
        $this->tplView->product = array('id' => @$_REQUEST['product'], 'name'=> $productGroup->fields['name']." / ".$package->planname);
        $this->tplView->productGroup = @$_REQUEST['productGroup'];

        // Work out if this product has and bundled products
        $this->tplView->hasBundledProducts = $package->hasBundledProducts();

        if($package->hasBundledProducts()) {

            // Get the first bundled product
            $bundledProducts = $package->getBundledProducts();

            // Loop the bundled products until we find one not in the session
            foreach ($bundledProducts AS $key) {

                // Check if it's in the session

                // Get the package information from the bundle product
                $bundlePackage = new Package($key);
                $bundleProductGroup = PackageTypeGateway::getPackageTypes($bundlePackage->planid);
                $bundleProductGroup = $bundleProductGroup->fetch();

                // Determine what page to load next
                if($bundleProductGroup->fields['type'] == 3) {
                    $this->tplView->nextUrl = 'order.php?step=2&product='.$bundlePackage->id.'&domain=1';
                } else {
                    $this->tplView->nextUrl = 'order.php?step=2&product='.$bundlePackage->id.'&bundled=1';                
                }
            }
        } else {
            $this->tplView->nextUrl = 'order.php?step=4';
        }

        // Get Custom Fields
        $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;
                }
            }
        }


        // Get advanced settings
        $advancedSettings = @unserialize($package->advanced);

        // Check for a possible subdomain
        if(isset($advancedSettings['subdomain']) && $advancedSettings['subdomain'] != '') {

            $this->tplView->subDomains = array();

            // Explode the subdomains
            $subDomains = explode(";", $advancedSettings['subdomain']);

            // Populate the subdomains
            if(is_array($subDomains)) {
                foreach($subDomains AS $key) {
                    $this->tplView->subDomains[] = $key;
                }
            } else {
                $this->tplView->subDomains[] = $advancedSettings['subdomain'];
            }
        }

        // Get advanced fields
        $advancedInfo = @unserialize($package->advanced);
        if(isset($advancedInfo['allowSubdomains']) && !$package->hasBundledProducts()) {
            $this->tplView->offerSubdomains = true;

            // Explode the domains
            $subDomains = explode(";", $advancedInfo['subdomain']);
            foreach($subDomains AS $key) {
                $this->tplView->subdomain[] = array('name' => trim($key));
            }
        }


        // Get Package Addons
        $this->tplView->packageAddons = $this->getAddons();

                // Handle the form post
        $cartItemId = $this->processFormPost($_REQUEST, @$_REQUEST['formId'], 'configureProduct');
        $this->tplView->cartItemId = $cartItemId;

        // Process the progress bar
        $this->tplView->progress = $this->getProgressBar();
        $this->tplView->progressBar = $this->tplView->fetch('progressBar.tpl.php');

        // Process the cart summary
        $cartSummary = $this->getCartSummary();
        $this->tplView->cartItems = $cartSummary['items'];
        $this->tplView->cartTotal = $cartSummary['total']['price'];
        $this->tplView->cartSummary = $this->tplView->fetch('cartSummary.tpl.php');

        // Do we have a manually specified domain
        if((isset($_GET['domainName']) && isset($_GET['tld'])) || (isset($_SESSION['domainName']) && isset($_SESSION['tld']))) {
            foreach ( $this->tplView->customFields as $id => &$customField ) {
                if ( @$customField['isDomain'] == 1 ) {
                    $this->tplView->customFields[$id]['savedValue'] = (isset($_GET['domainName']))?$_GET['domainName']:$_SESSION['domainName'];
                    // PHP kept erroring unless we did this if the long way...
                    if ( isset($_GET['tld']) ) {
                        $this->tplView->customFields[$id]['savedValue'] .= '.' . $_GET['tld'];
                    } else {
                        $this->tplView->customFields[$id]['savedValue'] .= '.' . $_SESSION['tld'];
                    }
                    break;
                }
            }
            unset($_SESSION['domainName']);
            unset($_SESSION['tld']);
        }

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

        // Show the footer
        $this->tplView->display('signup_footer.tpl.php');
    }
}