<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: LeasecalculatorController.php, v 1.0 2019/05/17 
//
class LeasecalculatorController extends Controller {
    public function indexAction() {
		$ObjCategory                      = new ProductCategoryModel();
        $ObjBrand                         = new BrandModel();
		$ObjProductList                   = new ProductListModel();
		$languageIDs                      = $this->ObjView->languageIDs;
		$staticBlock = array();
		//$brandKey = 'bmw';
		$brandKey = FRANCHISEE;
        /* if brand key found in url */
        if ($brandKey != '') {
            $sefProductIDArray = array();
            $params            = array(
                'languageIDs' => $languageIDs,
                'brandKey' => $brandKey
            );
            $brandInfo         = $ObjBrand->getBrand($params);
            if (empty($brandInfo)) {
                $this->ObjView->display('NoPage.tpl');
                exit;
            }
            $brandID          = $brandInfo['brandID'];
            if(empty($brandID)) {
                $brandID        = $brandInfo['brandID'];                
            }
            if($brandID>0) {
                //get Subbrands if any
                $getSub = $ObjBrand->getSubBrandIDs($brandID);                
                $brandIDs = $this->ObjCommon->brandID;
                if(!empty($getSub) && !empty($getSub['brandIDs'])) {
                    $brandIDs .= ",".$getSub['brandIDs'];
                }
            }
            
            /* START :  To find the active brand Categories */
            $args             = array(
                'brandID' => $brandIDs
            );
            $brandCategories  = $ObjProductList->listCategoriesUnderBrands($args);
           
            /* END :  To find the active brand Categories */
            /* START : Iterate with each category from "$this->ObjCommon->CategoryAll" and found the children using "$this->ObjCommon->CategoryTree" */
            $activeCategories = array();
            foreach ($this->ObjCommon->CategoryAll as $category) {
                //$getSubCategories = $this->ObjCommon->getSubCategories($category['productCategoryID']);
                $getSubCategories = array();
                $getSubCategories = array_merge(array(
                    $category['productCategoryID']
                ), $getSubCategories);
                /* Check whether the same or subcategory is active Offer category */
                $commonCategories = array_intersect($getSubCategories, $brandCategories);
                /* array itersect will return the common categories ;ie We found the category or subcategory is active */
                if (count($commonCategories) > 0) {
                    $activeCategories[] = $category;
                }
            }            
            /* END : Iterate with each category from "$this->ObjCommon->CategoryAll" and found the children using "$this->ObjCommon->CategoryTree" */
            /* START : Recreate the tree structure from list of category array */
            /* Iteration start to find the similar Category having same group */
            foreach ($activeCategories as $key => $value) {
                //$categoryTree[$activeCategories[$key]['productCategoryParent']][] = $activeCategories[$key];
                $categoryTree[0][] = $activeCategories[$key];
            }
            /* Again create the tree structured Array */
            $resBrandCategories = $ObjCategory->createCategoryTree($categoryTree, $categoryTree[0]);
            //echo "<pre>";print_r($resBrandCategories);exit;
            //"<pre>";print_r();exit;
            /* END : Recreate the tree structure from list of category array */
			
			$ObjCustommenu = new CustommenuModel();
			$staticBlock   = $ObjCustommenu->listStaticBlocksFrontend($languageIDs, '',$brandID);
		} 
		$this->ObjView->assign('staticBlock', $staticBlock[0]['blockContent']);
		$this->ObjView->assign('resBrandCategories', $resBrandCategories);
        $this->ObjView->display('LeaseCalculator.tpl');
    }
    public function ajaxGetLeaseRateAction() {
	  $ObjProduct            =  new ProductModel();    
	  $variantCode			 = 	$_POST['variantCode'];
	  $duration			 	 = 	$_POST['duration'];
	  $mileage			 	 = 	$_POST['mileage'];
	  $tyreChange			 = 	$_POST['tyreChange'];
	  $args              	 = array(
								'variantCode' 	=> $variantCode,
								'duration' 		=> $duration,
								'mileage'		=> $mileage,
								'tyreChange'	=> $tyreChange
							);
	  $leaseRate			 = 	$ObjProduct->getLeaseRate($args);
	  echo (!empty($leaseRate))?round($leaseRate):'';
   } 
   public function ajaxgetProductDetailsAction() {
	   $ObjProduct            = new ProductModel();
           $ObjCustomOption              =       new CustomOptionModel();
	   $product_id			  = $_POST['product_id'];
	   $languageIDs           = $this->ObjView->languageIDs;
	   $this->ObjCommon->setCommonSefPath(array(
            'product'
        ), array(
            "0" => $product_id
        ));
		$productType          = array(
            'productTypeID' => 1,
            'productTypeKey' => 'product_product',
            'productTypeUrlKey' => '',
            'isFeatured' => 1,
            'limitMainListing' => '',
            'limitDefListing' => '',
            'productTypeName' => $this->getLanguageValue('lblProducts')
        );
        $args                 = array(
            'requestedBy' => 'customer',
            'requestPage' => 'product_detail',
            'limitFrom' => 0,
            'limitTo' => 1,
            'languageIDs' => $languageIDs,
            'previewOnly' => "Yes",
            'productType' => $productType,
            'selectedProductID' => $product_id,
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
            'productStatus' => 'Active'
        );
      
        $resultProductProduct = $ObjProduct->getProductDetails($args);  
		//print_r($args); print_r($resultProductProduct);exit;
		
		$imagesetarr    =   explode('-',$resultProductProduct[0]['optionSKU']);
                
          $customOption = $ObjCustomOption->getProductCustomOptions($languageIDs, $product_id);
            if (count($customOption) > 0) {
                foreach ($customOption as $key => $option) {
                    $variants                       = $ObjCustomOption->getCustomOptionVariants($languageIDs, $option['customOptionID']);
                    $customOption[$key]['variants'] = $variants;
                }
            }
            for($i=0;$i<count($customOption);$i++){
                    for($j=0;$j<count($customOption[$i]['variants']);$j++){
                        
                        if(isset($cartID) && ($cartID>0)){
                            if($customOption[$i]['variants'][$j]['customOptionVariantID']==$selectedCustomOptionValues[$customOption[$i]['customOptionID']][0]['customOptionVariantID']){
                                if($customOption[$i]['customOptionName'] != 'Wheel' && $customOption[$i]['customOptionName'] != 'Trim')
                                {
                                    $imagesetarr[]  =   $customOption[$i]['variants'][$j]['variantCode'];
                                }
                                $setdefaultimages[$customOption[$i]['customOptionID']] = array('id'=>$customOption[$i]['variants'][$j]['customOptionVariantID'],'image'=>$customOption[$i]['variants'][$j]['variantThumbImage']);
                            }
                        }
                        else{
                            if($customOption[$i]['variants'][$j]['isDefault']==1){
                                if($customOption[$i]['customOptionName'] != 'Wheel' && $customOption[$i]['customOptionName'] != 'Trim')
                                {
                                    $imagesetarr[]  =   $customOption[$i]['variants'][$j]['variantCode'];
                                }
                                $setdefaultimages[$customOption[$i]['customOptionID']] = array('id'=>$customOption[$i]['variants'][$j]['customOptionVariantID'],'image'=>$customOption[$i]['variants'][$j]['variantThumbImage']);
                            }
                        }
                    }
            }
		$resProductSummaryImages   =   $this->loadingProductImages(implode('_',$imagesetarr),'extr',30);
		$requestPath = $this->sefPathByID($product_id, 'product');
		
		$return = array(
			'productTitle'				=> $resultProductProduct[0]['productTitle'],
			'requestPath'				=> (!empty($requestPath))?$requestPath:'',
			'productOptionRegularPrice'	=> round($resultProductProduct[0]['productOptionRegularPrice']),
			'vehicleImage'				=> $resProductSummaryImages[0]['vehicleImage'],
                         'monthlyInstallment'	=> round($resultProductProduct[0]['monthlyInstallment'])
			
		);
		echo json_encode($return);
   }
   public function loadingProductImages($image_code,$imageType='extr',$angle=''){
		$ObjProduct                          = new ProductModel();
		$resImages  =   $ObjProduct->getProductImages($image_code,$imageType,'no',$angle);
		return $resImages;
	}
	public function sefPathByID($currID, $type = 'product') {
        $languageIDs = $this->ObjView->languageIDs;
        $ObjUrl      = new UrlrewriteModel();
        $idPath      = $type . '/' . $currID . '/';
        $resUrl      = $ObjUrl->getRequestPathByIdPath($languageIDs['Current'], $idPath);
        return $resUrl['requestPath'];
    }
}