<?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: OfferController, v 1.0 2018/12/27 12:56:15
//
class OfferController extends Controller {
        public function indexAction()    {
                $ObjOffer           = 	new OfferModel();
                $ObjBrand           =   new BrandModel();	
                $languageIDs		= 	$this->ObjView->languageIDs;		
                $link	=	'offer/index/';
                if (isset($_POST['search'])){			
                        if (isset($_POST['offerGroupID']) && $_POST['offerGroupID'] != ""){
                                $link .= "offerGroupID/" . (int)$_POST['offerGroupID'] . "/";
                        }			
                        if (isset($_POST['offerTypeID']) && $_POST['offerTypeID'] != ""){
                                $link .= "offerTypeID/" . (int)$_POST['offerTypeID'] . "/";
                        }			
                        if (isset($_POST['offerTitle']) && $_POST['offerTitle'] != ""){
                                $link .= "offerTitle/" . $this->encodeUrlString($_POST['offerTitle']) . "/";
                        }
                        if ($_POST['brandID']>0) {
                            $link .= "frID/" . $_POST['brandID'] . "/";
                        }
                        $this->setRedirect($link);
                }
                else{
                        $sortby		=	$this->getRequestValue("sortby");
                        $orderby	=	($this->getRequestValue("orderby")=="")?"asc":$this->getRequestValue("orderby");
                $offerTitle='';			
                        if($this->getRequestValue('offerTitle')){
                                $offerTitle		= 	$this->decodeUrlString($this->getRequestValue('offerTitle'));
                                $link.="offerTitle/".$this->encodeUrlString($offerTitle). "/";
                        }$offerDescription='';			
                        if($this->getRequestValue('offerDescription')){
                                $offerDescription		= 	$this->getRequestValue('offerDescription');
                                $link.="offerDescription/".$offerDescription. "/";
                        }
                        if($this->getRequestValue('offerGroupID')){
                                $offerGroupID		= 	$this->getRequestValue('offerGroupID');
                                $link.="offerGroupID/".$offerGroupID. "/";
                        }
                        if($this->getRequestValue('offerTypeID')){
                                $offerTypeID		= 	$this->getRequestValue('offerTypeID');
                                $link.="offerTypeID/".$offerTypeID. "/";
                        }
                        if ($this->getRequestValue('frID')) {
                            $brandID = $this->getRequestValue('frID');
                        }
                }		
                if (isset($_POST['select_status'])){
                        $params=array(
                                'status'=>$_POST['select_status'],
                                'offerIDs'=>$_POST['offerID']
                        );
                        $ObjOffer->changeStatus($params);
                        $this->setMessage('language.lblOfferstatusUpdatedSuccess','success');
                        $this->setRedirect($link);
                }
                if($sortby=='')$sortby='sort_priority';
                list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page', $rows = 10); 

                $params =array(
                        'limitFrom'=>0,
                        'limitTo'=>'',
                        'languageIDs'=>$languageIDs,
                        'sortby'=>$sortby,
                        'orderby'=>$orderby,
                        'offerTitle'=>$offerTitle ,
                        'offerDescription'=>$offerDescription,
                        'offerTypeID'   => $offerTypeID,
                        'offerGroupID'   => $offerGroupID,
                        'brandID' => isset($brandID) ? $brandID : ''
                );
                $listOffer    = $ObjOffer->listOffer($params);	

                $resPagesCount = $this->setPagesCount($key = 'page');
                $this->ObjView->assign("page", $page);	
                $this->ObjView->assign("sortby", $sortby); $this->ObjView->assign("orderby", ($orderby=="asc")?'desc':'asc'); $this->ObjView->assign("offerTitle", $offerTitle); $this->ObjView->assign("offerDescription", $offerDescription);
                $this->ObjView->assign('listOffer', $listOffer);	

                $editPrivilege	=	$this->ObjCommon->hasPrivilege('offer/edit/');
                $this->ObjView->assign("editPrivilege", $editPrivilege);
                $deletePrivilege	=	$this->ObjCommon->hasPrivilege('offer/destroy/');
                $this->ObjView->assign("deletePrivilege", $deletePrivilege);
				$addPrivilege	=	$this->ObjCommon->hasPrivilege('offer/new/');
                $this->ObjView->assign("addPrivilege", $addPrivilege);
                

                $this->ObjView->assign("link", $link);
                $this->ObjView->assign("offerGroupID", $offerGroupID);
                $this->ObjView->assign("offerTypeID", $offerTypeID);
                $this->ObjView->assign("brandID", isset($brandID) ? $brandID : '');
                $brandParams         = array(
                    'languageIDs' => $languageIDs
                );       
                $listBrand      = $ObjBrand->listBrand($brandParams);  
                $this->ObjView->assign('listBrand', $listBrand);
                $this->ObjView->display('OfferList.tpl');
        }




        public function newAction()    {
                $ObjOffer           = 	new OfferModel();
                $ObjImage           =   new ImageModel();
                $ObjBrand           =   new BrandModel();	
                $languageIDs        = $this->ObjView->languageIDs;
                if($this->ObjForm->isValid('formOffer','submitOffer')){

                              
                        if($_POST["offerImage_temp"]){
                                $offerImageImage   = $this->escape($_POST['offerImage']);
                                $target_path = $this->getDestFilePath($_POST["offerImage_temp"]);
                                $ObjImage->copy_file($_POST["offerImage_temp"], '/' . __UPLOADS_FOLDER . 'offer/' . $offerImageImage);
                                $ObjImage->resizeImage($_POST["offerImage_temp"], '/' . __UPLOADS_FOLDER . 'offer/' . $offerImageImage, 1185, 533);
                                
                                $ObjImage->resizeImage(__ROOT_PATH . '/' . $_POST["offerImage_temp"], $target_path, 890, 400);
                                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'offer/thumb/' . $offerImageImage);                               
                                @unlink($target_path);
                                @unlink($_POST["offerImage_temp"]);
                        }
                $settingsDateFormat                 = $this->getSettingValue('site_settings', 'date_format');
                $_POST['offerStartTime']   = $this->convertDateForSQL($_POST['offerStartTime'], $settingsDateFormat);
                $_POST['offerEndTime']     = $this->convertDateForSQL($_POST['offerEndTime'], $settingsDateFormat);
                        $offerID    =   $ObjOffer->insert($languageIDs);
                        $ObjSef                 =           new SefModel();
                        $suffix    =   $this->getSettingValue('seo_settings', 'offer_url_suffix'); 
                        $ObjSef->_refreshOfferRewrite($languageIDs['AllList'], $offerID, $_POST['offerUrlKey'], $suffix,"insert",$_POST['brandID']);
                        $this->setMessage('language.lblOfferaddSuccess','success');
                        $this->setRedirect('offer/index/');
                } 
                $brandParams         = array(
                    'languageIDs' => $languageIDs
                );       
                $listBrand      = $ObjBrand->listBrand($brandParams);  
                $this->ObjView->assign('listBrand', $listBrand);
                $this->ObjView->display('OfferAdd.tpl');
        }

        public function editAction()    {
                $ObjImage           =   new ImageModel();
                $ObjBrand           =   new BrandModel();	
                $offerID =   $this->getRequestValue('id');
                $ObjOffer    	= 	new OfferModel();
                $languageIDs        = 	$this->ObjView->languageIDs;
                $params=array(
                        'offerID'=>$offerID,
                        'languageIDs'=>$languageIDs
                );
                $getOffer	= $ObjOffer->getOffer($params);
                if(empty($getOffer)){
                         $this->setRedirect('offer');
                }


                if($this->ObjForm->isValid('formOffer','submitOffer')){


                        if($_POST["offerImage_temp"]){
                                $offerImageImage   = $this->escape($_POST['offerImage']);
                                $target_path = $this->getDestFilePath($_POST["offerImage_temp"]);
                                $ObjImage->copy_file($_POST["offerImage_temp"], '/' . __UPLOADS_FOLDER . 'offer/' . $offerImageImage);
                                $ObjImage->resizeImage($_POST["offerImage_temp"], '/' . __UPLOADS_FOLDER . 'offer/' . $offerImageImage, 1185, 533);
                               
                                $ObjImage->resizeImage(__ROOT_PATH . '/' . $_POST["offerImage_temp"], $target_path, 890, 400);
                                $ObjImage->copy_file($target_path, '/' . __UPLOADS_FOLDER . 'offer/thumb/' . $offerImageImage);
                                @unlink($target_path);
                                @unlink($_POST["offerImage_temp"]);
                                
                        }
                $settingsDateFormat                 = $this->getSettingValue('site_settings', 'date_format');
                $_POST['offerStartTime']   = $this->convertDateForSQL($_POST['offerStartTime'], $settingsDateFormat);
                $_POST['offerEndTime']     = $this->convertDateForSQL($_POST['offerEndTime'], $settingsDateFormat);
                        $offerID    =   $ObjOffer->insert($languageIDs,$offerID);
                        $ObjSef                 =           new SefModel();
                        $suffix    =   $this->getSettingValue('seo_settings', 'offer_url_suffix'); 
                        $ObjSef->_refreshOfferRewrite($languageIDs['AllList'], $offerID, $_POST['offerUrlKey'], $suffix,"",$_POST['brandID']);
                        $this->setMessage('language.lblOfferupdatedSuccess','success');
                        $this->setRedirect('offer/index/');

                } 
                 if ($getOffer['offerStartTime'])
                    $getOffer['offerStartTime'] = substr($getOffer['offerStartTime'], 0, -3);
                if ($getOffer['offerEndTime'])
                    $getOffer['offerEndTime'] 	= substr($getOffer['offerEndTime'], 0, -3);
                $this->ObjView->assignValues($getOffer);
                $this->ObjView->assign('offerID', $offerID);
                $resLanguageSelects = explode(',', $getOffer['availableLang']);
                $this->ObjView->assign('resLanguageSelects', $resLanguageSelects); 
                  $brandParams         = array(
                    'languageIDs' => $languageIDs
                );       
                $listBrand      = $ObjBrand->listBrand($brandParams);  
                $this->ObjView->assign('listBrand', $listBrand);
                $this->ObjView->display('OfferAdd.tpl');

        }

        public function viewAction()    {
                $offerID  =   $this->getRequestValue('id');
                $ObjOffer    	= 	new OfferModel();
                $languageIDs        = $this->ObjView->languageIDs;
                $params=array(
                        'offerID'=>$offerID,
                        'languageIDs'=>$languageIDs
                );
                $getOffer	= $ObjOffer->getOffer($params);
                if(empty($getOffer)){
                         $this->setRedirect('offer/index/');
                }
                $this->ObjView->assign('getOffer', $getOffer);
                $this->ObjView->assign('offerID', $offerID);
                $editPrivilege	=	$this->ObjCommon->hasPrivilege('offer/edit/');
                $this->ObjView->assign("editPrivilege", $editPrivilege);
                $this->ObjView->assign("previousURl", $this->getPreviousURL());
                $this->ObjView->display('OfferView.tpl');

        }

        public function ajaxstatusAction()    {
                $offerID 	=   $this->getRequestValue('id');
                $status					  	=   $this->getRequestValue('status');
                $ObjOffer    	= 	new OfferModel();
                $params=array(
                        'status'=>$status,
                        'offerIDs'=>array($offerID)
                );
                $changeStatus = $ObjOffer->changeStatus($params);
                $this->setMessage('language.lblOfferstatusUpdatedSuccess','success');

        }

        public function destroyAction()    {
                $offerID  =   $this->getRequestValue('id');
                if(isset($offerID)){
                        $ObjOffer    	= 	new OfferModel();
                        $params=array(
                                'status'=>'D',
                                'offerIDs'=>array($offerID)
                        );
                        $changeStatus = $ObjOffer->changeStatus($params);
                        $this->setMessage('language.lblOfferdeletedSuccess','success');
                        $this->setRedirect('offer/index/');

                }
        }
        public function ajaxUpdateOfferPriorityAction(){
                $languageIDs=$this->ObjView->languageIDs;
                $ObjOffer    	= 	new OfferModel();
                $offerPriorities	=	explode(",",$_POST['offerPriority']);
                $resBannerOrder	=	$ObjOffer->changeOrder($offerPriorities,$languageIDs);
        }
         public function getDestFilePath($path) {
        $path_parts = pathinfo($path);
        $file_name  = basename($path, '.' . $path_parts['extension']);
        return $path_parts['dirname'] . "/" . $file_name . "_" . rand() . "." . $path_parts['extension'];
    }
    
     public function submissionlistAction()    {
                $ObjOffer    	= 	new OfferModel();
				$ObjBrand           = new BrandModel();	
                $languageIDs		= 	$this->ObjView->languageIDs;		
                $link	=	'offer/submissionlist/';
                if (isset($_POST['search'])){			
                        if (isset($_POST['searchName']) && $_POST['searchName'] != ""){
                                $link .= "searchName/" . $this->encodeUrlString($_POST['searchName']) . "/";
                        }			
                        if (isset($_POST['searchEmail']) && $_POST['searchEmail'] != ""){
                                $link .= "searchEmail/" . $this->encodeUrlString($_POST['searchEmail']) . "/";
                        }			
                        if (isset($_POST['searchShowroom']) && $_POST['searchShowroom'] != ""){
                                $link .= "searchShowroom/" . $this->encodeUrlString($_POST['searchShowroom']) . "/";
                        }
                         if (isset($_POST['searchOffer']) && $_POST['searchOffer'] != ""){
                                $link .= "searchOffer/" . $this->encodeUrlString($_POST['searchOffer']) . "/";
                        }
						if ($_POST['brandID']>0) {
                            $link .= "frID/" . $_POST['brandID'] . "/";
                        }
                        $this->setRedirect($link);
                }
                else{
//                        $sortby		=	$this->getRequestValue("sortby");
//                        $orderby	=	($this->getRequestValue("orderby")=="")?"asc":$this->getRequestValue("orderby");
                $searchName='';			
                        if($this->getRequestValue('searchName')){
                                $searchName		= 	$this->decodeUrlString($this->getRequestValue('searchName'));
                                $link.="searchName/".$this->encodeUrlString($searchName). "/";
                        } $searchEmail='';			
                        if($this->getRequestValue('searchEmail')){
                                $searchEmail		= 	$this->decodeUrlString($this->getRequestValue('searchEmail'));
                                $link.="searchEmail/".$this->encodeUrlString($searchEmail). "/";
                        }
                         $searchShowroom='';			
                        if($this->getRequestValue('searchShowroom')){
                                $searchShowroom		= 	$this->decodeUrlString($this->getRequestValue('searchShowroom'));
                                $link.="searchShowroom/".$this->encodeUrlString($searchShowroom). "/";
                        }
                         $searchOffer='';			
                        if($this->getRequestValue('searchOffer')){
                                $searchOffer		= 	$this->decodeUrlString($this->getRequestValue('searchOffer'));
                                $link.="searchOffer/".$this->encodeUrlString($searchOffer). "/";
                                $this->ObjView->assign("searchOffer", $searchOffer);
                        }
						$brandID = '';
                        if ($this->getRequestValue('frID')) {
                            $brandID = $this->getRequestValue('frID');
                        }
                }	
				if (isset($_POST['export'])) {
					$resOrdersCsv         = $ObjOffer->listSubmission(0,'',$languageIDs,$searchName,$searchEmail,$searchShowroom,$searchOffer,$brandID,'Export');
					$ObjCsv               = new Csv();
					$csvOutputHeader      = array(
						$this->getLanguageValue("lblName"),
						$this->getLanguageValue("lblPhone"),
						$this->getLanguageValue("lblEmailID"),
						$this->getLanguageValue("lblShowroom"),
						$this->getLanguageValue("lblOffer"),
						$this->getLanguageValue("lblWhereDidYouFindUs"),
						$this->getLanguageValue("lblCreatedDate"));
					$csvOutputFileName    = "special_offer_list_" . date('d_m_Y_h_i_s_A');
					$count                = $resOrdersCsv->num_rows;
					if ($count > 0) {
						for ($i = 0; $i < $count; $i++) {
							$orders                                  = $resOrdersCsv->fetch_array(MYSQLI_ASSOC);
							$resOrdersCsvOut[$i]['name']      		 = $this->encryptDecrypt("decrypt",$orders['customer_name']);
							$resOrdersCsvOut[$i]['phone']      		 = $this->encryptDecrypt("decrypt",$orders['customer_phone']);
							$resOrdersCsvOut[$i]['email']  	 		 = $this->encryptDecrypt("decrypt",$orders['emailID']); 
							$resOrdersCsvOut[$i]['showroom']  	     = $orders['name']; 
							$resOrdersCsvOut[$i]['model']  	 		 = $orders['offerTitle']; 
							$resOrdersCsvOut[$i]['currentcar']  	 = $orders['findus']; 
							$resOrdersCsvOut[$i]['createdDate']  	 = ($orders['CreatedDate']!='0000-00-00 00:00:00')?$orders['CreatedDate']:'';
							unset($orders);
						}
					}
					$csvOutputData = $ObjCsv->output($csvOutputFileName . '.csv', $resOrdersCsvOut, $csvOutputHeader);
					exit;
				}
                list($limitFrom, $limitTo) = $this->getPageSettings($key = 'page', $rows = 10);
                $offerSubListing    =   $ObjOffer->listSubmission($limitFrom,$limitTo,$languageIDs,$searchName,$searchEmail,$searchShowroom,$searchOffer,$brandID);
                $resPagesCount = $this->setPagesCount($key = 'page');
                $this->ObjView->assign("page", $page);	
                $this->ObjView->assign("sortby", $sortby); $this->ObjView->assign("orderby", ($orderby=="asc")?'desc':'asc'); $this->ObjView->assign("offerTitle", $offerTitle); $this->ObjView->assign("offerDescription", $offerDescription);
                $this->ObjView->assign("searchOffer", $searchOffer);
                $this->ObjView->assign("searchName", $searchName);
                $this->ObjView->assign("searchShowroom", $searchShowroom);
                $this->ObjView->assign("searchEmail", $searchEmail);                
                $this->ObjView->assign('listSubmission', $offerSubListing);
				$this->ObjView->assign("brandID", isset($brandID) ? $brandID : '');
				$brandParams         = array(
					'languageIDs' => $languageIDs
				);       
				$listBrand      = $ObjBrand->listBrand($brandParams);  
				$this->ObjView->assign('listBrand', $listBrand);
                $this->ObjView->display('OfferSubmission.tpl');

                	
     
     }
}