<?php

require_once 'modules/admin/views/public/SignupView.php';
require_once 'modules/admin/models/PackageTypeGateway.php';
require_once 'modules/admin/models/Package.php';
require_once 'modules/billing/models/Currency.php';
require_once 'modules/admin/models/ActiveOrderGateway.php';

/**
* @package Admin
*/
class ViewSignup_1_PackageSelection extends SignupView
{
    var $permission   = '';
    var $currencys    = null;
    var $validPricing = false;
    var $hasSavings   = false;
    
    function dispatch()
    {

        $this->initialize();
        
        //lets see if there are any products that are stock controled
        //that need to be cleared
        $aogateway = new ActiveOrderGateway($this->user);
		$aogateway->clearAllOrdersForProductId();

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

        // Set header info

		// Unset the session used to stop things being added to the cart incase we got back here
        unset($_SESSION['avoidaddpackage']);
        
        // Destroy the temp item just to be safe
        $this->destroyTempItem();
        
        // Has somebody specified a domain name in the URL?
        if(isset($_GET['domainName']) && isset($_GET['tld'])) {
        	$_SESSION['domainName'] = $_GET['domainName'];
        	$_SESSION['tld'] = $_GET['tld'];
        }

		//lets get the productgroup if we were passed a product without the productgroup
        if( isset($_REQUEST['product']) && !isset($_REQUEST['productGroup']) ){
        	$tPackage = new Package($_REQUEST['product']);
        	$_REQUEST['productGroup'] = $tPackage->planid;
        }

        // Check we have been given a product group?
        if( isset($_REQUEST['productGroup']) ) {
			$_REQUEST['productGroup'] = $this->db->escape_string($_REQUEST['productGroup']);
            // Get the product group information
            $productGroup = PackageTypeGateway::getPackageTypes($_REQUEST['productGroup']);
            $productGroup = $productGroup->fetch();

            // Check if we are a domain, if so we need to move along
            if($productGroup->fields['type'] == 3) {
                
                // Show the domain form
                include("modules/admin/views/public/Signup_2_Domain.php");
                ViewSignup_2_Domain::dispatch();
                $this->showFooter(); // Show the footer to set the header vars etc properly
                exit;
            }


            // Get the packages for this group
            $dropdownCount = 0;
            $packageCount = 0;
            $query = "SELECT id FROM package WHERE planid = ? ORDER BY id";
            $result = $this->db->query($query, $_REQUEST['productGroup']);
            $selectedProduct = @$_GET['product'];
            while ($row = $result->fetch()) {

                // Get the info for this package
                $package = new Package($row['id']);

                // Should we include this product
                if($package->showpackage != 1) {
                    // Do we make an execption for direct link
                    if($package->allowdirectlink == 1 && $package->id == @$_GET['product']) {
                        // Move on
                    } else {
                        continue;
                    }
                }

                // Start the array
                $workingPackage = array();

                // start adding some pieces
                $workingPackage['planname'] = $package->planname;
                $workingPackage['id'] = $package->id;
                $workingPackage['showDropdown'] = ($package->showpackage == 1 || ($package->allowdirectlink == 1 && $selectedProduct == $package->id))?true:false;

                if($workingPackage['showDropdown']) { ++$dropdownCount; }

                // Work out if we have selected this product
                if(($selectedProduct == $package->id || $selectedProduct == false) && ($package->showpackage == 1 || $package->allowdirectlink == 1)) {
                    
                    $this->debug('here');
                    
                    $workingPackage['selected'] = true;
                    ++$packageCount;

                    // Set the pricing
                    $package->getProductPricing();
                    $this->tplView->pricing = $this->prettyPricing($package->pricingInformation);
                    $this->tplView->validPricing = $this->validPricing;
                    
                    // Add the description
                    $this->tplView->description = $package->description;
                    $this->tplView->planname = $package->planname;
					$this->tplView->timeExpireText = ""; 
					
                    // Get the stockInfo
                    $stockInfo = unserialize($package->stockInfo);
                    if(is_array($stockInfo)) {
                        // Check if we are doing stockControl
                        if($stockInfo['stockEnabled'] == 1) {

                            // Work out if stock control should be enabled or not
                            if($stockInfo['availableStock'] == 0 && $stockInfo['acceptSoldOut'] == 1) {

                                // Turn stock control off as we are still accepting orders
                                $this->tplView->stockControl = 0;

                            } elseif($stockInfo['availableStock'] > 0) {

                                // Turn stock control off as we are still accepting orders
                                $this->tplView->stockControl = 0;

                            } else {

                                // Not sure what else todo so turn stock control on and stop orders                        
                                $this->tplView->stockControl = 1;
                            }

                            
                            // Are we displaying the stock level
                            if($stockInfo['showStockLevel'] == 1) {
							
                                // Set the current stock level
                                $this->tplView->stockLevel = $stockInfo['availableStock'];

                            } else {

                                // Set disabled
                                $this->tplView->stockLevel = -1;
                            }
                            
                            $stockTimer = (int) $this->settings->get('Stock Timer');
		   					if($stockTimer > 0) { 
		   						$this->tplView->timeExpireText = "-&nbsp;".$this->lang("You have")." ".$stockTimer." ".$this->lang("minutes")." ".$this->lang("to complete each step"); 
		   					}                           

                        } else {

                            // Disabled
                            $this->tplView->stockControl = 0;
                            $this->tplView->stockLevel = -1;
                        }
                    } else {
                        
                        // Disabled
                        $this->tplView->stockControl = 0;
                        $this->tplView->stockLevel = -1;
                    }

                    // Get the custom fields as our hasCustomFields doesnt return it correctly
                    $customFieldCount = $this->getCustomFields('package', $package);
                    $customFieldCount = @count($customFieldCount);

                    // Get the addons
                    $addonCount = $this->getAddons($row['id']);
                    $addonCount = count($addonCount);
                    // Check if this product has any custom fields or addons
                    if(!$addonCount && !$customFieldCount && !$package->hasBundledProducts()) {
                        $this->tplView->nextUrl = 'order.php?step=4';

                    } elseif($addonCount || $customFieldCount) {

                        // Product has custom fields or addons to configure
                        $this->tplView->nextUrl = 'order.php?step=2';
                        
                    } elseif($package->hasBundledProducts() && (!$addonCount && !$customFieldCount)) {
                        // Some processing for bundled priducts

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

                        // Went wrong somewhere.
                        $this->tplView->nextUrl = 'order.php?step=4';
                    }

                    // Update the selected product so we don't overwrite the pricing
                    $selectedProduct = $package->id;
                    
                } else {

                    // Have to set this otherwise the template will moan
                    $workingPackage['selected'] = false;                              
                }

                // Add to the array
                $this->tplView->packages[] = $workingPackage;
            }

            // Work out what to do if we have nothing tos how
            if($packageCount == 0) {
                $this->tplView->nextUrl = '';
            }

            // Display saved percentages??
            $this->tplView->showSaved = ($this->settings->get('Include Saved Percentage') && $this->hasSavings == true)?1:0;

            // Set some hidden vars
            $this->tplView->product = $selectedProduct;
            $this->tplView->productGroup = $_REQUEST['productGroup'];
            $this->tplView->packageCount = $packageCount;
            $this->tplView->dropdownCount = $dropdownCount;

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

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

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

        } else {

            // Redirect to Step 0
            include("modules/admin/views/public/Signup_0_PackageGroup.php");
            ViewSignup_0_PackageGroup::dispatch();
        }

    }

    /*
     * Turn the returned pricing array into a pretty ony
     */
    function prettyPricing($pricingArray) {

        $finalPricing = array();
        $firstPrice = 0;
        $firstSelected = false;
        $saved = '-';

        // 1 Month
        if(@$pricingArray['price1included']) {

            // set the valid pricing term
            $this->validPricing = true;

            // Set the first price as theres nothing to calculate a saving from
            $firstPrice = @$pricingArray['price1'];

            // Get the selected item
            if(@$_REQUEST['term'] == '1' || $firstSelected == false) { $selected = true; $firstSelected = true; } else { $selected = false; }

            // Add the price
            $finalPricing[] = array('term'      => $this->lang('Monthly (1 Month)'),
                                    'price'     => $this->currencys->format($this->currency, @$pricingArray['price1'], true, false, "NONE", true),
                                    'setup'     => $this->currencys->format($this->currency, @$pricingArray['price1_setup'], true, false, "NONE", true),
                                    'termId'    => '1',
                                    'save'      => "-",
                                    'selected'  => $selected
                );
        }

        // Quarterly
        if(@$pricingArray['price3included']) {

            // set the valid pricing term
            $this->validPricing = true;

            // Get the saved percentage
            if($firstPrice != 0) {
                $saved = $firstPrice - @$pricingArray['price3'] / 3;
                $saved = $saved / $firstPrice * 100;

                if($saved > 0.0) {
                    $saved = $this->currencys->format($this->currency, $saved)."%";
                    $this->hasSavings = true;
                } else {
                    $saved = "-";
                }
            } else {
                $firstPrice = @$pricingArray['price3']/3;
            }

            // Get the selected item
            if(@$_REQUEST['term'] == '3' || $firstSelected == false) { $selected = true; $firstSelected = true; } else { $selected = false; }

            // Add the price
            $finalPricing[] = array('term'      => $this->lang('Quarterly (3 Months)'),
                                    'price'     => $this->currencys->format($this->currency, @$pricingArray['price3'], true, false, "NONE", true),
                                    'setup'     => $this->currencys->format($this->currency, @$pricingArray['price3_setup'], true, false, "NONE", true),
                                    'termId'    => '3',
                                    'save'      => $saved,
                                    'selected'  => $selected
                );
        }

        // Semi-Annual
        if(@$pricingArray['price6included']) {

            // set the valid pricing term
            $this->validPricing = true;

            // Get the saved percentage
            if($firstPrice != 0) {
                $saved = $firstPrice - @$pricingArray['price6'] / 6;
                $saved = $saved / $firstPrice * 100;
                
                if($saved > 0.0) {
                    $saved = $this->currencys->format($this->currency, $saved)."%";
                    $this->hasSavings = true;
                } else {
                    $saved = "-";
                }
            } else {
                $firstPrice = @$pricingArray['price6']/6;
            }

            // Get the selected item
            if(@$_REQUEST['term'] == '6' || $firstSelected == false) { $selected = true; $firstSelected = true; } else { $selected = false; }

            // Add the price
            $finalPricing[] = array('term'      => $this->lang('Semi-Annual (6 Months)'),
                                    'price'     => $this->currencys->format($this->currency, @$pricingArray['price6'], true, false, "NONE", true),
                                    'setup'     => $this->currencys->format($this->currency, @$pricingArray['price6_setup'], true, false, "NONE", true),
                                    'termId'    => '6',
                                    'save'      => $saved,
                                    'selected'  => $selected
                );
        }

        // From One to Ten Years
        $TermText = array(
            12  => $this->lang('Annual'),
            24  => $this->lang('Two Years'),
            36  => $this->lang('Three Years'),
            48  => $this->lang('Four Years'),
            60  => $this->lang('Five Years'),
            72  => $this->lang('Six Years'),
            84  => $this->lang('Seven Years'),
            96  => $this->lang('Eight Years'),
            108 => $this->lang('Nine Years'),
            120 => $this->lang('Ten Years')
        );
        for($TermLength = 12; $TermLength <= 120; $TermLength+=12){
            if(@$pricingArray['price'.$TermLength.'included']) {

                // set the valid pricing term
                $this->validPricing = true;

                // Get the saved percentage
                if($firstPrice != 0) {
                    $saved = $firstPrice - @$pricingArray['price'.$TermLength] / $TermLength;
                    $saved = $saved / $firstPrice * 100;

                    if($saved > 0.0) {
                        $saved = $this->currencys->format($this->currency, $saved)."%";
                        $this->hasSavings = true;
                    } else {
                        $saved = "-";
                    }
                } else {
                    $firstPrice = @$pricingArray['price'.$TermLength]/$TermLength;
                }

                // Get the selected item
                if(@$_REQUEST['term'] == "$TermLength" || $firstSelected == false) { $selected = true; $firstSelected = true; } else { $selected = false; }

                // Add the price
                $finalPricing[] = array('term'      => $TermText[$TermLength].' ('.$TermLength.' '.$this->lang('Months').')',
                                        'price'     => $this->currencys->format($this->currency, @$pricingArray['price'.$TermLength], true, false, "NONE", true),
                                        'setup'     => $this->currencys->format($this->currency, @$pricingArray['price'.$TermLength.'_setup'], true, false, "NONE", true),
                                        'termId'    => "$TermLength",
                                        'save'      => $saved,
                                        'selected'  => $selected
                    );
            }
        }

        // One Time
        if(@$pricingArray['priceonetimeincluded']) {

            // set the valid pricing term
            $this->validPricing = true;

            // Get the selected item
            if(@$_REQUEST['term'] == '0' || $firstSelected == false) { $selected = true; $firstSelected = true; } else { $selected = false; }

            // Add the price
            $finalPricing[] = array('term'      => $this->lang('One Time'),
                                    'price'     => $this->currencys->format($this->currency, @$pricingArray['onetime'], true, false, "NONE", true),
                                    'setup'     => '-',
                                    'termId'    => '0',
                                    'save'      => '',
                                    'selected'  => $selected
                );
        }
        
        return $finalPricing;
    }
}

?>
