<?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: TestdriveController.php, v 1.0 2019/05/17 
//
class TestdriveController extends Controller {
       public function indexAction() {
            $ObjProductList        = new ProductListModel();
            $TestdriveModel        = new TestdriveModel();
            $ObjBrand              = new BrandModel();
            $ObjEmailtemplate      = new EmailtemplateModel();
            $ShowroomsModel        = new ShowroomsModel();
            $ObjOtpCountry                       = new OtpCountryModel();
            $languageIDs           = $this->ObjView->languageIDs;
            $productType                 = array(
                'productTypeID' => 1,
                'productTypeKey' => 'product_product',
                'productTypeUrlKey' => '',
                'isFeatured' => 1,
                'limitMainListing' => '',
                'limitDefListing' => '',
                'productTypeName' => $this->getLanguageValue('lblProducts')
            );
            $menuItemID                       = (int) $this->getRequestValue("itemID");   
            $customGroupBy='bodyStyle';
            $default_catalog_listing     = 'price_asc';
            $bodyStyle=array();
            $custCode=array();
			$sucssMsge = 'no';
            //$brandKey = 'bmw';
			$brandKey = FRANCHISEE;
            /* if brand key found in url */
            if ($brandKey != '') {

                $paramsBrand            = array(
                    'languageIDs' => $languageIDs,
                    'brandKey'    => $brandKey
                );
                $brandInfo         = $ObjBrand->getBrand($paramsBrand);

                $brandID          = $brandInfo['brandID'];

                if($brandID>0) {
                    //get Subbrands if any
                    $getSub = $ObjBrand->getSubBrandIDs($brandID);                
                    //$brandIDs = 1;
                    $brandIDs = $this->ObjCommon->brandID;
                    if(!empty($getSub) && !empty($getSub['brandIDs'])) {
                        $brandIDs .= ",".$getSub['brandIDs'];
                    }
                }
            }
            $args                        = array(
                'requestedBy' => 'customer',
                'requestPage' => 'category_prod_listing',
                'limitFrom' => 0,
                'limitTo' => '',
                'languageIDs' => $languageIDs,
                'productType' => $productType,
                'brandID' => $brandID,
                'businessID' => '1',
                'brandIDs' => $brandIDs,
                'categoryID' => '',
                'categoryIDs' =>'',
                'customOrderBy' =>$default_catalog_listing,
                'searchKeyword' =>  array(),
                'attrDataObj' => array(),
                'priceRangeMin' => '',
                'priceRangeMax' => '',
                'emiRangeMin' => '',
                'emiRangeMax' => '',
                'discountRange' => '',
                'attrQueryStringArray' => '',
                'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
                'isProductDeal' => 'No',
                'showpage' => '',
                'menuItemID' => $menuItemID,
                'customGroupBy'=>$customGroupBy,
                'bodyStyle'=>$bodyStyle,
                'bmwCode'=>'',
                'custom'=>'Yes',
                'custCode'=>$custCode,
                'frontEnd'=>'Yes'
            );
       
        $resAllProducts              = $ObjProductList->testDriveProductModels($args); 
        $productarray=array();
        foreach($resAllProducts as $key=>$products){
			
			if(strtolower($products['bodyStyle'])=='off road'){
				$productarray[$key][0]=$products['productCategoryName'];
				$productarray[$key][1]=$products['productCategoryName'];
			}
			else{
				$productarray[$key][0]=$products['productCategoryName']." ".$products['bodyStyle'];
				$productarray[$key][1]=$products['productCategoryName']." ".$products['bodyStyle'];
			}
        }
        $selCat = '';
        if(!empty($this->ObjSession->getSession("MODELTEST"))) {            
            $selCat = $this->ObjSession->getSession("MODELTEST");
        }
        
        $carArray=array('BMW'=>'BMW','Alfa Romeo'=>'Alfa Romeo','Aston Martin'=>'Aston Martin','Audi'=>'Audi','Bentley'=>'Bentley','Bugatti'=>'Bugatti','Buick'=>'Buick','Cadillac'=>'Cadillac','Chevrolet'=>'Chevrolet','Chrysler'=>'Chrysler','Citroen'=>'Citroen','Daewoo'=>'Daewoo','DAF'=>'DAF','Daihatsu'=>'Daihatsu','Datsun'=>'Datsun','DC'=>'DC','Dodge'=>'Dodge','Ferrari'=>'Ferrari','Fiat'=>'Fiat','Ford'=>'Ford','GMC'=>'GMC','Honda'=>'Honda','Hummer'=>'Hummer','Hyundai'=>'Hyundai','Infiniti'=>'Infiniti','Isuzu'=>'Isuzu','Jaguar'=>'Jaguar','Jeep'=>'Jeep','Kia'=>'Kia','Lada'=>'Lada','Lamborghini'=>'Lamborghini','Lancia'=>'Lancia','Land Rover'=>'Land Rover','Lexus'=>'Lexus','Lincoln'=>'Lincoln','Lotus'=>'Lotus','Mahindra'=>'Mahindra','Maserati'=>'Maserati','Maybach'=>'Maybach','Mazda'=>'Mazda','McLaren'=>'McLaren','Mercedes-Benz'=>'Mercedes-Benz','Mercury'=>'Mercury','MG'=>'MG','MINI'=>'MINI','Mitsubishi'=>'Mitsubishi','Nissan'=>'Nissan','Opel'=>'Opel','Peugeot'=>'Peugeot','Pontiac'=>'Pontiac','Porsche'=>'Porsche','Renault'=>'Renault','Rolls Royce'=>'Rolls Royce','Rover'=>'Rover','Saab'=>'Saab','SEAT'=>'SEAT','Skoda'=>'Skoda','Simca'=>'Simca','Smart'=>'Smart','SsangYong'=>'SsangYong','Suzuki'=>'Suzuki','TATA'=>'TATA','Toyota'=>'Toyota','Volkswagen'=>'Volkswagen','Volvo'=>'Volvo','Wartburg'=>'Wartburg','Other'=>'Other','No car'=>'No car');
        $newArray=array();
        $i=0;
        foreach($carArray as $key=>$currentCar){
            $newArray[$i][0]=$key;
            $newArray[$i][1]=$currentCar;
            $i++;
        }
        $params        = array(
            'limitFrom' => 0,
            'limitTo' => '',
            'languageIDs' => $languageIDs,
            'searchName' => '',
            'searchEmail' => '',
            'brandID'=>$this->ObjCommon->brandID,
            'status' => 'A'
        );
        $listShowrooms = $ShowroomsModel->testdriveShowrooms($params);
        $siteUrl                  = rtrim($this->getSettingValue('site_settings', 'global_http_url'), '/');
        $redUri                   = str_replace($siteUrl."/".$this->ObjView->_currLanguageLCID."/",'',$_SERVER['SCRIPT_URI']);
        $redUri                   = str_replace($siteUrl."/",'',$redUri);
        //echo $redUri;exit;
        if(empty($redUri)) {
            $redUri = 'testdrive/';
        }        
        if($this->ObjForm->isValid('formTestDrive','submitFormtestDrive')){
          
            $this->ObjSession->setSession("MODELTEST","");
            $languageIDs['Content']=$languageIDs['Current'];
             $params       = array(
                'showroomID' => $_POST['showroomID'],
                'languageIDs' => $languageIDs,
                'brandID'=>$this->ObjCommon->brandID     
                );
            $getShowroom = $ShowroomsModel->getShowroom($params);
            $_POST['brandID'] = $getShowroom['brandID'];
            $insert=$TestdriveModel->saveTestdrive($languageIDs,$_POST);
            if($insert){
				$sucssMsge = 'yes';
                 $paramsBrand            = array(
                    'languageIDs' => $languageIDs,
                    'brandID'     => $_POST['brandID']
                );
                 $brandInfo              = $ObjBrand->getBrand($paramsBrand);
                 $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'testdrive-notification-email-user');
                    $from                   = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $subject                = $emailbody['emailSubject'];
                    $userName               = $_POST['name'];
                    //email body
                    $bodytag                = str_replace('{$username}', $userName, $emailbody['emailHtml']);
                    $bodytag                = str_replace('{$modelname}', $_POST['model'], $bodytag);
                     $bodytag                = str_replace('{$showroomName}', $getShowroom['name'], $bodytag);
                     $bodytag                = str_replace('{$showroomAddress}', $getShowroom['address'], $bodytag);
                    //$bodytag                = str_replace('{$showroomPhone}', $getShowroom['phone'], $bodytag);
					$phone 					 = stripslashes(preg_replace('/\s+/', '', $getShowroom['phone']));
					$bodytag                = str_replace('{$showroomPhone}', '<a href="tel:'.$phone.'">'.$phone.'</a>', $bodytag);
                    $bodytag                = str_replace('{$showroomEmail}', $getShowroom['email'], $bodytag);
                    // $bodytag                = str_replace('{$showroomLatitude}', $getShowroom['latitude'], $bodytag);
                    // $bodytag                = str_replace('{$showroomLongitude}', $getShowroom['longitude'], $bodytag);
					$bodytag                = str_replace('{$mapLink}', $getShowroom['mapLink'], $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $body                          = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                    $mailSettings                  = $this->getSettingValue('mail_settings');
                    $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
                    $ObjMail                       = new Mail($mailSettings);
                     $to        =  trim(addslashes($_POST['emailID']));
                     $ObjMail->clearAddresses();
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($from, $to, $subject, $body);
                    if ($ObjMail->Send()) {
                    }
                
                    $emailbody              = $ObjEmailtemplate->getEmailTemlateDetails($languageIDs, '', 'testdrive-notification-email-admin');
                    $from                   = array(
                        $emailbody['emailFromEmail'],
                        $emailbody['emailFromName']
                    );
                    $subject                = $emailbody['emailSubject'];
                    $userName               = $_POST['name'];
                    
                    $emailID                           = $this->getSettingValue('product_cart_settings', 'book_test_drive_email');
                    //email body
                    $bodytag                = str_replace('{$userName}', $userName, $emailbody['emailHtml']);
                    $bodytag                = str_replace('{$franchisee}', $brandInfo['brandName'], $bodytag);
                    $bodytag                = str_replace('{$modelname}', $_POST['model'], $bodytag);
                    //$bodytag                = str_replace('{$userPhone}', $_POST['phone'], $bodytag);
					$bodytag                = str_replace('{$userPhone}', "+" . $_POST['countrycode']." ".$_POST['phone'], $bodytag);
                    $bodytag                = str_replace('{$userEmail}', $_POST['emailID'], $bodytag);
                    $bodytag                = str_replace('{$showroom}', $getShowroom['name'], $bodytag);
                    $bodytag                = str_replace('{$showroomAddress}', $getShowroom['address'], $bodytag);
                    $bodytag                = str_replace('{$showroomPhone}', $getShowroom['phone'], $bodytag);
                    $bodytag                = str_replace('{$showroomEmail}', $getShowroom['email'], $bodytag);
                    $bodytag                = str_replace('{$showroomLatitude}', $getShowroom['latitude'], $bodytag);
                    $bodytag                = str_replace('{$showroomLongitude}', $getShowroom['longitude'], $bodytag);
                    $bodytag                = str_replace('{$whenToBuy}', $_POST['whenTobuy'], $bodytag);
                    $bodytag                = str_replace('{$currentcar}', $_POST['currentCar'], $bodytag);
                    $this->ObjView->assign('emailbody', $bodytag);
                    $body                          = $this->ObjCommon->fetch("email_templates/Layout.tpl", $languageIDs);
                    $mailSettings                  = $this->getSettingValue('mail_settings');
                    $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
                    $ObjMail                       = new Mail($mailSettings);
                     $emailID        =  trim(addslashes($emailID));
                     $ObjMail->clearAddresses();
                    $ObjMail->IsHTML();
                    $ObjMail->sendMail($from, $emailID, $subject, $body);
                    if ($ObjMail->Send()) {
                    }
					echo "<script> fbq('track', 'CompleteRegistration');</script>";
                $this->setMessage("language.lblThankYouForTestdrive", "success");
                $this->setRedirect($redUri);
            }
        }
        //otpcountry list
        $languageIDs['Content']=$languageIDs['Current'];
        $resOTPCountry  =   $ObjOtpCountry->listOtpCountryOptions(array('status'=>'A','languageIDs'=>$languageIDs));
        $this->ObjView->assign('resCountry', $resOTPCountry);
        $this->ObjView->assign('listShowrooms', $listShowrooms);
        $this->ObjView->assign('productarray', $productarray);
        $this->ObjView->assign('selCat', $selCat);
        $this->ObjView->assign('currentCar', $newArray);
		$this->ObjView->assign('sucssMsge', $sucssMsge);
        $this->ObjView->display('Testdrive.tpl');
    }
    
}