AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.216.139
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/www/lrsys_projetos/sopizzas/application/controllers/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_projetos/sopizzas/application/controllers/createorderfrontend.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
require_once APPPATH."third_party/Services/Twilio.php";
// require_once APPPATH."third_party/PinPayment/autoload.php";
// use Omnipay\Omnipay;
// use Omnipay\Common\CreditCard;
class CreateOrderFrontend extends CI_Controller {

  function __construct()
  {
     parent::__construct();
     $this->load->helper("url");
     $this->load->helper('form');
     $this->load->library('session');
     $this->load->library('cart');
     $this->load->model('createorder_model');
     $this->load->model('frontend_model');
     $this->load->model('dashboard_model');
     $this->load->model('user');
     // $this->load->library('braintree_lib');
     $this->load->library('mypaypal');
     $this->load->library('myemail');
     //$this->load->library('pinpaymentlib');
     $this->config->load('facebook');
     if($this->session->userdata('user_language'))
      {
        $language = $this->session->userdata('user_language');
      }
      else
      {
        $language = $this->config->item("language");
      }
      $data['user_language'] =  $language;
      $this->lang->load('frontpage', $language);
  }
  function index()
  {
    if ($this->input->server('REQUEST_METHOD') == 'POST') {
      $this->placeOrder();
    }
  }
  function testNotify() {
    $apiKey = ANDROID_PUSH_API;//AIzaSyAfAtTYhdwxYR9csZtyI3wOlAMl-JjcViw
    $message = 'New order is placed. Please check.';
    $messageData = array('message'=> $message, 'title'=> "New delivery task", 'appredirect'=> "",'order_id'=>288);
    $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $apiKey);
    $data = array(
      'data' => $messageData,
      'registration_ids' => array('e78NFbyM1Bg:APA91bG_E7Q_raQ2IbV4FBLM1nSHMQTKhlAdcc03BiiMEnHEHkUw3T1Me5GWXfby4VpYfrj2TKmnIl1hwkYAMa5-3x4b-pDkixoxIyrAthWF9ZO1SPXG0h5uHMK6GdH6jvHoVA_KdkW6')
      // 'registration_ids' => array('eAPpP8rcdPU:APA91bHWCcFJ9R0F2lUny0iks7HEf0S1Eirlk4AOTS3U5BWsy4oy3cbUCqzlsGkEtBgweqGwAAMOFNCwqrs84-HIpAJDbycFGVJVeV170YsTSNxNryna2mLb3mv3eU-Py9biRoN_luw0')
    );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, "https://fcm.googleapis.com/fcm/send" );
    curl_setopt( $ch, CURLOPT_POST, true );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); 
    curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) );
    $response = curl_exec($ch);
    curl_close($ch);
    echo $response;
  }
  function testPinPayment()
  {
      $SECRET_KEY = $this->config->item("pin_payment_key");
      $IS_LIVE = $this->config->item("pin_payment_is_live");
      $IS_TEST = false;
      if(!$IS_LIVE) $IS_TEST = true;
      $gateway = Omnipay::create('Pin');
      // Initialise the gateway
      $gateway->initialize(array(
          'secretKey' => $SECRET_KEY,
          'testMode'  => $IS_TEST, // Or false when you are ready for live transactions
      ));
       // Create a credit card object
       // This card can be used for testing.
       // See https://pin.net.au/docs/api/test-cards for a list of card
       // numbers that can be used for testing.
       $card = new CreditCard(array(
              'firstName'    => 'Example',
              'lastName'     => 'Customer',
              'number'       => '4200000000000000',
              'expiryMonth'  => '01',
              'expiryYear'   => '2020',
              'cvv'          => '123',
              'email'        => 'customer@example.com',
              'billingAddress1'       => '1 Scrubby Creek Road',
              'billingCountry'        => 'AU',
              'billingCity'           => 'Scrubby Creek',
              'billingPostcode'       => '4999',
              'billingState'          => 'QLD',
      ));
      // Do a purchase transaction on the gateway
      $transaction = $gateway->purchase(array(
          'description'              => 'Your order for widgets',
          'amount'                   => '10.00',
          'currency'                 => 'AUD',
          'clientIp'                 => $_SERVER['REMOTE_ADDR'],
          'card'                     => $card,
      ));
      $response = $transaction->send();
      $this->pr($response);
      if ($response->isSuccessful()) {
           echo "Purchase transaction was successful!\n";
           $sale_id = $response->getTransactionReference();
           echo "Transaction reference = " . $sale_id . "\n";
       }
  }
  function showItemDetails() {
    $menu_id = $this->input->post('id');

    $menudetails=$this->frontend_model->GetMenuDetails($menu_id);

    if($menudetails['menu_photo']!=''){
      $menu_photo_file_path=FCPATH.MENU_IMAGE_PATH_THUMBS.$menudetails['menu_photo'];
      if (file_exists($menu_photo_file_path)) {
            $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.$menudetails['menu_photo'];
         } 
         else {
            $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.MENU_IMAGE_DEFAULT_IMAGE;
         }
      }
      else {
        $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.MENU_IMAGE_DEFAULT_IMAGE;
      }

      $Fixprice='';
      $dataSize='';
      $dataSubAddons='';
      $dataAddonsHeader='';
      $spl_instruction ='';
      $dataAddons ='';
      if($menudetails['sizeoption']=='size') {
        $MenuSize=$this->frontend_model->GetMenuSize($menudetails['id']);
        if(is_array($MenuSize) && sizeof($MenuSize)>0) {
          $dataSize='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                          <span class="col-md-3 col-sm-4 col-xs-12">
                            '.$this->lang->line('Price').'
                          </span><span class="col-md-9 col-sm-8 col-xs-12 paddingleft0">';
          // making menu size checkbox
          foreach($MenuSize as $key=>$row2) { 
            if ($key == 0) {
              $checked = 'checked';
              $dataSize .= "<input type=\"hidden\" name=\"mySizePrice\" id=\"mySizePrice\" value=\"".trim(htmlentities($row2['menu_slice_price']))."\">
              <input type=\"hidden\" name=\"mySizeName\" id=\"mySizeName\" value=\"".trim(htmlentities($row2['menu_slice_name']))."\">
              <input type=\"hidden\" name=\"mySizeId\" id=\"mySizeId\" value=\"".trim(htmlentities($row2['menu_slice_id']))."\">";
            }
            else {
              $checked = '';
            }
            $dataSize .="
              <span class=\"col-md-6 col-sm-6 col-xs-12\">
                <input name=\"sizegroup\" class=\"\" type=\"radio\" data-size-name=\"".trim(htmlentities($row2['menu_slice_name']))."\"  data-size-id=\"".trim(htmlentities($row2['menu_slice_id']))."\" data-size-price=\"".trim(htmlentities($row2['menu_slice_price']))."\" onclick=\"setSizeDetails(this)\" ".$checked."></input>
      <label for=\"radio\"><span><span></span></span>".htmlentities($row2['menu_slice_name']).' - '.SITENAME_CURRENCY.$row2['menu_slice_price']."</label>
                
              </span>
              ";
          }
          $dataSize .='</span></span>';
        }

      }
      else {
        // fix price
        $Fixprice='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                    <span class="col-md-3 col-sm-4 col-xs-6">
                      '.$this->lang->line('Price').'
                    </span>
                    <span class="col-md-9 col-sm-8 col-xs-6">
                      '.SITENAME_CURRENCY.$menudetails['menu_price'].'
                    </span>
                  </span>';
      }

      if($menudetails['menu_addons']=='Yes') {
        $MenuAddonsHeader=$this->frontend_model->GetMenuAddonsHeader($menudetails['id']);
        if(is_array($MenuAddonsHeader) && sizeof($MenuAddonsHeader)>0) {
          foreach($MenuAddonsHeader as $key=>$row3) { 
            $dataSubAddons='';
            $dataAddonsHeader ='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                          <span class="col-md-3 col-sm-4 col-xs-12">
                            '.$row3['menuaddons_addonsname'].'<br><span style="color: red;">('.$this->lang->line('Choose_up_to').' <span id="addonChooseUpto_'.$row3['menuaddons_id'].'" data-old-count="'.$row3['menuaddons_addonscount'].'" class="commonChooseUpto">'.$row3['menuaddons_addonscount'].'</span>)</span>
                          </span>';

            $MenuSubAddons=$this->frontend_model->GetMenuSubAddons($row3['menuaddons_id']);
            if(is_array($MenuSubAddons) && sizeof($MenuSubAddons)>0) {
              $dataSubAddons ='<span class="col-md-9 col-sm-8 col-xs-12 paddingleft0">';
              foreach($MenuSubAddons as $key=>$row4) { 
                if($row4['menuaddons_price']!='0') {
                  $addonsPrice=SITENAME_CURRENCY.$row4['menuaddons_price'];
                }
                else {
                  $addonsPrice=''.$this->lang->line('Free').'';
                }
                // addon price and name
                $dataSubAddons .='<span class="col-md-6 col-sm-6 col-xs-12 commonParent addonSingleWrap" id="addonParent_'.$row3['menuaddons_id'].'">
                        <input onclick="addonLimit('.$row3['menuaddons_addonscount'].','.$row4['menuaddons_id'].','.$row3['menuaddons_id'].'); setAddonDetails(this,'.$row3['menuaddons_id'].','.$row4['menuaddons_id'].');" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" id="advacce_menu_'.$row4['menuaddons_id'].'" class="single-checkbox_'.$row3['menuaddons_id'].' commonCheckbox" name="addons" type="checkbox"></input><label for="checkbox"><span></span>'.$row4['menuaddons_addonsname'].' ('.$addonsPrice.')<br>
                        </label>
                        <br>
                        <i class="fa fa-minus-square-o fa-lg" style="cursor:pointer" aria-hidden="true" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" onclick="changeAddonCount(this, '.$row4['menuaddons_id'].', '.$row3['menuaddons_id'].', \''."d".'\', '.$row3['menuaddons_addonscount'].')"></i>
                         <span class="commonAddonQuantity" id="addon-qty-'.$row4['menuaddons_id'].'" onchange="setAddonDetails(this,'.$row3['menuaddons_id'].','.$row4['menuaddons_id'].')">1</span>
                         <i class="fa fa-plus-square-o fa-lg" style="cursor:pointer" aria-hidden="true" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" onclick="changeAddonCount(this, '.$row4['menuaddons_id'].', '.$row3['menuaddons_id'].', \''."i".'\', '.$row3['menuaddons_addonscount'].')"></i>
                      </span>';
              }
              $dataAddons .=$dataAddonsHeader.$dataSubAddons.'</span></span>';
            }
            $dataAddons .= '<input type="hidden" name="myAddonList[]" class="commonMyAddonList" id="myAddonList_'.$row3['menuaddons_id'].'">';                            
          }
        }                      
      }


      if($menudetails['menu_spl_instruction']!='No'){

        $spl_instruction = '<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                                <span class="col-md-3 col-sm-4 col-xs-12">
                                  '.$this->lang->line('Special_Instructions').'
                                </span>
                                <span class="col-md-9 col-sm-8 col-xs-12">
                                  <textarea class="areatext" style="" class="form-control" rows="5" id="mySpclInst" name="mySpclInst"></textarea>
                                  <p>'.$this->lang->line('Example').'</p>
                                </span>
                              </span>';
      }
      $optionList = '';
      for ($i=1; $i < 21; $i++) { 
        $optionList .= '<option value="'.$i.'">'.$i.'</option>';
      }
      $dataPopup = '<div class="modal-dialog">
                        <input type="hidden" name="myMenuId" id="myMenuId" value="'.$menudetails['id'].'">
                        <input type="hidden" name="myMenuName" id="myMenuName" value="'.$menudetails['menu_name'].'">
                        <input type="hidden" name="myMenuPrice" id="myMenuPrice" value="'.$menudetails['menu_price'].'">
                        <input type="hidden" name="myMenuType" id="myMenuType" value="'.$menudetails['sizeoption'].'">
                        
                        <!-- Modal content-->
                        <div class="modal-content">
                          <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"></button>
                            <h4 class="modal-title text-center">'.$this->lang->line('Add_item_to_cart').'</h4>
                          </div>
                          <div class="modal-body">
                            <div class="col-md-12 col-sm-12 custom-padding-0">
                              <div class="col-md-8 col-sm-8">
                                <h3> '.$menudetails['menu_name'].'</h3>
                                <p style="font-size:15px;">'.$menudetails['menu_description'].'</p>
                              </div>
                              <div class="col-md-4 col-sm-4">
                                <img src="'.$menu_image_name_with_path.'" class="addcart-img">
                              </div>
                            </div>
                            <div class="col-md-12 custom-padding-0 price-body">
                              <span class="col-md-12 col-sm-12 col-xs-12 value-box">
                                <span class="col-md-3 col-sm-4 col-xs-6">
                                  '.$this->lang->line('Quantity').'
                                </span>
                                <span class="col-md-9 col-sm-8 col-xs-6">
                                  <select style="padding: 7px;" data-old-qty="1" class="" id="myMenuQty" name="myMenuQty" onchange="resetAddon(this)">
                                    '.$optionList.'
                                  </select>
                                </span>
                              </span>
                              '.$Fixprice.'
                              '.$dataSize.'
                              '.$dataAddons.'

                              '.$spl_instruction.'

                              <div class="clearfix"></div>
                              <div class="col-md-12 text-center mct30">
                                <button type="button" class="btn btn-info cos-mh-btn" style="float:none;" onclick="addOrder()">'.$this->lang->line('Add_to_Cart').'</button>
                              </div>
                            </div>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">'.$this->lang->line('Close').'</button>
                          </div>
                        </div>
                      </div>';

    echo $dataPopup;
  }
  function showEditItemDetails() {
    $menu_id = $this->input->post('id');
    $rowid = $this->input->post('rowid');
    $cartEditId = '<input type="hidden" id="cartEditId" name="cartEditId" value="'.$rowid.'">';

    $menudetails=$this->frontend_model->GetMenuDetails($menu_id);

    if ($this->cart->contents()[$rowid]) {
      $oldContent = $this->cart->contents()[$rowid];
      $oldQty = $oldContent['qty'];
      if ($oldContent['size_name'] != '') {
        $oldSizeId = $oldContent['size_id'];
        $oldSizeName = $oldContent['size_name'];
      }
      $oldPrice = $oldContent['price'];
      $oldInstruction = $oldContent['instruction'];
      if (is_array($oldContent['addons']) && count($oldContent['addons']) > 0) {
        $oldIfAddons = true;
        $oldAddons = $oldContent['addons'];
      }
      else {
        $oldIfAddons = false;
      }
    }

    if($menudetails['menu_photo']!=''){
      $menu_photo_file_path=FCPATH.MENU_IMAGE_PATH_THUMBS.$menudetails['menu_photo'];
      if (file_exists($menu_photo_file_path)) {
            $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.$menudetails['menu_photo'];
         } 
         else {
            $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.MENU_IMAGE_DEFAULT_IMAGE;
         }
      }
      else {
        $menu_image_name_with_path=base_url().MENU_IMAGE_PATH_THUMBS.MENU_IMAGE_DEFAULT_IMAGE;
      }

      $Fixprice='';
      $dataSize='';
      $dataSubAddons='';
      $dataAddonsHeader='';
      $spl_instruction ='';
      $dataAddons ='';
      if($menudetails['sizeoption']=='size') {
        $MenuSize=$this->frontend_model->GetMenuSize($menudetails['id']);
        if(is_array($MenuSize) && sizeof($MenuSize)>0) {
          $dataSize='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                          <span class="col-md-3 col-sm-4 col-xs-12">
                     '.$this->lang->line('Price').'
                          </span><span class="col-md-9 col-sm-8 col-xs-12 paddingleft0">';
          // making menu size checkbox
          $checkSize = 1;
          foreach($MenuSize as $key=>$row2) { 
            if ($row2['menu_slice_id'] == $oldSizeId) {
              $checkSize++;
              $checked = 'checked';
              $dataSize .= "<input type=\"hidden\" name=\"mySizePrice\" id=\"mySizePrice\" value=\"".trim(htmlentities($row2['menu_slice_price']))."\">";
              $dataSize .="
              <span class=\"col-md-6 col-sm-6 col-xs-12\">
                <input name=\"sizegroup\" class=\"\" type=\"radio\" data-size-id=\"".trim(htmlentities($row2['menu_slice_id']))."\" data-size-name=\"".trim(htmlentities($row2['menu_slice_name']))."\" data-size-price=\"".trim(htmlentities($row2['menu_slice_price']))."\" onclick=\"setSizeDetails(this)\" ".$checked."></input>
      <label for=\"radio\"><span><span></span></span>".htmlentities($row2['menu_slice_name']).' - '.SITENAME_CURRENCY.$row2['menu_slice_price']."</label>
                
              </span>
              <input type=\"hidden\" name=\"mySizeName\" id=\"mySizeName\" value=\"".trim(htmlentities($row2['menu_slice_name']))."\">
              <input type=\"hidden\" name=\"mySizeId\" id=\"mySizeId\" value=\"".trim(htmlentities($row2['menu_slice_id']))."\">";
            }
            else {
              $checked = '';
              $dataSize .="
              <span class=\"col-md-6 col-sm-6 col-xs-12\">
                <input name=\"sizegroup\" class=\"\" type=\"radio\" data-size-id=\"".trim(htmlentities($row2['menu_slice_id']))."\" data-size-name=\"".trim(htmlentities($row2['menu_slice_name']))."\" data-size-price=\"".trim(htmlentities($row2['menu_slice_price']))."\" onclick=\"setSizeDetails(this)\" ".$checked."></input>
      <label for=\"radio\"><span><span></span></span>".htmlentities($row2['menu_slice_name']).' - '.SITENAME_CURRENCY.$row2['menu_slice_price']."</label>
                
              </span>
              ";
            }
          }
          if ($checkSize == 1) {
            $dataSize .="<input type=\"hidden\" name=\"mySizeName\" id=\"mySizeName\" value=\"\">
              <input type=\"hidden\" name=\"mySizeId\" id=\"mySizeId\" value=\"\"></span></span>";
          }
          else {
            $dataSize .="</span></span>";
          }
        }

      }
      else {
        // fix price
        $Fixprice='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                    <span class="col-md-3 col-sm-4 col-xs-6">
               '.$this->lang->line('Price').'
                    </span>
                    <span class="col-md-9 col-sm-8 col-xs-6">
                      '.SITENAME_CURRENCY.$menudetails['menu_price'].'
                    </span>
                  </span>';
      }

      if($menudetails['menu_addons']=='Yes') {
        $MenuAddonsHeader=$this->frontend_model->GetMenuAddonsHeader($menudetails['id']);
        if(is_array($MenuAddonsHeader) && sizeof($MenuAddonsHeader)>0) {
          foreach($MenuAddonsHeader as $key=>$row3) { 
            $dataSubAddons='';
            $dataAddonsHeader ='<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                          <span class="col-md-3 col-sm-4 col-xs-12">
                            '.$row3['menuaddons_addonsname'].'<br><span style="color: red;">('.$this->lang->line('Choose_up_ to').' <span id="addonChooseUpto_'.$row3['menuaddons_id'].'" data-old-count="'.$row3['menuaddons_addonscount'].'" class="commonChooseUpto">'.($row3['menuaddons_addonscount'] * $oldQty).'</span>)</span>
                          </span>';

            $MenuSubAddons=$this->frontend_model->GetMenuSubAddons($row3['menuaddons_id']);
            if(is_array($MenuSubAddons) && sizeof($MenuSubAddons)>0) {
              $dataSubAddons ='<span class="col-md-9 col-sm-8 col-xs-12 paddingleft0">';
              foreach($MenuSubAddons as $key=>$row4) { 
                if($row4['menuaddons_price']!='0') {
                  $addonsPrice=SITENAME_CURRENCY.$row4['menuaddons_price'];
                }
                else {
                  $addonsPrice=''.$this->lang->line('Free').'';
                }
                // addon price and name
                if (isset($oldAddons[$row4['menuaddons_id']])) {
                  $addon_qty = $oldAddons[$row4['menuaddons_id']]['addon_qty'];
                  $addonChecked = 'checked';
                }
                else {
                  $addon_qty = 1;
                  $addonChecked = '';
                }
                $dataSubAddons .='<span class="col-md-6 col-sm-6 col-xs-12 commonParent addonSingleWrap" id="addonParent_'.$row3['menuaddons_id'].'">
                        <input '.$addonChecked.' onclick="addonLimit('.$row3['menuaddons_addonscount'].','.$row4['menuaddons_id'].','.$row3['menuaddons_id'].'); setAddonDetails(this,'.$row3['menuaddons_id'].','.$row4['menuaddons_id'].');" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" id="advacce_menu_'.$row4['menuaddons_id'].'" class="single-checkbox_'.$row3['menuaddons_id'].' commonCheckbox" name="addons" type="checkbox"></input><label for="checkbox"><span></span>'.$row4['menuaddons_addonsname'].' ('.$addonsPrice.')<br>
                        </label>
                        <br>
                        <i class="fa fa-minus-square-o fa-lg" style="cursor:pointer" aria-hidden="true" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" onclick="changeAddonCount(this, '.$row4['menuaddons_id'].', '.$row3['menuaddons_id'].', \''."d".'\', '.$row3['menuaddons_addonscount'].')"></i>
                         <span class="commonAddonQuantity" id="addon-qty-'.$row4['menuaddons_id'].'">'.$addon_qty.'</span>
                         <i class="fa fa-plus-square-o fa-lg" style="cursor:pointer" aria-hidden="true" data-addon-id="'.$row4['menuaddons_id'].'" data-addon-name="'.trim(htmlentities($row4['menuaddons_addonsname'])).'" data-addon-price="'.trim(htmlentities($row4['menuaddons_price'])).'" onclick="changeAddonCount(this, '.$row4['menuaddons_id'].', '.$row3['menuaddons_id'].', \''."i".'\', '.$row3['menuaddons_addonscount'].')"></i>
                      </span>';
              }
              $dataAddons .=$dataAddonsHeader.$dataSubAddons.'</span></span>';
            }
            if ($oldIfAddons) {
              $myString = '';
              foreach ($oldAddons as $oldKey => $oldValue) {
                if ($oldValue['parent_id'] == $row3['menuaddons_id']) {
                  $myString .= ','.$oldValue['addon_original_name'].'|'.$oldValue['addon_price'].'|'.$oldValue['addon_qty'].'|'.$oldValue['addon_id'].'|'.$oldValue['parent_id'];
                }
              }
              $dataAddons .= '<input type="hidden" name="myAddonList[]" class="commonMyAddonList" id="myAddonList_'.$row3['menuaddons_id'].'" value="'.$myString.'">';
            }
            else {
              $dataAddons .= '<input type="hidden" name="myAddonList[]" class="commonMyAddonList" id="myAddonList_'.$row3['menuaddons_id'].'">';
            }                            
          }
        }                      
      }


      if($menudetails['menu_spl_instruction']!='No'){

        $spl_instruction = '<span class="col-md-12 col-sm-12 col-xs-12 value-box">
                                <span class="col-md-3 col-sm-4 col-xs-12">
                                  '.$this->lang->line('Special_Instructions').'
                                </span>
                                <span class="col-md-9 col-sm-8 col-xs-12">
                                  <textarea class="areatext" style="" class="form-control" rows="5" id="mySpclInst" name="mySpclInst">'.$oldInstruction.'</textarea>
                                  <p>'.$this->lang->line('Example').'</p>
                                </span>
                              </span>';
      }
      $optionList = '';
      for ($i=1; $i < 21; $i++) { 
        if ($i == $oldQty) {
          $selected = 'selected';
        }
        else {
          $selected = '';
        }
        $optionList .= '<option value="'.$i.'" '.$selected.'>'.$i.'</option>';
      }
      $dataPopup = '<div class="modal-dialog">
                        <input type="hidden" name="myMenuId" id="myMenuId" value="'.$menudetails['id'].'">
                        <input type="hidden" name="myMenuName" id="myMenuName" value="'.$menudetails['menu_name'].'">
                        <input type="hidden" name="myMenuPrice" id="myMenuPrice" value="'.$menudetails['menu_price'].'">
                        <input type="hidden" name="myMenuType" id="myMenuType" value="'.$menudetails['sizeoption'].'">
                        '.$cartEditId.'
                        <!-- Modal content-->
                        <div class="modal-content">
                          <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"></button>
                            <h4 class="modal-title text-center">'.$this->lang->line('Update_Cart_Item').'Update Cart Item</h4>
                          </div>
                          <div class="modal-body">
                            <div class="col-md-12 col-sm-12 custom-padding-0">
                              <div class="col-md-8 col-sm-8">
                                <h3> '.$menudetails['menu_name'].'</h3>
                                <p style="font-size:15px;">'.$menudetails['menu_description'].'</p>
                              </div>
                              <div class="col-md-4 col-sm-4">
                                <img src="'.$menu_image_name_with_path.'" class="addcart-img">
                              </div>
                            </div>
                            <div class="col-md-12 custom-padding-0 price-body">
                              <span class="col-md-12 col-sm-12 col-xs-12 value-box">
                                <span class="col-md-3 col-sm-4 col-xs-6">
                                  '.$this->lang->line('Quantity').'
                                </span>
                                <span class="col-md-9 col-sm-8 col-xs-6">
                                  <select style="padding: 7px;" data-old-qty="'.$oldQty.'" class="" id="myMenuQty" name="myMenuQty" onchange="resetAddon(this)">
                                    '.$optionList.'
                                  </select>
                                </span>
                              </span>
                              '.$Fixprice.'
                              '.$dataSize.'
                              '.$dataAddons.'

                              '.$spl_instruction.'

                              <div class="clearfix"></div>
                              <div class="col-md-12 text-center mct30">
                                <button type="button" class="btn btn-info cos-mh-btn" style="float:none;" onclick="addOrder()">'.$this->lang->line('Update_Cart').'</button>
                              </div>
                            </div>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">'.$this->lang->line('Close').'</button>
                          </div>
                        </div>
                      </div>';

    echo $dataPopup;
  }
  function addOrder() {
    // print_r($this->input->post());
    //$cart = $this->cart->contents();
    if ($this->input->post('cartEditId')) {
      $data = array(
        'rowid' => $this->input->post('cartEditId'),
        'qty'   => 0
      );
      $this->cart->update($data);
    }
    $menu_id = $this->input->post('myMenuId');
    $menu_qty = $this->input->post('myMenuQty');
    $menu_price = $this->input->post('myMenuPrice');
    $menu_name = $this->input->post('myMenuName');
    
    $menu_size = $this->input->post('myMenuType');
    $menu_addon_array = $this->input->post('myAddonList');
    $menu_size_name = $this->input->post('mySizeName');
    $menu_size_id = $this->input->post('mySizeId');
    $menu_size_price = $this->input->post('mySizePrice');
    $menu_spcl_inst = $this->input->post('mySpclInst');
    if ($menu_spcl_inst == '0' || $menu_spcl_inst == 0) {
      $menu_spcl_inst = '';
    }
    if (is_array($menu_addon_array)) {
      $menu_addon_string = implode(',', $menu_addon_array);
    }
    else {
      $menu_addon_string = '';
    }

    $addonArray = array();

    $menuExist = 0;

    if ($menuExist == 0) {
      if ($menu_size == 'size' && $menu_size_name != '') {
        $menu_name = $menu_name;
        $menu_price = $menu_size_price;
      }

      if ($menu_addon_string != '') {
        $menu_addon = array_filter(explode(',', $menu_addon_string));
        foreach ($menu_addon as $key => $value) {
          $myArray = explode('|', $value);
          $addonArray[$myArray[3]]['addon_name'] = $myArray[0]." (".$myArray[2]." x ".SITENAME_CURRENCY.$myArray[1].")";
          $addonArray[$myArray[3]]['addon_original_name'] = $myArray[0];
          $addonArray[$myArray[3]]['addon_price'] = $myArray[1];
          $addonArray[$myArray[3]]['addon_qty'] = $myArray[2];
          $addonArray[$myArray[3]]['addon_id'] = $myArray[3];
          $addonArray[$myArray[3]]['parent_id'] = $myArray[4];
        }
      }
      $options = array('size_id' => $menu_size_id, 'addons' => $addonArray);
      $data = array(
          'id'              =>  intval($menu_id),
          'qty'             =>  intval($menu_qty),
          'price'           =>  floatval($menu_price),
          'name'            =>  $menu_name,
          'size_name'       =>  $menu_size_name,
          'size_id'         =>  $menu_size_id,
          'addons'          =>  $addonArray,
          'instruction'     =>  $this->input->post('mySpclInst'),
          'options'         =>  $options
        );
      $this->cart->insert($data);
    }
    $this->updateCartView();
    // print_r($this->cart->contents());
    //$this->cart->destroy();
  }
  function changeOrderType() {
    $orderType = $this->input->post('orderType');
    $this->updateCartView($orderType);
  }
  function updateCartView($orderType = '') {

    //$cart = array_reverse($this->cart->contents());
    if ($orderType == '') {
      if ($this->session->userdata('cartData')) {
        $cartData = $this->session->userdata('cartData');
        if (isset($cartData['orderType'])) {
          $orderType = $cartData['orderType'];
        }
      }
    }
    $cart = $this->cart->contents();
    $myHtml = '';
    $subtotal = 0;
    $grandtotal = 0;
    if ($cart) {
      $myHtml .= '<div class="table-responsive" style="max-height: 200px;">
                    <table class="table table-hover table-bordered" id="add-cart">
                      <tbody>';
      foreach ($cart as $key => $value) {
        $subtotal = $subtotal + $value['subtotal'];
        if ($value['size_name'] != '') {
          $name = $value['name'].' ('.$value['size_name'].')';
        }
        else {
          $name = $value['name'];
        }
      $addonsHtml = '';
      $itemAddonPrice = 0;
      if (is_array($value['addons']) && count($value['addons']) > 0) {
        //$addonsHtml .= '<div class="cartItemAddon">';
        $i = 1;
        foreach ($value['addons'] as $keys => $values) {
          $itemAddonPrice = $itemAddonPrice + floatval($values['addon_price']) * $values['addon_qty'];
          $subtotal = $subtotal + (floatval($values['addon_price']) * $values['addon_qty']);
          if ($i > 1) {
            //$addonsHtml .= ', ';
          }
          if ($addonsHtml == '') {
            $addonsHtml .= '<div class="cartItemAddon"><strong><u>Addons</u></strong></div>';
          }
          $addonsHtml .= '<div class="cartItemAddon">'.$values['addon_name'].'</div>';
          $i++;
        }
        //$addonsHtml .= '</div>';
      }
      $myHtml .=       '<tr class="cartItemRow" id="row_'.$value['rowid'].'">
                          <td style="width: 10%;"><i class="fa fa-lg fa-edit" style="cursor:pointer" aria-hidden="true" onclick="editOrder(\''.$value['rowid'].'\', '.$value['id'].')"></i></td>
                          <td style="width: 10%;">'.$value['qty'].'</td>
                          <td style="width: 70%; font-size: 12px;">
                            '.$name.'
                            '.$addonsHtml.'
                          </td>
                          <td style="width: 22%;">'.SITENAME_CURRENCY.''.number_format(($value['price'] * $value['qty']) + $itemAddonPrice, 2, '.', '').'</td>
                          <td style="width: 10%;"><img src="'.base_url().'assets/img/cancel.png" style="cursor:pointer" onclick="deleteFromCart(\''.$value['rowid'].'\')"></td>
                        </tr>';

      }
      $myHtml .=      '</tbody>
                    </table>
                  </div>';
      $session_data = $this->session->userdata('order_restaurant_id');
      $restaurant_id = $session_data['id'];
      $restOrderType = $this->createorder_model->restOrderType($restaurant_id);
      $orderTypeHtml = '';
      if (isset($restOrderType->restaurant_delivery) && $restOrderType->restaurant_delivery == 'Yes') {
        $checked = '';
        if ($orderType == 'delivery') {
          $checked = 'checked';
        }
        else if($orderType == '' && $restOrderType->restaurant_pickup == 'No' && $restOrderType->restaurant_dinein == 'No') {
          $checked = 'checked';
          $orderType = 'delivery';
        }
        $orderTypeHtml .= '<span class="midAlign">
                              <input type="radio" data-type="delivery" onclick="changeOrderType(this)" name="order_type" class="orderTypeClass" '.$checked.'>
                              <label>'.$this->lang->line('Delivery').'</label>
                            </span>';
      }
      if (isset($restOrderType->restaurant_pickup) && $restOrderType->restaurant_pickup == 'Yes') {
        $checked = '';
        if ($orderType == 'pickup') {
          $checked = 'checked';
        }
        else if($orderType == '' && $restOrderType->restaurant_delivery == 'No' && $restOrderType->restaurant_dinein == 'No') {
          $checked = 'checked';
          $orderType = 'pickup';
        }
        $orderTypeHtml .= '<span class="midAlign">
                              <input type="radio" data-type="pickup" onclick="changeOrderType(this)" name="order_type" class="orderTypeClass" '.$checked.'>
                              <label>'.$this->lang->line('Pickup').'</label>
                            </span>';
      }
      if (isset($restOrderType->restaurant_dinein) && $restOrderType->restaurant_dinein == 'Yes') {
        $checked = '';
        if ($orderType == 'dinein') {
          $checked = 'checked';
        }
        else if($orderType == '' && $restOrderType->restaurant_delivery == 'No' && $restOrderType->restaurant_pickup == 'No') {
          $checked = 'checked';
          $orderType = 'dinein';
        }
        $orderTypeHtml .= '<span class="midAlign">
                              <input type="radio" data-type="dinein" onclick="changeOrderType(this)" name="order_type" class="orderTypeClass" '.$checked.'>
                              <label>'.$this->lang->line('Dine-In').'</label>
                            </span>';
      }
      // cart countings
      $salesTax = $this->createorder_model->restSalesTax($restaurant_id);
      // $taxAmount = $subtotal * ($salesTax / 100);
      // $subtotalWithTax = $subtotal + $taxAmount;
      $deliveryCharge = $this->createorder_model->deliveryCharge();
      if ($orderType != 'delivery') {
        $deliveryCharge = 0.00;
      }
      $subtotalWithDelCharge = $subtotal + $deliveryCharge;
      $taxAmount = $subtotalWithDelCharge * ($salesTax / 100);
      $subtotalWithTaxWithDelCharge = $subtotalWithDelCharge + $taxAmount;
      $subtotalWithTax = $subtotalWithTaxWithDelCharge;
      $myHtml .= '<div class="table-responsive">
                    <table class="table table-hover table-bordered" id="">
                      <tbody>
                        <tr class="" id="totalItemCheckoutRow">
                          <td class="text-right" width="75%">'.$this->lang->line('Menu_Item_Price').':</td>
                          <td width="25%" id="totalItemCheckout">'.SITENAME_CURRENCY.''.number_format($subtotal, 2, '.', '').'</td>
                        </tr>
                        <tr style="color: rgb(11, 80, 158);">
                          <td class="text-right" width="75%">'.$this->lang->line('Delivery_Charge').':</td>
                          <td width="20%">'.SITENAME_CURRENCY.''.number_format($deliveryCharge, 2, '.', '').'</td>
                        </tr>
                        <tr class="">
                          <td class="text-right" width="75%">'.$this->lang->line('Tax').'('.number_format($salesTax, 2, '.', '').' %):</td>
                          <td width="20%" id="taxCheckout">'.SITENAME_CURRENCY.''.number_format($taxAmount, 2, '.', '').'</td>
                        </tr>
                      </tbody>
                      <tbody id="delivery-charge1">
                        <tr style="font-weight:600;" id="subtotalRowCheckout">
                          <td class="text-right" width="75%">'.$this->lang->line('Subtotal').':</td>
                          <td width="20%" id="subtotalWithTaxCheckout">'.SITENAME_CURRENCY.''.number_format($subtotalWithTax, 2, '.', '').'</td>
                        </tr>
                      </tbody>
                      <tbody class="hideInCheckout">
                        <tr style="font-weight:600;">
                          <td class="text-right" width="75%">'.$this->lang->line('Total').':</td>
                          <td width="20%">'.SITENAME_CURRENCY.''.number_format($subtotalWithTaxWithDelCharge, 2, '.', '').'</td>
                        </tr>
                      </tbody>
                      <tbody class="hideInCheckout">
                        <tr style="font-weight:600;text-align:center;">
                          <td colspan="3">
                            '.$orderTypeHtml.'
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>';
    }
    else {
      $myHtml = '<div class="table-responsive">
                    <table class="table table-hover table-bordered" id="add-cart">
                      <tbody>
                        <tr class="text-center">
                          <td>
                            '.$this->lang->line('No_items_added_yet').'
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>';
    }
    $data['subtotal'] = isset($subtotal)?number_format($subtotal, 2, '.', ''):0;
    $data['taxAmount'] = isset($taxAmount)?number_format($taxAmount, 2, '.', ''):0;
    $data['subtotalWithTax'] = isset($subtotalWithTaxWithDelCharge)?number_format($subtotalWithTaxWithDelCharge, 2, '.', ''):0;
    $data['deliveryCharge'] = isset($deliveryCharge)?number_format($deliveryCharge, 2, '.', ''):0;
    $data['subtotalWithTaxWithDelCharge'] = isset($subtotalWithTaxWithDelCharge)?number_format($subtotalWithTaxWithDelCharge, 2, '.', ''):0;
    $data['salesTax'] = isset($salesTax)?number_format($salesTax, 2, '.', ''):0;
    $data['orderType'] = $orderType;
    if ($this->session->userdata('cartData')) {
      $this->session->unset_userdata('cartData');
    }
    $this->session->set_userdata('cartData', $data);
    $data['myHtml'] = $myHtml;
    echo json_encode($data);
  }
  function deleteFromCart() {
    $rowid = $this->input->post('rowid');
    $data = array(
        'rowid' => $rowid,
        'qty'   => 0
      );
    $this->cart->update($data);
    $this->updateCartView();
  }
  function updateCartCount() {
    $rowid = $this->input->post('rowid');
    $qty = $this->input->post('qty');
    $data = array(
        'rowid' => $rowid,
        'qty'   => $qty
      );
    $this->cart->update($data);
    $this->updateCartView();
  }
  function placeOrder($guest = '') {
    /*echo "<pre>";
    print_r ($this->input->post());
    echo "</pre>";
    exit();*/
    /*if ($this->session->userdata('cartData')) {
      $this->session->unset_userdata('cartData');
    }*/
    //$this->session->set_userdata('cartData', $this->input->post());
    if (!$this->session->userdata('logged_in_customer')) {
      $requestPage = 'checkout';
      $this->showCustomerLogin($requestPage);
    }
    else {
      //$this->checkout();
      $customerData = $this->session->userdata('logged_in_customer');
      $this->db->select('*');
      $this->db->from('rt_customer');
      $this->db->where('customer_id', $customerData['id']);
      $custQuery = $this->db->get();
      $custData = $custQuery->row_array();
      if ($custQuery->num_rows() > 0) {
        $data['custData'] = $custData;
        $this->db->select('*');
        $this->db->from('rt_credit_cards');
        $this->db->where('customer_id', $customerData['id']);
        $ccQuery = $this->db->get();
        $ccData = $ccQuery->row_array();
        if (isset($ccData['cc_number']) && $ccData['cc_number'] != '') {
           $CCNumber = $this->createorder_model->ccDecrypt($ccData['cc_number'], $ccData['cc_time']);
          $CCNumberLength = strlen($CCNumber);
          $myCCNumber = substr_replace($CCNumber, 'XXXXXXXXXXXX', 0, $CCNumberLength - 4);
        }
        else {
          $myCCNumber = '';
        }
        if (isset($ccData['cc_cvv'])) {
          $CCCvv = $this->createorder_model->ccDecrypt($ccData['cc_cvv'], $ccData['cc_time']);
        }
        $data['cc_number'] = isset($myCCNumber)?$myCCNumber:'';
        $data['cc_type'] = isset($ccData['cc_type'])?$ccData['cc_type']:'';
        $data['cc_exp_month'] = isset($ccData['cc_exp_month'])?$ccData['cc_exp_month']:'';
        $data['cc_exp_year'] = isset($ccData['cc_exp_year'])?$ccData['cc_exp_year']:'';
        $data['cc_cvv'] = isset($CCCvv)?$CCCvv:'';
        $data['cc_time'] = isset($ccData['cc_time'])?$ccData['cc_time']:'';
      }
      $data['StateList'] = $this->frontend_model->StateList();
      $data['CityList'] = $this->frontend_model->CityList();
      $data['pointDetails'] = $this->frontend_model->getRewardPoints($customerData['id']);
      $data['redemptionAvailability'] = $this->frontend_model->getRedemptionAvailability($customerData['id']);
      $data['rewardAvailability'] = $this->frontend_model->checkRewardPointStatus();
      $data['title'] = 'Checkout';
      $data['page'] = 'checkout';
      $data['cart'] = $this->cart->contents();
      $data['cartData'] = $this->session->userdata('cartData');
    $data['serviceType'] = $data['cartData']["orderType"];
    if($data['cartData']["orderType"] == "delivery")
    {
        $data['serviceType'] = "Delivery";
    }
    else if($data['cartData']["orderType"] == "pickup")
    {
        $data['serviceType'] = "Pick Up";
    }
    else if($data['cartData']["orderType"] == "dinein")
    {
        $data['serviceType'] = "Dine In";
    }
    //print_r($data);
      $data['billingStateList'] = $this->createorder_model->billingStateList();
      $this->load->view('frontend/header');
      $this->load->view('frontend/checkout', $data);
      $this->load->view('frontend/footer');
    }
  }
  function showCheckout() {
    $data['StateList'] = $this->frontend_model->StateList();
    $data['CityList'] = $this->frontend_model->CityList();
    $data['title'] = 'Checkout';
    $data['page'] = 'checkout';
    $data['cart'] = $this->cart->contents();
    $data['cartData'] = $this->session->userdata('cartData');
    $data['serviceType'] = $data['cartData']["orderType"];
    if($data['cartData']["orderType"] == "delivery")
    {
        $data['serviceType'] = "Delivery";
    }
    else if($data['cartData']["orderType"] == "pickup")
    {
        $data['serviceType'] = "Pick Up";
    }
    else if($data['cartData']["orderType"] == "dinein")
    {
        $data['serviceType'] = "Dine In";
    }
    //print_r($data['cartData']);
      //echo "showCheckout: ".print_r($data);
    $data['billingStateList'] = $this->createorder_model->billingStateList();
    $this->load->view('frontend/header');
    $this->load->view('frontend/checkout', $data);
    $this->load->view('frontend/footer');
  }
  function showCustomerLogin($requestPage='') {
    $cookieData = $this->input->cookie('remember_me_token_customer');
    $cookieDataPass = $this->input->cookie('remember_me_token_customer_pass');
    $data['username'] = '';
    $data['password'] = '';
    $data['ischecked'] = '';
    if ($cookieData != "") {
      $result = $this->user->login_cookie_customer($cookieData);
      if($result)
      {
        $sess_array = array();
        foreach($result as $row)
        {
        $data['username'] = $row->customer_email;
        $data['password'] = $cookieDataPass;
        $data['ischecked'] = 'checked';
        }
      }
    }
    $data['requestPage'] = 'checkout';
    $data['page'] = 'customer_login';
    $data['title'] = '';
    $data['keywords'] = '';
    $data['description'] = '';
    $this->load->view('frontend/header', $data);
    $this->load->view('frontend/login');
    $this->load->view('frontend/footer');
  }
  function applyCoupon() {
    $coupon_code = $this->input->post('coupon_code');
    if ($this->session->userdata('order_restaurant_id')) {
      $details = $this->session->userdata('order_restaurant_id');
      $restaurant_id = $details['id'];
    }
    else {
      $restaurant_id = 0;
    }
    $now = date('Y-m-d');
    $this->db->select('offer_percentage, offer_price');
    $this->db->from('rt_restaurant_offer');
    $this->db->where('coupon_code', $coupon_code);
    $this->db->where('offer_valid_from <=', $now);
    $this->db->where('offer_valid_to >=', $now);
    $this->db->where('status', '1');
    $queryCoupon = $this->db->get();
    if ($queryCoupon->num_rows() > 0) {
      $myCoupon = $queryCoupon->row();
      if ($myCoupon->offer_percentage > 0) {
        $dataCoupon = array('offer' => $myCoupon->offer_percentage, 'type' => 'per', 'msg' => 'valid');
      }
      else {
        $dataCoupon = array('offer' => $myCoupon->offer_price, 'type' => 'fix', 'msg' => 'valid');
      }
    }
    else {
      $dataCoupon = array('msg' => 'invalid');
    }
    echo json_encode($dataCoupon);
  }
  function saveTempData() {
    //print_r($this->input->post());
    if ($this->session->userdata('tempCustData')) {
      $this->session->unset_userdata('tempCustData');
    }
    $tempDataArray = array(
        'customer_name'       =>    $this->input->post('customer_name'), 
        'customer_lastname'   =>    $this->input->post('customer_lastname'), 
        'customer_email'      =>    $this->input->post('customer_email'), 
        'customer_phone'      =>    $this->input->post('customer_phone'), 
        'customer_street'     =>    $this->input->post('customer_street'), 
        'customer_city'       =>    $this->input->post('customer_city'), 
        'customer_state'      =>    $this->input->post('customer_state'), 
        'customer_zip'        =>    $this->input->post('customer_zip'), 
        'instructions'        =>    $this->input->post('instructions'), 
        'customer_password'   =>    $this->input->post('customer_password')
      );
    $this->session->set_userdata('tempCustData', $tempDataArray);
    //print_r($this->session->userdata('tempCustData'));
  }
  function checkDeliveryArea() {
    // print_r($this->session->userdata());
    $customer_street = $this->input->post('customer_street');
    $customer_zip = $this->input->post('customer_zip');
    $customer_city = $this->input->post('customer_city');
    $customer_state = $this->input->post('customer_state');
    $address = '';
    if ($customer_street !== '') {
      $address .= $customer_street;
    }
    if ($customer_zip !== '') {
      if ($address !== '') {
        $address .= ', ';
      }
      $address .= $customer_zip;
    }
    if ($customer_city !== '') {
      if ($address !== '') {
        $address .= ', ';
      }
      $address .= $customer_city;
    }
    if ($customer_state !== '') {
      if ($address !== '') {
        $address .= ', ';
      }
      $address .= $customer_state;
    }

    $restaurant_id = 0;
    $isDeliveryAvailable = false;
    $deliveryZone = 0;
    $deliveryCharge = 0;
    $minOrderPrice = 0;

    if ($this->session->userdata('order_restaurant_id')) {
      $details = $this->session->userdata('order_restaurant_id');
      $restaurant_id = $details['id'];
    }
    if ($restaurant_id !== 0) {
      $delivery_details = $this->createorder_model->restaurantDeliveryDetails($restaurant_id);
      // echo json_encode($delivery_details); exit();
      if(isset($delivery_details->delivery_zone_1) && $this->mypolygon->checkPolygon($address, $delivery_details->delivery_zone_1, '')) {
        $isDeliveryAvailable = true;
        $deliveryZone = 1;
        $deliveryCharge = $delivery_details->restaurant_delivery_charge;
        $minOrderPrice = $delivery_details->restaurant_minorder_price;
      }
      else if(isset($delivery_details->delivery_zone_2) && $this->mypolygon->checkPolygon($address, $delivery_details->delivery_zone_2, '')) {
        $isDeliveryAvailable = true;
        $deliveryZone = 2;
        $deliveryCharge = $delivery_details->restaurant_delivery_charge_2;
        $minOrderPrice = $delivery_details->restaurant_minorder_price_2;
      }
      else if(isset($delivery_details->delivery_zone_3) && $this->mypolygon->checkPolygon($address, $delivery_details->delivery_zone_3, '')) {
        $isDeliveryAvailable = true;
        $deliveryZone = 3;
        $deliveryCharge = $delivery_details->restaurant_delivery_charge_3;
        $minOrderPrice = $delivery_details->restaurant_minorder_price_3;
      }
    }

    $data['isDeliveryAvailable'] = $isDeliveryAvailable;
    $data['deliveryZone'] = $deliveryZone;
    $data['deliveryCharge'] = $deliveryCharge;
    $data['minOrderPrice'] = $minOrderPrice;

    if ($this->session->userdata('delivery_details')) {
      $this->session->unset_userdata('delivery_details');
    }
    $this->session->set_userdata('delivery_details', $data);

    echo json_encode($data);
  }
  function checkout() {
//     echo "<pre>";
//     print_r ($this->input->post());
//     //print_r ($this->cart->contents());
//     echo "</pre>";
//     exit();
    $now = date('Y-m-d H:i:s');
    // customer details
    $customer_id = $this->input->post('customer_id');
    $customername = $this->input->post('customer_name');
    $customerlastname = $this->input->post('customer_lastname');
    $customer_email = $this->input->post('customer_email');
    $customer_phone = $this->input->post('customer_phone');
    $customer_street = $this->input->post('customer_street');
    $customer_buildtype = $this->input->post('customer_buildtype');
    $customer_zip = $this->input->post('customer_zip');
    $customer_state = $this->input->post('customer_state');
    $customer_city = $this->input->post('customer_city');
    $customer_password = $this->input->post('customer_password');

    $usertype = 'C';
    // card details 
    $time = time();
    $cc_type = $this->input->post('cc_type');
    $cc_number_clean = str_replace(' ', '', $this->input->post('cc_number'));
    $cc_number = $this->createorder_model->ccEncrypt($cc_number_clean, $time);
    $cc_exp_month = $this->input->post('cc_exp_month');
    $cc_exp_year = $this->input->post('cc_exp_year');
    $cc_cvv = $this->createorder_model->ccEncrypt($this->input->post('cc_cvv'), $time);

    $tempCode = $this->input->post('tempCode');
    if ($tempCode != '') {
      $tempCode_array = explode('-|-', $tempCode);
      $oldCode = $this->createorder_model->ccDecrypt($tempCode_array[0], $tempCode_array[1]);
    }
    else {
      $oldCode = '';
    }
    // cart details
    $subtotal = $this->input->post('subtotal');
    $itemTotal = $subtotal;
    $salesTax = $this->input->post('salesTax');
    $taxAmount = $this->input->post('taxAmount');
    $subtotalWithTax = $this->input->post('subtotalWithTax');
    $deliveryCharge = $this->input->post('deliveryCharge');
    $subtotalWithTaxWithDelCharge = $this->input->post('subtotalWithTaxWithDelCharge');
    $orderType = $this->input->post('orderType');
    $coupon_type = $this->input->post('coupon_type');
    $coupon_value = $this->input->post('coupon_value');
    if ($coupon_type == 'fix') {
      $offer_fix = $coupon_value;
      $offer_per = 0;
      $offervalue = $offer_fix;
    }
    else if ($coupon_type == 'per') {
      $offer_per = $coupon_value;
      $offer_fix = 0;
      $offervalue = $subtotal * ($offer_per / 100);
    }
    else {
      $offer_per = 0;
      $offer_fix = 0;
      $offervalue = 0;
    }
    if ($this->input->post('ifTip') == 'tip_yes') {
      if ($this->input->post('TipType') == 'fix') {
        $tipAmount = $this->input->post('tip_fix');
      }
      else if($this->input->post('TipType') == 'per') {
        //$tipAmount = $subtotal * ($this->input->post('tip_per') / 100);
        $tipAmount = $itemTotal * ($this->input->post('tip_per') / 100);
      }
      else {
        $tipAmount = 0.00;
      }
    }
    else {
      $tipAmount = 0.00;
    }
    $taxAmount = ($subtotal + $deliveryCharge) * ($salesTax / 100);
    $subtotal = $subtotal - $offervalue;
    if ($subtotal < 0) {
      $subtotal = 0.00;
      $offervalue = $itemTotal;
    }
    $pointUsedAmount = 0;//ifPointUsed,pointUsedAmount
    $pointAmountBalance = 0;//ifPointUsed,pointUsedAmount

    if($this->input->post('ifPointUsed') == 'Yes')
    {
        $pointUsedAmount = $this->input->post('pointUsedAmount');
        $pointAmountBalance = $this->input->post('pointAmountBalance');
    }
    $subtotalWithDelCharge = $subtotal + $deliveryCharge;
    $subtotalWithTax = $subtotalWithDelCharge + $taxAmount;
    $subtotalWithTaxWithDelCharge = $subtotalWithTax;
    $subtotalWithTaxWithDelCharge = $subtotalWithTaxWithDelCharge + $tipAmount;
    $paymentOption = 'cc';

      if($this->input->post('ifPointUsed') == 'Yes') {
          if ($pointAmountBalance > $subtotalWithTaxWithDelCharge) {
              $pointUsedAmount = $subtotalWithTaxWithDelCharge;
          }
          //$grandTotal = $subtotalWithTaxWithDelCharge - $offervalue;
           $subtotalWithTaxWithDelCharge = ($pointUsedAmount >= $subtotalWithTaxWithDelCharge ? $subtotalWithTaxWithDelCharge - $pointUsedAmount : 0);
      }
    $grandTotal = number_format($subtotalWithTaxWithDelCharge, 2, '.', '');
     // print_r($this->input->post());exit;
    // other details
    $instructions = $this->input->post('instructions');
    // restaurant details
    if ($this->session->userdata('order_restaurant_id')) {
      $details = $this->session->userdata('order_restaurant_id');
      $restaurant_id = $details['id'];
    }
    else {
      $restaurant_id = 0;
    }
    $restaurant_name = $this->createorder_model->restName($restaurant_id);
    $restaurant_sales_tax = $this->createorder_model->restSalesTax($restaurant_id);
    $commission = $this->createorder_model->restaurantCommission($restaurant_id, $itemTotal, $deliveryCharge, $taxAmount, $offervalue);

    // $RestaurantShare = number_format(($itemTotal + $taxAmount - $offervalue) - $commission, 2, '.', '');
    // $WebsiteShare = number_format($grandTotal - $RestaurantShare, 2, '.', '');
    // echo 'Item Total: '.$itemTotal.' Delivery Charge: '.$deliveryCharge.' Commission: '.$commission.' Tax: '.$taxAmount.' Sub Total: '.($itemTotal+$taxAmount+$deliveryCharge).' Tips: '.$tipAmount.' Coupon Discount: -'.$offervalue.' Grand Total: '.$grandTotal.'<br> RestaurantShare: '.$RestaurantShare.' WebsiteShare: '.$WebsiteShare; exit();
    $this->db->trans_start();
    $this->db->select('customer_id');
    $this->db->from('rt_customer');
    $this->db->where('customer_email', $customer_email);
    $custQuery = $this->db->get();
    $custData = $custQuery->row();
    if ($custQuery->num_rows() > 0) {
      $customer_id = $custData->customer_id;
    }
    if (!isset($customer_id) || $customer_id == '') {
      $usertype = 'G';
      if ($customer_password != '') {
        $customer_data_in = array(
            'customer_name'           =>    $customername,
            'customer_lastname'       =>    $customerlastname,
            'customer_email'          =>    $customer_email,
            'customer_phone'          =>    $customer_phone,
            'customer_street'         =>    $customer_street,
            'customer_buildtype'      =>    $customer_buildtype,
            'customer_zip'            =>    $customer_zip,
            'customer_state'          =>    $customer_state,
            'customer_city'           =>    $customer_city,
            'customer_password'       =>    md5($customer_password),
            'customer_validate'       =>    1,
            'addeddate'               =>    $now
          );
        $this->db->insert('rt_customer', $customer_data_in);
        $customer_id = $this->db->insert_id();
      }
      else {
        $customer_id = 0;
      }
    }
    /*echo "<pre>";
    print_r ($customer_data_in);
    print_r ($card_data_in);
    echo "</pre>";*/
    $this->db->select('driver_payout');
    $this->db->from('rt_sitesetting');
    $query = $this->db->get();
    $myData = $query->row();
    $driver_commission = $myData->driver_payout;
    $address = $customer_street.' '.$customer_buildtype.' '.$customer_zip;
    if($address!='') {
       $geo = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false');
       // We convert the JSON to an array
       $geo = json_decode($geo, true);
       // If everything is cool
       if ($geo['status'] = 'OK') {
       // We set our values
       $latitude = isset($geo['results'][0]['geometry']['location']['lat'])? $geo['results'][0]['geometry']['location']['lat']: DEFAULT_LAT;
       $longitude = isset($geo['results'][0]['geometry']['location']['lng'])? $geo['results'][0]['geometry']['location']['lng'] : DEFAULT_LONG;
       }
       else {
         $latitude = DEFAULT_LAT;
         $longitude = DEFAULT_LONG;
       }
     }
     else {
       $latitude = DEFAULT_LAT;
       $longitude = DEFAULT_LONG;
     }

    // $stateName = $this->createorder_model->fetchStateName($customer_state);
    // $cityName = $this->createorder_model->fetchCityName($customer_city);
    $stateName = $customer_state;
    $cityName = $customer_city;
    if ($stateName != '') {
      $customer_street .= ', '.$stateName;
    }
    if ($cityName != '') {
      $customer_street .= ', '.$cityName;
    }
    if ($customer_zip != '') {
      $customer_street .= ', '.$customer_zip;
    }
    $this->db->select('restaurant_estimated_time, braintree_sub_merchant_id');
    $this->db->from('rt_restaurant');
    $this->db->where('restaurant_id', $restaurant_id);
    $queryEst = $this->db->get();
    $restaurant_estimated_time = $queryEst->row()->restaurant_estimated_time;
    $braintree_sub_merchant_id = $queryEst->row()->braintree_sub_merchant_id;
    if ($restaurant_estimated_time != '') {
      $restaurant_estimated_time = $restaurant_estimated_time.' mins';
    }
    $dbOrderType = '';
    if ($orderType == 'delivery') {
      $dbOrderType = 'Delivery';
    }
    else if ($orderType == 'pickup') {
      $dbOrderType = 'Pickup';
    }
    else if ($orderType == 'dinein') {
      $dbOrderType = 'Dine-In';
    }
    $order_data_in = array(
        'restaurant_id'         =>    $restaurant_id,
        'restaurant_name'       =>    $restaurant_name,
        'customer_id'           =>    $customer_id,
        'usertype'              =>    $usertype,
        'customername'          =>    $customername,
        'customerlastname'      =>    $customerlastname,
        'customeremail'         =>    $customer_email,
        'customercellphone'     =>    $customer_phone,
        'deliverydoornumber'    =>    $customer_buildtype,
        'deliverystreet'        =>    $customer_street,
        'deliveryzip'           =>    $customer_zip,
        'deliverystate'           =>    $customer_state,
        'deliverycity'           =>    $customer_city,
        'deliverytype'          =>    $dbOrderType,
        'deliverydate'          =>    $restaurant_estimated_time,
        'deliverytime'          =>    '',
        'instructions'          =>    $instructions,
        'menuprice_total'       =>    $itemTotal,
        'tax_per'               =>    $restaurant_sales_tax,
        'taxvalue'              =>    $taxAmount,
        'offer_fix'          =>    $offer_fix,
        'offer_per'          =>    $offer_per,
        'offervalue'         =>    $offervalue,
        'ordersubtotal'         =>    $itemTotal+$taxAmount+$deliveryCharge,
        // 'ordersubtotal'         =>    $subtotal+$taxAmount+$tipAmount,
        'delivery_charged'      =>    $deliveryCharge,
        'driver_commission'     =>    $driver_commission,
        'ordertotalprice'       =>    $grandTotal,
        'payment_type'          =>    strtoupper($paymentOption),
        'paypal_status'         =>   'failed',
        'status'                =>    'In Preparation',
        'orderdate'             =>    $now,
        'commission'            =>    $commission,
        'deliverylatitude'      =>    $latitude,
        'deliverylongitude'     =>    $longitude,
        'tip'                   =>    $tipAmount,
        'point_amount'          =>    $pointUsedAmount
      );
    $this->db->insert('rt_order', $order_data_in);
    $orderid = $this->db->insert_id();
    $ordergenerateid = 'ORD'.$orderid;
    $orderid_code_up = array('ordergenerateid' => $ordergenerateid);
    $this->db->where('orderid', $orderid);
    $this->db->update('rt_order', $orderid_code_up);
    $cart = $this->cart->contents();
    foreach ($cart as $key => $value) {
      $menuid = $value['id'];
      $quantity = $value['qty'];
      if ($value['size_name'] != '') {
        $menuname = $value['name'].' ('.$value['size_name'].')';
      }
      else {
        $menuname = $value['name'];
      }
      $menuprice = $value['price'];
      $tot_menuprice = $value['subtotal'];
      $addonsname = '';
      $addonsprice = 0;
      if (is_array($value['addons']) && count($value['addons']) > 0) {
        foreach ($value['addons'] as $keys => $values) {
          if ($addonsname != '') {
            //$addonsname .= ' + ';
            $addonsname .= ', ';
          }
          $addonsname .= $values['addon_name'];
          $addonsprice = $addonsprice + (floatval($values['addon_price']) * $values['addon_qty']);
        }
        $tot_menuprice = $tot_menuprice + $addonsprice;
      }
      $specialinstruction = !empty($value['instruction'])?$value['instruction']:'';
      $cart_data_in = array(
          'menuid'        => $menuid,
          'quantity'      => $quantity,
          'menuname'      => $menuname,
          'menuprice'     => $menuprice,
          'tot_menuprice' => $tot_menuprice,
          'addonsname'    => $addonsname,
          'addonsprice'   => $addonsprice,
          'orderid'       => $orderid,
          'restaurantid'  => $restaurant_id,
          'specialinstruction'  => $specialinstruction,
          'addeddate'     => $now
        );
      $this->db->insert('rt_restaurant_cart', $cart_data_in);
    }
    if ($paymentOption != 'cod') {
      $ccDetails = $this->createorder_model->getCCDetails($customer_id);
      if (($oldCode == $cc_number_clean || !is_numeric($cc_number_clean)) && $customer_id != 0) {
        $btCardNumber = $ccDetails->cc_number;
        $btCardExpMonth = $ccDetails->cc_exp_month;
        $btCardExpYear = $ccDetails->cc_exp_year;
        $btCardCVV = $ccDetails->cc_cvv;
      }
      else {
        $btCardNumber = $cc_number_clean;
        $btCardExpMonth = $cc_exp_month;
        $btCardExpYear = $cc_exp_year;
        $btCardCVV = $this->input->post('cc_cvv');
      }
      $RestaurantShare = number_format($itemTotal + $taxAmount - $offervalue - $commission, 2, '.', '');
      $WebsiteShare = number_format($grandTotal - $RestaurantShare, 2, '.', '');
      /*$result = Braintree_Transaction::sale(array(
                    'merchantAccountId' => $braintree_sub_merchant_id,
                    'amount' => $RestaurantShare,
                    'serviceFeeAmount' => $WebsiteShare,
                        'creditCard' => array(
                        'number' => $btCardNumber,
                        'cardholderName' => '',
                        'expirationDate' => $btCardExpMonth.'/'.$btCardExpYear,
                        'cvv' => $btCardCVV
                    ),
                        'options' => array(
                          'submitForSettlement' => true,
                          'holdInEscrow' => true
                        ),
                ));
      if($result->success && $result->transaction->id) {
          $transactionId = $result->transaction->id;
          //echo $transactionId;
          $cc_status_up = array(
              'transaction_id'  => $transactionId,
              'paypal_status'   => 'success'
            );
          $this->db->where('orderid', $orderid);
          $this->db->update('rt_order', $cc_status_up);
      }*/

      /*
       * Pin Payment Gateway charge card
       */
      $transactionStatus = false;
      $message = $this->lang->line('Unable_to_process');
      if($grandTotal > 0) {
          $transactionStatus = false;
          $message = $this->lang->line('Unable_to_process');
          $requestParams = array(
              'IPADDRESS' => $_SERVER['REMOTE_ADDR'],          // Get our IP Address
              'PAYMENTACTION' => 'Sale'
          );
          $creditCardDetails = array(
              'CREDITCARDTYPE' => $cc_type,
              'ACCT' => $btCardNumber,
              'EXPDATE' => $btCardExpMonth.$btCardExpYear,
              'CVV2' => $btCardCVV
          );
          $payerDetails = array(
              'FIRSTNAME' => $customername,
              'LASTNAME' => $customerlastname,
              'COUNTRYCODE' => 'USA',
              'STATE' => $this->input->post('customer_billing_state'),
              'CITY' => $this->input->post('customer_billing_city'),
              'STREET' => $this->input->post('billing_customer_street'),
              'ZIP' => $this->input->post('billing_customer_zip')
          );
          $orderParams = array(
              'AMT' => $grandTotal,               // This should be equal to ITEMAMT + SHIPPINGAMT
              'ITEMAMT' => $grandTotal,
              'SHIPPINGAMT' => '0',
              'CURRENCYCODE' => 'USD'       // USD for US Dollars
          );
          $item = array(
              'L_NAME0' => SITENAME.' Order',
              'L_DESC0' => '',
              'L_AMT0' => $grandTotal,
              'L_QTY0' => '1'
          );
          // echo "<pre>";
          // print_r($orderParams);
          // echo "</pre>";
          // exit();
          //$paypal = new Paypal();
          $response = $this->mypaypal->request('DoDirectPayment',
              $requestParams + $creditCardDetails + $payerDetails + $orderParams + $item
          );
          if (is_array($response) && $response['ACK'] == 'Success') {
            $this->frontend_model->deductPoint($customer_id, $pointUsedAmount);
            $transactionId = $response['TRANSACTIONID'];
            $transactionStatus = true;
            $cc_status_up = array(
                'transaction_id' => $transactionId,
                'paypal_status' => 'success'
            );
            $this->db->where('orderid', $orderid);
            $this->db->update('rt_order', $cc_status_up);
          }
          else {
            $transactionStatus = false;
            $message = $response['L_LONGMESSAGE0'];
          }
      }else{
          $transactionStatus = true;
          //$this->frontend_model->payRewardPoint($customer_id, $grandTotal);
          $this->frontend_model->deductPoint($customer_id, $pointUsedAmount);
          $transactionId = "POINT_USED";
          $cc_status_up = array(
              'transaction_id' => $transactionId,
              'paypal_status' => 'success'
          );
          $this->db->where('orderid', $orderid);
          $this->db->update('rt_order', $cc_status_up);
      }
    }
    /*echo "<pre>";
    print_r ($response);
    echo "</pre>";
    exit();*/
    $this->db->trans_complete();
    if (!$transactionStatus) {
      $this->db->trans_start();
      $this->db->where('orderid', $orderid);
      $this->db->delete('rt_order');
      $this->db->where('orderid', $orderid);
      $this->db->delete('rt_restaurant_cart');
      $this->db->trans_complete();
      /*echo "<pre>";
      print_r ($result);
      echo "</pre>";
      exit();*/
      //$this->session->set_flashdata('error_msg', $response['L_LONGMESSAGE0']);
      $this->session->set_flashdata('error_msg', $message);
      //$this->placeOrder();
      redirect('createorderfrontend/showCheckout');
      //redirect('createorderfrontend/placeOrder');
    }
    else {
        if($orderType == "delivery") {
            $notifyDriverCheck = $this->notifyDriver($orderid);
            //echo $notifyDriver; exit();
            if ($notifyDriverCheck == 0) {
                $this->session->set_userdata('noDriver', array('1'));
            }
        }
      $this->notifyRestaurant($orderid, $restaurant_id);
      $this->db->trans_commit();
      $this->cart->destroy();
      $this->session->unset_userdata('cartData');
      $this->session->unset_userdata('tempCustData');
      $this->session->set_userdata('orderidInfo', array('orderid' => $orderid));
      redirect('createorderfrontend/thankyou');
    }
  }
  function thankyou() {
    if ($this->session->userdata('orderidInfo')) {
      $orderidInfo = $this->session->userdata('orderidInfo');
      $orderid = $orderidInfo['orderid'];
    }
    else {
      redirect(base_url());
    }
    $orderShort = $this->createorder_model->orderShortDetails($orderid);
    $orderLong = $this->createorder_model->orderLongDetails($orderid);
    $this->db->select('rest.order_receive_type, rest.restaurant_contact_email');
    $this->db->from('rt_order as ord');
    $this->db->join('rt_restaurant as rest', 'rest.restaurant_id = ord.restaurant_id', 'left');
    $this->db->where('ord.orderid', $orderid);
    $restQuery = $this->db->get();
    $restData = $restQuery->row();
    $orderReceiveTypeString = $restData->order_receive_type;
    $restaurantEmail = $restData->restaurant_contact_email;
    $orderReceiveTypeArray = array_filter(explode(',', $orderReceiveTypeString));
    $orderReceiveEmail = false;
    if (in_array('email', $orderReceiveTypeArray)) {
      $orderReceiveEmail = true;
    }
    $cart_items = '';
    if ($orderLong) {
      foreach ($orderLong as $key => $value) {
        $cart_items .= '<tr class="even" style="">';
        $cart_items .=     '<td style="text-align: center;">'.($key+1).'</td>';
        if($value->addonsname != "")
        {
        $cart_items .=     '<td style="text-align: center;">'.trim(htmlentities($value->menuname)).'<br /><span style="font-size: 12px;">'.trim(htmlentities($value->addonsname)).'</span></td>';
        }
        else {
        $cart_items .=     '<td style="text-align: center;">'.trim(htmlentities($value->menuname)).'</td>';
        }
        $cart_items .=     '<td style="text-align: center;">'.$value->quantity.'</td>';
        $cart_items .=     '<td style="text-align: center;">'.SITENAME_CURRENCY.''.$value->menuprice.'</td>';
        $cart_items .=     '<td style="text-align: center;">'.SITENAME_CURRENCY.''.$value->tot_menuprice.'</td>';
        $cart_items .=   '</tr>';
      }
    }
    if ($orderShort && $orderLong) {
      $image_path = base_url().'assets/';
      $variables = array();
      $to = $orderShort->customeremail;

      $variables['order_id'] = 'ORD'.$orderShort->orderid;
      $variables['customer_email'] = $orderShort->customeremail;
      $variables['customer_name'] = $orderShort->customername.' '.$orderShort->customerlastname;
      $variables['total_item_price_label'] = 'Menu Item Price';
      $variables['total_item_price'] = number_format($orderShort->menuprice_total, 2, '.', '');
      $variables['tax_label'] = 'Tax('.$orderShort->tax_per.'%)';
      $variables['tax_amount'] = number_format($orderShort->taxvalue, 2, '.', '');
      $variables['sub_total_label'] = 'Sub Total';
      $variables['sub_total_amount'] = number_format($orderShort->ordersubtotal, 2, '.', '');
      $variables['delivery_charge_label'] = 'Delivery Charge';
      $variables['delivery_charge_amount'] = number_format($orderShort->delivery_charged, 2, '.', '');
      $variables['tips_label'] = 'Tips';
      $variables['tips_amount'] = $orderShort->tip == ''?0.00:number_format($orderShort->tip, 2, '.', '');
      $variables['offer_label'] = 'Coupon Discount';
      $variables['offer_amount'] = number_format($orderShort->offervalue, 2, '.', '');
      $variables['point_label'] = 'Reward Point Used';
      $variables['point_amount'] = number_format($orderShort->point_amount, 2, '.', '');
      $variables['grand_total_label'] = 'Grand Total';
      $variables['grand_total'] = number_format($orderShort->ordertotalprice, 2, '.', '');
      $variables['cart_items'] = $cart_items;

      $variables['image_path'] = $image_path;
      $variables['to_email'] = $to;
      //$variables['sender_email'] = SITE_CONTACT_EMAIL;
      $variables['site_address'] = SITE_ADDRESS;
      $variables['sender_name'] = SITENAME;
      $variables['site_name'] = SITENAME;
      $template_name = 'customer_order';
      $mail_data = $this->frontend_model->getEmailTemplate($template_name);
      $mailcontent=htmlspecialchars_decode($mail_data->template);
      $subject = $mail_data->subject;
      foreach($variables as $key => $value) {
        $mailcontent = str_replace('{{'.$key.'}}', $value, $mailcontent);
      }
    }
    $this->send_my_mail($to,$subject,$mailcontent);
      $variables=array(
          '{SERVICE_NAME}'=>$orderShort->deliverytype,
          '{ORDER_ID}'=>$orderShort->ordergenerateid,
          '{SITENAME}'=>SITENAME,
          '{RESTAURANT_NAME}'=>$orderShort->restaurant_name,
          '{CUSTOMER_NAME}'=>$orderShort->customername." ".$orderShort->customerlastname
      );
      $description = $this->config->item("MSG")["ORDER_NOTIFY_CUSTOMER"];
      $sms_content_customer = $this->notification_model->EmailSendArray($description, $variables);//replace varibles

      $notification_param = array("to" => $orderShort->customercellphone,
          "message" => $sms_content_customer);
      $this->notification_model->sendSMSNotification($notification_param);
      $param = array();
      $param['push_notif_message'] = $sms_content_customer;
      $param['orderid'] = $orderShort->orderid;
      $param['msg_to'] = "customer";
      $param['browse_url'] = "";
      $param['has_url'] = "false";
      $this->notification_model->sendPushMessage($param);

    if ($orderReceiveEmail) {
      $this->send_my_mail($restaurantEmail,'Copy of Order',$mailcontent);
    }
    $this->session->unset_userdata('orderidInfo');
    if ($this->session->userdata('noDriver') && $orderShort->deliverytype == "Delivery") {
      //echo 'No driver!';
      $variables['status_message'] = 'We don\'t have any driver available as of the moment. It\'s busy! Unfortunately ORD'.$orderShort->orderid.' may be delayed momentarily. You can track your order by logging in your account and also from our site using \'Track Order\' button on top right corner. We will send an SMS once a driver accepts your order.';
      $template_name = 'order_status_msg';
      $mail_data = $this->frontend_model->getEmailTemplate($template_name);
      $mailcontent=htmlspecialchars_decode($mail_data->template);
      $subject = $mail_data->subject;
      foreach($variables as $key => $value) {
        $mailcontent = str_replace('{{'.$key.'}}', $value, $mailcontent);
      }
      //echo $mailcontent; exit();
      $this->send_my_mail($to,$subject,$mailcontent);
      $this->db->trans_start();
      $this->db->select('restaurant_contact_email');
      $this->db->from('rt_restaurant');
      $this->db->where('restaurant_id', $orderShort->restaurant_id);
      $restaurantData = $this->db->get();
      $variables['status_message'] = 'We don\'t have any driver available as of the moment. ORD'.$orderShort->orderid.' might be delayed for a little while.';
      $template_name = 'order_status_msg';
      $mail_data = $this->frontend_model->getEmailTemplate($template_name);
      $mailcontent=htmlspecialchars_decode($mail_data->template);
      $subject = $mail_data->subject;
      foreach($variables as $key => $value) {
        $mailcontent = str_replace('{{'.$key.'}}', $value, $mailcontent);
      }
      $this->send_my_mail($restaurantData->row()->restaurant_contact_email,$subject,$mailcontent);
      $this->session->unset_userdata('noDriver');
    }
    $data['title']  = "Thank You";  
    $data['page'] = "order";
    $this->load->view('frontend/header',$data);
    $this->load->view('frontend/thankyou');
    $this->load->view('frontend/footer');
  }
  function notifyDriver($orderid) {
    $notifyDriverCheck = 0;
    $now = date('Y-m-d H:i:s');
    //$orderid = $this->input->post('orderid');
    $why = $this->input->post('why');
    if ($why == 're') {
      $myArray = array(
          'isdriver_assign'   => 0,
          'delivery_status'   => 0,
          'driverid'          => 0,
          'drivername'        => 0,
          'status'            => 'In Preparation',
        );
      $this->db->trans_start();
      $this->db->where('orderid',$orderid);
      $this->db->update('rt_order',$myArray);
      $this->db->trans_complete();
    }
    $nowTime = date('H:i');
    $this->db->where('notify_order_id', $orderid);
    $this->db->delete('rt_driver_notify');
    $assigned_driver_in = array('notify_order_id' => $orderid, 'notify_time' => $nowTime);
    $this->db->insert('rt_driver_notify', $assigned_driver_in);
    $order_arr=array('isdriver_assign' => 1, 'driver_assign_time' => $now);
    $this->db->trans_start();
    $this->db->where('orderid',$orderid);
    $this->db->update('rt_order',$order_arr);
    $this->db->trans_complete();
    $Driver_List = $this->dashboard_model->get_driver_list();
    if(is_array($Driver_List) && sizeof($Driver_List)>0) {
     foreach($Driver_List as $row) {  
      $result = $this->dashboard_model->check_driver($row['driver_id']);
      if(!$result) {
        $notifyDriverCheck = 1;
        $deviceToken = $row['ios_device_token'];
        $deviceTokenAndroid = $row['android_device_token'];
        $registrationIdsArray = array($deviceTokenAndroid);
        if($deviceToken!='' && $deviceToken!=null && strlen($deviceToken) > 10) {
          $message = 'New order is placed. Please check.';
            $device_ios = array();
            array_push($device_ios, array("id" => $deviceToken, "msg" => $message, "appredirect" => ""));
            //print_R($device_ios);
            $this->notification_model->iosNotification($device_ios, "");
        }
        if($deviceTokenAndroid != "" && $deviceTokenAndroid != null) {
          $message = 'New order is placed. Please check.';
          $this->notification_model->androidNotification( $registrationIdsArray, $message, "New Delivery Task", "", ANDROID_PUSH_API, $orderid, $browse_url="", $has_url="false");
        }
      }
     }
   }
   return $notifyDriverCheck;
  }
  function notifyRestaurant($orderid, $restaurant_id) {
    $now = date('Y-m-d H:i:s');
    $nowTime = date('H:i');
    $orderShort = $this->createorder_model->orderShortDetails($orderid);
    $this->db->select('order_push_token_android');
    $this->db->from('rt_restaurant');
    $this->db->where('restaurant_id', $restaurant_id);
    $query = $this->db->get();
    $restDetails = $query->row_array();

      $variables=array(
          '{SERVICE_NAME}'=>$orderShort->deliverytype,
          '{ORDER_ID}'=>$orderShort->deliverytype,
          '{SITENAME}'=>SITENAME,
          '{RESTAURANT_NAME}'=>$orderShort->deliverytype,
          '{CUSTOMER_NAME}'=>$orderShort->deliverytype." ".$orderShort->deliverytype
      );
      $description = $description = $this->config->item("MSG")["ORDER_NOTIFY_RESTAURANT"];
      $sms_content_restaurant = $this->notification_model->EmailSendArray($description, $variables);//replace varibles
      $notification_param_res = array("to" => $orderShort->restaurant_phone,
          "message" => $sms_content_restaurant);
      $this->notification_model->sendSMSNotification($notification_param_res);

    $deviceToken = '';
    $deviceTokenAndroid = $restDetails['order_push_token_android'];
    $registrationIdsArray = array($deviceTokenAndroid);
      if($deviceToken!='' && $deviceToken!=null && strlen($deviceToken) > 10) {
          $device_ios = array();
          array_push($device_ios, array("id" => $deviceToken, "msg" => $sms_content_restaurant, "appredirect" => ""));
          //print_R($device_ios);
          $this->notification_model->iosNotification($device_ios, "");
      }
      if($deviceTokenAndroid != "" && $deviceTokenAndroid != null) {
          $this->notification_model->androidNotification( $registrationIdsArray, $sms_content_restaurant, "New Order Placed", "", ANDROID_PUSH_API, $orderid, $browse_url="", $has_url="false");
      }
    return true;
  }
  function send_my_mail($mail_To,$mail_subject,$mail_Body,$mail_CC="")
  {
      //Testing email
      //$mail_To .= ',earthtechnology7@gmail.com';
      $mail_From = SITENAME;

      $mail = new PHPMailer();

      //Your SMTP servers details

      $mail->IsSMTP(); // set mailer to use SMTP
      $mail->Host = SMTP_HOST; // specify main and backup server or localhost
      $mail->SMTPAuth = true; // turn on SMTP authentication
      $mail->Username = SMTP_USER; // SMTP username
      $mail->Password = SMTP_PASSWORD; // SMTP password It should be same as that of the SMTP user
      //$mail->AddCustomHeader("Precedence: bulk");

      //$mail->PluginDir = "/home/phpaucti/public_html/website_development/coding/includes/";
      $mail->From = $mail->Username; //Default From email same as smtp user
      $mail->FromName = $mail_From;
      $emailArr = explode(',',$mail_To);
      foreach($emailArr AS $emailVal) {
      $mail->AddAddress($emailVal, ""); //Email address where you wish to receive/collect those emails.
      }

      /*$emailCCArr = explode(',',$mail_CC);
      foreach($emailCCArr AS $emailCCVal) {
      $mail->AddCC($emailCCVal, ""); //Email address where you wish to receive/collect those emails.
      }*/


      $mail->WordWrap = 100; // set word wrap to 50 characters
      $mail->IsHTML(true); // set email format to HTML
      $mail->Subject = $mail_subject;
      $message = $mail_Body;
      $mail->Body = $message;

      if(!$mail->Send())
      {
      /*echo "Message could not be sent. <p>";
      echo "Mailer Error: " . $mail->ErrorInfo;
      exit;*/
      }
      else
      {
      //echo 'ok';
      }

  }

    private function pr($response)
    {
        echo "<pre>";
        print_r($response);
        echo "</pre>";
    }
}

Anon7 - 2022
AnonSec Team