<?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: PaymentController.php, v 1.0 2011/06/14 20:52:11
//
class PaymentController extends Controller {
    public function __construct() {
        parent::__construct();
        $this->ObjView->assign('statPageName', 'PaymentThanks');
    }
    public function indexAction() {
        $ObjOrder             = new OrderModel();
        $ObjSettings          = new SettingsModel();
        $ObjContent           = new ContentModel();
        $ObjCart              = new CartModel();
        $ObjProductList       = new ProductListModel();
        $ObjProduct      = new ProductModel();
        $ObjPaymentgateway    = new PaymentgatewayModel();
        $ObjCustomOption                = new CustomOptionModel();
        $ObjShowroom                    = new ShowroomsModel();
        $languageIDs          = $this->ObjView->languageIDs;
        $orderID              = $this->getRequestValue('id');
        $orderID              = $this->encryptDecrypt("decrypt",$orderID);
        $distinct_product_ids = array();
        $total_amount         = 0;
        $totalItemCount       = 0;
	$transIDs             = '';
		$brandID = $this->ObjCommon->brandID;
		$siteUrl = rtrim($ObjSettings->getSettingValuebyBrand('', 'global_https_url',$brandID), "/");
        $this->ObjView->assign('siteUrl', $siteUrl);
		
        $all_orders           = $ObjCart->getMasterAndChildOrders($orderID, $languageIDs['Current']);
        $getOrderDetails   = $ObjCart->getOrderMasterDetails($orderID);
        $orderItems    = $ObjCart->getOrderItemDetailsByParentOrderID($orderID,array(),'','Yes');
        if(empty($getOrderDetails)){
            $this->setRedirect("/index/");
        }
        $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,
            'productType' => $productType,
            'languageIDs' => $languageIDs,
            'selectedProductID' => $orderItems[0]['productID'],
            'userGroupID' => (int) $this->ObjCommon->REGISTERED_USER_GROUP_ID,
            'productStatus' => 'Active'
        );
        $resultProductProduct = $ObjProduct->getProductDetails($args);
        ////////////////////////////////////////
        $imagesetarr	=	explode('-',$resultProductProduct[0]['optionSKU']);
        $itemDetails              =   unserialize($orderItems[0]['extra']);
            $variantText = '';
            foreach ($itemDetails['customOptionValues'] as $values) {    
                $customOptionVariantID	=	$values[0]['customOptionVariantID'];
                $variantdetails	=	$ObjCustomOption->getVariantDetails($customOptionVariantID);
                if($values[0]['customOptionName']!='Wheel' && $values[0]['customOptionName']!='Trim')
                        $imagesetarr[]	=	$variantdetails['variantCode'];
                $variantText .= '<tr>
                                    <td style="font-family:Arial, Helvetica, sans-serif; color: #848586; font-size: 14px; padding:0px 0px 30px 50px;" width="160">'.$values[0]['customOptionName'].'</td>
                                    <td style="font-family:Arial, Helvetica, sans-serif; color: #111315; font-size: 14px; padding:0px 0px 30px 0px;">'.$values[0]['variantValue'].'</td>
                            </tr>';
            }
        $resProductSummaryImages  =   $ObjProduct->getProductImages(implode('_',$imagesetarr),'extr','yes',30,'thumb');
        $this->ObjView->assign('externalimage', $resProductSummaryImages[0]['Imageslist']);
        $this->ObjView->assign('productDetails', $resultProductProduct[0]);
        $this->ObjView->assign('getOrderDetails', $getOrderDetails);
        $psarr	=	array('showroomID'=>$itemDetails['showroom'],'languageIDs'=>$languageIDs,'brandID' => $this->ObjCommon->brandID);
        $resShowroomDets	=	$ObjShowroom->getShowroom($psarr);
      /*  if (!$userID) {
            if ($this->ObjSession->getSession("GUEST_ORDER_ID")) {
                if ($this->ObjSession->getSession("GUEST_EMAIL_ID") == $all_orders[0]['customer_email']) {
                    $this->ObjSession->setSession("GUEST_ORDER_ID", $this->ObjSession->getSession("GUEST_ORDER_ID") . ',' . $orderID);
                } else {
                    $this->ObjSession->unsetSession("GUEST_ORDER_ID");
                    $this->ObjSession->setSession("GUEST_ORDER_ID", $orderID);
                    $this->ObjSession->setSession("GUEST_EMAIL_ID", $all_orders[0]['customer_email']);
                }
            } else {
                $this->ObjSession->setSession("GUEST_EMAIL_ID", $all_orders[0]['customer_email']);
                $this->ObjSession->setSession("GUEST_ORDER_ID", $orderID);
            }
        }*/
        
        $enableChequeMoneyOrderDetails = 0;
        $chequeAccDetails              = array();
        $paymentSettingsGroupID        = $all_orders[0]['paymentSettingsGroupID'];
        $paymentSettingsGroupKeyDet    = $ObjPaymentgateway->getPaymentSettingGroupDetails($paymentSettingsGroupID);
        $paymentSettingsGroupKey       = $paymentSettingsGroupKeyDet['paySetGroupKey'];
        if($paymentSettingsGroupID<=0) {
            $paymentSettingsGroupKey =  'lblAccountCredit';
        }
        if ($paymentSettingsGroupKey == 'ChequeMoneyOrder') {
            $enableChequeMoneyOrderDetails = 1;
            $accNumberDetails              = $ObjPaymentgateway->listPaymentSettingsByGroupId($paymentSettingsGroupID, '', 'account_number');
            $accNumberDetails              = $accNumberDetails[0];
            $accNameDetails                = $ObjPaymentgateway->listPaymentSettingsByGroupId($paymentSettingsGroupID, '', 'account_name');
            $accNameDetails                = $accNameDetails[0];
            $chequeAccDetails['accName']   = $accNameDetails['paySetValue'];
            $chequeAccDetails['accNumber'] = $accNumberDetails['paySetValue'];
        } 
        if ($this->ObjSession->getSession("CART_REDIRECT ") == 'Yes' || $_SESSION['CART_REDIRECT']== 'Yes') {
            //encrypt email,name and phone info
            $ObjCart->updateOrderEmail($getOrderDetails['customer_email'],$getOrderDetails['billingFirstName'],$getOrderDetails['billingPhone'],$getOrderDetails['masterOrderID']);
            $amountTotal = $total_amount;
            $orderNumber = $orderNumbers;
            $this->ObjView->assign('enableChequeMoneyOrderDetails', $enableChequeMoneyOrderDetails);
            $this->ObjView->assign('chequeAccDetails', $chequeAccDetails);
            $productPurchaseMsg1 = str_replace("TEMPORDERID", $replaceOrderID, $this->getLanguageValue("lblProductPurchaseMsg1"));
            $this->ObjView->assign('thankYouMessage', $this->getLanguageValue("lblProductPurchaseThanks"));
            $this->ObjView->assign('productPurchaseMsg1', $productPurchaseMsg1);
            $this->ObjView->assign('amountTotal', $amountTotal);
            $this->ObjView->assign('orderIDs', $orderNumber);
            $this->ObjSession->unsetSession("CART_REDIRECT");
            $_SESSION['CART_REDIRECT'] = '';
            unset($_SESSION['CART_REDIRECT']);
            $paymentThanksContent = $ObjContent->getContentDetails($languageIDs, '', '', 'thank-you-for-buying-products');
            $this->ObjView->assign('paymentThanksTitle', $paymentThanksContent['contentTitle']);
            $this->ObjView->assign('paymentThanksDescription', $paymentThanksContent['content']);
            $this->ObjView->assign('content', $paymentThanksContent);
            $this->ObjView->assign('userID', $userID);
           
            $resBillAddress = unserialize($all_orders[0]['billingAddress']);
            $resShipAddress = unserialize($all_orders[0]['shippingAddress']);   
            
            $this->ObjView->assign('paymentSettingsGroupKey', $paymentSettingsGroupKey);
            $this->ObjView->assign('all_orders', $all_orders);
            $this->ObjView->assign('shippingStatus',$shippingStatus); 
            if($userPhone!=''){				 
                $orderNumbers		=	isset($orderNumber)?implode(',', $orderNumber):'';
                $orderPrice		=	 $this->ObjView->getFormattedCurrency($amountTotal, '', 0, 0,'No');
                $link=$this->getSettingValue('site_settings', 'global_http_url')."/user/purchases/";
                $ObjSmsTemplate            = new SmstemplateModel();
                $messageBody                    = $ObjSmsTemplate->getSmsTempDetails('', $languageIDs,'sms_buyer_order_generate');
				
		//  sms body
                $bodytag                = str_replace('(1)', $orderNumbers, $messageBody['smsTemplateContent']);
                $bodytag                = str_replace('(2)', $orderPrice, $bodytag);
                $bodytag                = str_replace('(3)', $link, $bodytag);
                //$msgKey = "(1),*,".$orderNumbers.",@,(2),*,".$orderPrice.",@,(3),*,".$link;			
                $user_id=$this->getSettingValue('sms_settings', 'sms_username');
                $password=$this->getSettingValue('sms_settings', 'sms_password');
                $userPhoneFull=str_replace("-","",$userPhone);
//                if (strpos($userPhone, "05") === 0){
//                  $userPhoneFull          = '966'.ltrim($userPhone, '0');	
//                }else{
//                  $userPhoneFull          = '91'.$userPhone;	
//                }

                $sms = new Sms($user_id, $password);
                $result	=	$sms->setSms($bodytag,$userPhoneFull,'Normal',$msgKey);

                }			
               			
           		            
               if($shippingStatus=='Pending') {
                    $this->ObjView->assign('shippingDate',date('l jS \ M Y',strtotime($all_orders[0]['orderCreatedDate'])));
                    $this->ObjView->assign('shippingTime',date('H:i:s a',strtotime($all_orders[0]['orderCreatedDate'])));
               } else {
                    $this->ObjView->assign('shippingDate',date('l jS \ M Y',strtotime($shippingDet['activityDate'])));
                    $this->ObjView->assign('shippingTime',date('H:i:s a',strtotime($shippingDet['activityDate'])));
               }
                $this->ObjView->assign('orderProcessDate',date('l jS \ M Y',strtotime($all_orders[0]['orderCreatedDate'])));
                $this->ObjView->assign('orderProcessTime',date('H:i:s a',strtotime($all_orders[0]['orderCreatedDate'])));
                $this->ObjView->assign('all_orders_count',$totalItemCount);
                $this->ObjView->assign('orderCreatedDate',date('d F, Y H:i:s a',strtotime($all_orders[0]['orderCreatedDate'])));
                $this->ObjView->assign('transIDs',$transIDs);
                //echo '<pre>'; print_r($resBillAddress);exit;
                $this->ObjView->display('PaymentThanks.tpl');
           } 
            else {
                $this->setRedirect("/index/");
            }
    }
    //END OF FUNCTION
    //TO FOLLOW OR UNFOLLOW BUSINESS
    public function ajaxFollowAction() {
        $ObjBusinessModel     = new BusinessModel();
        $businessID           = $_POST['businessID'];
        $userID               = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $followBusinessInsert = $ObjBusinessModel->saveFollowBusiness($businessID, $userID);
        echo $followBusinessInsert;
        exit;
    }
    //END OF FUNCTION
    public function setProductSharingSettings() {
        $siteUrl = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/");
        $this->ObjView->assign('siteUrl', $siteUrl);
        //Twitter
        $settingsTwitterPostNewProductOn   = $this->getSettingValue('social_media_settings', 'twitter_post_new_product_on');
        $settingsTwitterProductPostMessage = $this->getSettingValue('social_media_settings', 'twitter_product_post_message');
        $this->ObjView->assign('settingsTwitterPostNewProductOn', $settingsTwitterPostNewProductOn);
        $this->ObjView->assign('settingsTwitterProductPostMessage', preg_replace('/\s+/', ' ', str_replace("<br />", '\n', nl2br($settingsTwitterProductPostMessage))));
        //Facebook	
        $settingsFacebookNewProductOnWall   = $this->getSettingValue('social_media_settings', 'facebook_new_product_on_wall');
        $settingsFacebookProductPostMessage = $this->getSettingValue('social_media_settings', 'facebook_product_post_message');
        $this->ObjView->assign('settingsFacebookNewProductOnWall', $settingsFacebookNewProductOnWall);
        //Google Plus
        $settingsGooglePlusNewProductOnWall = $this->getSettingValue('social_media_settings', 'googleplus_new_product_on_wall');
        $this->ObjView->assign('settingsGooglePlusNewProductOnWall', $settingsGooglePlusNewProductOnWall);
        //Pinterest
        $settingsPinterestNewProductOnWall   = $this->getSettingValue('social_media_settings', 'pinterest_new_product_on_wall');
        $settingsPinterestProductPostMessage = $this->getSettingValue('social_media_settings', 'pinterest_product_post_message');
        $this->ObjView->assign('settingsPinterestNewProductOnWall', $settingsPinterestNewProductOnWall);
        $this->ObjView->assign('settingsPinterestProductPostMessage', preg_replace('/\s+/', ' ', str_replace("<br />", '\n', nl2br($settingsPinterestProductPostMessage))));
    }
}