<?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: FinancecalculatorController.php, v 1.0 2019/05/17 
//
class FinancecalculatorController extends Controller {

    public function indexAction() {
		$ObjCategory                      = new ProductCategoryModel();
        $ObjBrand                         = new BrandModel();
		$ObjProductList                   = new ProductListModel();
		$ObjCurrency                   	  = new CurrencyModel();
		$languageIDs                      = $this->ObjView->languageIDs;
		$processingFeesPercentage 		  = $this->getSettingValue('product_cart_settings', 'finance_processing_fees');
		$downPaymentPercentage 			  = $this->getSettingValue('product_cart_settings', 'finance_down_payment');
		
		$getCurrentDtls = $ObjCurrency->getCurrencyByCurrencyID($this->ObjView->_defaultCurrency);
		$currencySymbol = $getCurrentDtls['currencySymbol'];
		
		//$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]);                   
            //"<pre>";print_r();exit;
            /* END : Recreate the tree structure from list of category array */
		} 
                $finance_term 			  = $this->getSettingValue('product_cart_settings', 'finance_term');
		$this->ObjView->assign('resBrandCategories', $resBrandCategories);
		$this->ObjView->assign('processingFeesPercentage', $processingFeesPercentage);
		$this->ObjView->assign('downPaymentPercentage', $downPaymentPercentage);
                $this->ObjView->assign('finance_term', $finance_term);
		$this->ObjView->assign('currencySymbol', $currencySymbol);
        $this->ObjView->display('FinanceCalculator.tpl');
    }
	public function ajaxGetFinanceRateAction() {
	  $ObjProduct            	=  	new ProductModel();    
          $ObjCustomOption              =       new CustomOptionModel();
	  $variantCode			 	= 	$_POST['variantCode'];
	  $product_id			 	= 	$_POST['product_id'];
	  $return					=	array();
	  $finance			 	= 	$ObjProduct->getfinanceRate($variantCode);
	  $languageIDs                      = $this->ObjView->languageIDs;
          $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;
                }
            }
            $imagesetarr    =   explode('-',$variantCode);
            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,'thumb');
          
	  if (isset($product_id) && $product_id != '') 
		$return				 	=	$this->getProductDetails($product_id);
		
	  $return['financeRate']		 = 	(!empty($finance['financeRate']))?floatval($finance['financeRate']):'';
	  $return['detailedDescription'] = 	(!empty($finance['detailedDescription']))?$finance['detailedDescription']:'';
          $return['vehicleImage']	 = 	$resProductSummaryImages[0]['vehicleImage'];          
	  echo json_encode($return);
   } 
   public function getProductDetails( $product_id) {
	   $ObjProduct            = new ProductModel();
		$languageIDs          = $this->ObjView->languageIDs;
	   
		$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']);
		$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'])
			
		);
		return $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'];
    }
   public function ajaxGetShortDescAction() {
	  $languageIDs       = $this->ObjView->languageIDs;
	  $ObjProductList    = new ProductListModel();
	  $category			 = 	$_POST['category'];
	  $args              = array(
								'languageIDs' => $languageIDs,
								'categoryID' => $category,
								'type'		 => 'shortDesc',
                                                                'orderby' => 'productTitle',
                                                                'sortby' => 'ASC',
							);
       
	 $resProducts		= 	$ObjProductList->listAllProductBasicDtls($args);
	 //print_r($resProducts);exit;
	 $selectStr = '';
	 if(!empty($resProducts)) {	
			$selectStr .= '<option value="">'.$this->getLanguageValue('lblSelect').'</option>';
		 foreach ($resProducts as $key => $value) {
			 $selectStr .= '<option value="'.$value['productShortDescription'].'">'.$value['productShortDescription'].'</option>';
		 } 
	 }
	  echo $selectStr;
   } 
   public function ajaxGetProductsAction() {
	  $languageIDs       = $this->ObjView->languageIDs;
	  $ObjProductList    = new ProductListModel();
	  $shortDesc		 = 	$_POST['shortDesc'];
	  $args              = array(
								'languageIDs' => $languageIDs,
								'shortDesc' => $shortDesc,
								'type'		 => 'variant'
							);
       
	 $resProducts		= 	$ObjProductList->listAllProductBasicDtls($args);
	 $selectStr = '';
	 if(!empty($resProducts)) {	
			$selectStr .= '<option value="">'.$this->getLanguageValue('lblSelect').'</option>';
		 foreach ($resProducts as $key => $value) {
			 $selectStr .= '<option value="'.$value['optionSKU'].'" price="'.$value['productOptionRegularPrice'].'" product_id="'.$value['productID'].'">'.$value['productTitle'].'</option>';
		 } 
	 }
	 
	  echo $selectStr;
   } 
}