<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4:           */
// +----------------------------------------------------------------------+
// | PHP version 4/5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2004-2010 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts VistaCart                     |
// +----------------------------------------------------------------------+
// | Authors: Jipson<jipson.thomas@armiasystems.com>                      |
// +----------------------------------------------------------------------+
include("../braintree/lib/Braintree.php");
class CartsController extends AppController {

    var $name = "Cart";
    var $helpers = array('Html', 'Form', 'Pagination');
    var $components = array('Pagination', 'Catmenu', 'Upsshipping', 'Authorizepayment', 'Yourpay', 'Usps', 'Xmlparser', 'Australiapost', 'Canadapost', 'Fedex', 'Googlecart', 'Googleitem', 'Bluepay','TwoCo','Moneybrokers','Paypalpro','Paypalflow','Payflowlink','Ogone','Paypaladvanced','Quickbook'); // Added
    var $uses = array('Product', 'Productdetail', 'Category', 'Cart', 'UserAddress', 'Country', 'Order', 'OrderDetail', 'Currency', 'Cmspage', 'State', 'User', 'Setting', 'Coupon', 'Giftcard', 'Giftcarduser', 'GiftcardDetail', 'Newsletteruser', 'Paypal');

    public $card_id, $usercard_id, $amnt_used;

    
    function index() {

    }

    function beforeFilter() {

        if (isset($this->Setting) && !empty($this->Setting->table)) {

            $this->Setting->load();
        }

        global $sitefolder;

        global $meta_description;

        global $meta_keywords;

        global $page_title;

        global $currency;

        global $allow_giftcoupon;

        $cnfg = Configure::read('Neutrino');

        $sitefolder = $cnfg["sitebasefolder"];

        $meta_description = $cnfg["meta_description"];

        $meta_keywords = $cnfg["meta_keywords"];

        $page_title = $cnfg["page_title"];

        $currency = $cnfg["currency"];

        $allow_giftcoupon = $cnfg["allow_giftcoupon"];

        global $style;

        $style = $cnfg["style"];

        $this->set('base_url', FULL_BASE_URL);

        $this->set('allow_giftcoupon', $allow_giftcoupon);

        $this->set('style', $style);

        $this->set('meta_description', $meta_description);

        $this->set('meta_keywords', $meta_keywords);

        $this->pageTitle = $page_title;

        $this->set('cnfg', $cnfg);

        //get cart count
        $sus = $this->Session->read();
        if ($this->Session->check('Userlog') === true) {
            $userid = $sus["Userlog"]["id"];
            $cartCount = $this->Cart->getCartCount($userid,'user');
        }else {
            $sessid = $this->Session->id();
            $cartCount = $this->Cart->getCartCount($sessid,'G');
        }
        $this->set('cartcount',$cartCount);
    }

    function beforeRender() {
        //$lst  =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..
       // $lst = $this->Category->findAll();
         $lst   =   $this->Category->findAll(null, NULL, 'Category.cname ASC', null, null);
        if (empty($lst) === false) {
            foreach ($lst as $det)
                $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);
            $this->set('menu_array', $menu_array);
        }
        //Code Added By shyam for Category Menu Listing ends here..
        $footer_links = $this->Cmspage->find('list', array('conditions' => array('Cmspage.type' => 'content', 'Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);
    }

    function __validateLoginStatus($typ = 'U') {

        if ($typ == 'A') {

            if ($this->Session->check('Admin') == false) {

                $this->redirect(array('controller' => 'admins', 'action' => 'login'));

                $this->Session->setFlash('The URL you\'ve followed requires you login.');
            }
        } else {

            if ($this->Session->check('Userlog') == false) {

                $this->redirect(array('controller' => 'users', 'action' => 'login'));

                $this->Session->setFlash('The URL you\'ve followed requires you login.');
            }
        }
    }

    function add($pid = '', $cid = '', $optid = '') {

        //$this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $dat["user_id"] = 0;

        if (!empty($sus) === true) {

            $dat["user_id"] = $sus["id"];
        }

        $sessid = $this->Session->id();

        //$chk  =   $this->Cart->find("product_id=".$pid." AND user_id=".$dat["user_id"]." AND customvalue = '".base64_decode($opt)."'");

        if ($optid <> '' && $optid <> 0) {

            $chk = $this->Cart->find("product_id=" . $pid . " AND user_id=" . $dat["user_id"] . " AND option_id = '" . $optid . "' AND sess_id='" . $sessid . "' AND type='P'");
        } else {
            $chk = $this->Cart->find("product_id=" . $pid . " AND user_id=" . $dat["user_id"] . " AND sess_id='" . $sessid . "' AND type='P'");
        }

        if (!empty($chk["Cart"])) {


            $this->Session->setFlash('This product has been already added to cart, you can update the quantity in the cart.');

            //$this->redirect('/carts/show');
            $this->redirect(array('controller' => 'carts', 'action' => 'show'));

            exit;
        } else {

            $dat["sess_id"] = $this->Session->id();

            $dat["product_id"] = $pid;

            $pdet = $this->Product->findById($pid);

            //Setting the prices for whole sale and retail users..

            if (isset($sus) && empty($sus) === false) {

                if ($sus["usertype"] == 'wholesale') {

                    if ($pdet["Product"]["wholesale_price"] > 0) {

                        $dat["product_price"] = $pdet["Product"]["wholesale_price"];
                    } else {

                        $dat["product_price"] = $pdet["Product"]["price"];
                    }

                    $dat["price_type"] = 'W';
                }

                if ($sus["usertype"] == 'retail') {

                    $dat["product_price"] = $pdet["Product"]["price"];

                    $dat["price_type"] = 'R';
                }
            } else {

                $dat["product_price"] = $pdet["Product"]["price"];
            }

            //Setting the prices for whole sale and retail users..





            $dat["discount_type"] = $pdet["Product"]["discount_type"];

            $dat["discount"] = $pdet["Product"]["discount"];

            $dat["shipping_charge"] = $pdet["Product"]["shipping_price"];

            $dat["quantity"] = 1;

            $dat["prodtype"] = $pdet["Product"]["prodtype"];

            $dat["type"] = 'P';

            //$dat["customvalue"]       =   base64_decode($opt);

            if ($optid <> '' && $optid <> 0) {

                $dat["option_id"] = $optid;

                $pcmdet = $this->Productdetail->findById($dat["option_id"]);

                $dat["extra_price"] = $pcmdet["Productdetail"]["extraprice"];
            }

            else
                $optid = '';

            $tpflag = true;

            
            if ($this->Session->check('Userlog') === true) { // check with user
                $citem = $this->Cart->findAllByUserId($dat["user_id"]);
            } else { // else check with current session
                $citem = $this->Cart->findAllBySessId($sessid);
            }
            
            if (!empty($citem)) {

                foreach ($citem as $it) {                   
                    if ($it["Cart"]["prodtype"] <> $dat["prodtype"] || $it["Cart"]["prodtype"] == 'Gift Card') {
                        $tpflag = false;
                    }
                }
            }



            if ($tpflag <> true) {
                $this->Session->setFlash('Sorry, products of different type(digital/non-digital/Gift Card) can\'t buy together!');
            } else {

                if ($pdet["Product"]["stock"] < $dat["quantity"]) {

                    $this->Session->setFlash('Sorry,There is not enough stock available for the product you requested!');
                } else {

                    $this->Cart->save($dat);
                }
            }

            //$this->redirect('/carts/show');
            $this->redirect(array('controller' => 'carts', 'action' => 'show'));

            exit;
        }
    }

    ######## Function to show cart.......................................
    ######## Function to add gift card tocart.......................................

    function giftcard($cid = '') {

        //$this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $dat["user_id"] = 0;

        if (!empty($sus) === true) {

            $dat["user_id"] = $sus["id"];
        }

        $sessid = $this->Session->id();

        $chk = $this->Cart->find("product_id=" . $cid . " AND user_id=" . $dat["user_id"] . " AND sess_id='" . $sessid . "' AND type='G'");

        if (!empty($chk["Cart"])) {

            $this->Session->setFlash('<label style="padding-left:150px;">This Gift card has been already added to cart, you can update the quantity in the cart.</label>');

            //$this->redirect('/carts/show');
            $this->redirect(array('controller' => 'carts', 'action' => 'show'));

            exit;
        } else {

            $gdet = $this->Giftcard->findById($cid);

            if (isset($gdet) && empty($gdet) === false) {

                $avail_stock = $gdet["Giftcard"]["stock"];
            }

            if ($avail_stock < 1) {

                $this->Session->setFlash('Sorry,There is not enough stock available for the gift card you requested!');

                //$this->redirect('/carts/show');
                $this->redirect(array('controller' => 'carts', 'action' => 'show'));

                exit;
            }

            $dat["sess_id"] = $this->Session->id();

            $dat["product_id"] = $cid;

            //prodtype being changed from digital to gift card
            $dat["prodtype"] = 'Gift Card';

            $cdet = $this->Giftcard->findById($cid);

            $dat["product_price"] = $cdet["Giftcard"]["gift_amnt"];

            $dat["quantity"] = 1;

            $dat["type"] = 'G';

            $dat["price_type"] = 'C';

//            $citem = $this->Cart->findAllByUserId($dat["user_id"]);
            $citem = $this->Cart->find('all', array('conditions' => array('Cart.user_id' => $dat["user_id"],'Cart.sess_id' => $dat["sess_id"])));
            $tpflag = true;
            if (!empty($citem)) {
                foreach ($citem as $it) {

                    if ($it["Cart"]["prodtype"] <> $dat["prodtype"]) {

                        $tpflag = false;
                    }
                }
            }



            if ($tpflag <> true) {

                $this->Session->setFlash('Sorry, Gift Card and other products can\'t buy together!');
            } else {

                $this->Cart->save($dat);
            }

            $this->redirect('/carts/show');

            exit;
        }
    }

    ######## Function to show cart.......................................

    function show() {

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);
        $promo_code ='';
        if ($this->Session->check('Coupon') == true) {
           
            $coup = $this->Session->read('Coupon');

            $this->set('couparray', $coup);
        }
        if ($this->Session->check('promo_code') == true) {
            $promo_code = $this->Session->read('promo_code');
        }

        //echopre($_REQUEST);

        $this->set('promo_code', $promo_code);
        $sus = $this->Session->read();

        if ($this->Session->check('Userlog') === true) {

            $userid = $sus["Userlog"]["id"];
            $sessid = $this->Session->id();

            $cupdate = $this->Cart->updatesessuser($sessid, $userid);


            $citem1 = $this->Cart->findAllByUserId($userid);
            //$maxid = $this->Cart->findAllByUserId($userid);
            //Finding the product type of the lastly added product type and deleting the product with the other types
            $cart_tbl = $this->Cart->getTableName('carts');
            $max_rowid = $this->Cart->find('first', array(
                    'fields' => 'MAX(Cart.id) as maxid',
                    'conditions' => array('Cart.user_id ' => $userid)
            ));

            $last_prodtype = 'Non-Digital';
            if (isset($max_rowid[0]["maxid"]) && $max_rowid[0]["maxid"] <> 0) {
                $last_ptype = $this->Cart->findById($max_rowid[0]["maxid"]);
                if (isset($last_ptype) && empty($last_ptype) === false) {
                    $last_prodtype = trim($last_ptype["Cart"]["prodtype"]);
                }
            }

            $del_parray = array();
            $citem2 = $this->Cart->find('all', array('conditions' => array('user_id' => $userid)));
            foreach ($citem2 as $cvals2) {
                $ptype = $cvals2['Cart']['prodtype'];
                if (trim($last_prodtype) <> trim($ptype))
                    $del_parray[] = $cvals2['Cart']['id'];
            }
            if (isset($del_parray) && empty($del_parray) === false) {
                $this->Cart->query("delete FROM $cart_tbl where id IN (" . implode(',', $del_parray) . ")");
            }
            //Finding the product type of the lastly added product

            $del_array = array();
            $chk_array = array();
            foreach ($citem1 as $cvals1) {
                $chk_rowid = $cvals1['Cart']['id'];
                $chk_prodid = $cvals1['Cart']['product_id'];
                $chk_userid = $cvals1['Cart']['user_id'];
                $chk_optid = $cvals1['Cart']['option_id'];
                $chk_type = $cvals1['Cart']['type'];

                $chk_str = $chk_prodid . '-' . $chk_optid . '-' . $chk_type;


                if (in_array($chk_str, $chk_array)) {
                    $upid = explode('-', $chk_str);
                    $upqty = $cvals1['Cart']['quantity'];
                    $this->Cart->query("update $cart_tbl set quantity=(quantity +" . $upqty . ") where id='" . $upid[0] . "'");
                    $del_array[] = $chk_rowid;
                }
                $chk_array[] = $chk_str;
            }
            if (isset($del_array) && empty($del_array) === false) {
                $this->Cart->query("delete FROM $cart_tbl where id IN (" . implode(',', $del_array) . ")");
            }


            //$citem    =   $this->Cart->findAllByUserId($userid);

            $citem = $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'G', 'user_id' => $userid)));

            $gitem = $this->Cart->find('all', array('conditions' => array('Cart.type' => 'G', 'user_id' => $userid)));
        } else {

            $sessid = $this->Session->id();

            //$citem    =   $this->Cart->findAllBySessId($sessid);

            $citem = $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'G', 'sess_id' => $sessid)));

            $gitem = $this->Cart->find('all', array('conditions' => array('Cart.type' => 'G', 'sess_id' => $sessid)));
        }
             



        //Code to get the cart item along with the combination values of products if any starts here...

        for ($i = 0; $i < count($citem); $i++) {

            if ($citem[$i]["Cart"]["option_id"] <> 0 && $citem[$i]["Cart"]["option_id"] <> '') {

                $pcombndet = $this->Productdetail->findAllById($citem[$i]["Cart"]["option_id"]);


                $pcmbnid = explode(',', $pcombndet[0]["Productdetail"]["customvalue_id"]);

        if ($citem[$i]["Product"]["combination"] == 'Y') {

              $stockcnt = $this->Productdetail->findById($citem[$i]["Cart"]["option_id"]);

          $citem[$i]["Product"]['stock'] = $stockcnt['Productdetail']['stock'];


        }



                foreach ($pcmbnid as $key => $val) {

                    if ($val != '') {

                        $combnstr[] = $this->Product->getpdctcmbn($val);

                        $combinations = implode(" ,", $combnstr);

                        $citem[$i]["Cart"]["combn_values"] = $combinations;
                    }
                }
            }

            unset($combnstr);
            unset($combinations);
        }

              
        //Setting the combination flag
        $cmbtype_flag = 'no';
        if (count($citem) > 0) {
            foreach ($citem as $itm) {
                if ($itm["Product"]["combination"] <> '')
                    $cmbtype_flag = 'yes';

               /* echo "<pre>";
                print_r($itm["Cart"]["option_id"]);
                echo "</pre>";*/

                if($itm["Product"]["combination"]=='Y')
                {
                    $stockcnt = $this->Productdetail->findById($itm["Cart"]["option_id"]);

                    $itm["Product"]['stock'] = $stockcnt["Productdetail"]["stock"];

                }


            }
        }
        $this->set('cmbtype_flag', $cmbtype_flag);

        $this->set('itemlist', $citem);

        //Code to get the cart item along with the combination values of products if any starts here...

        $gftbl = $this->Cart->getTableName("giftcards");

        if (isset($gitem) && empty($gitem) === false) {

            for ($i = 0; $i < count($gitem); $i++) {

                $gdet = $this->Giftcard->query("select gift_code,stock from " . $gftbl . " where id='" . $gitem[$i]["Cart"]["product_id"] . "'");

                $gitem[$i]["Cart"]["gift_code"] = $gdet[0][$gftbl]["gift_code"];

                $gitem[$i]["Product"]["stock"] = $gdet[0][$gftbl]["stock"];
            }

            $this->set('giftcard', $gitem);
        }

        //Code to get the cart item along with the combination values of products if any ends here...



        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', $curr["Currency"]["logo"]);
    }

    ######## Function to show cart At Admin side.......................................

    function showadmincart($uid) {

        $this->__validateLoginStatus('A');

        $user_id = $uid;

        $citem = $this->Cart->findAllByUserId($user_id);

        //print_r($citem);exit;

        $this->set('itemlist', $citem);

        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', $curr["Currency"]["logo"]);
    }

    ######### Function to update quantity in the cart.......................

    function update() {

     
        //Checking For Valid Coupon Code starts here...
        $this->Session->write('promo_code', "");

       // $this->Session->setFlash('');

      if(isset($_POST["btn_apply"]) && trim($_POST["btn_apply"]) == 'Apply'){
        
        if (isset($_POST["code"]) && trim($_POST["code"]) <> '') {

            $coup = $this->Coupon->findByCode($_POST["code"]);     
          
            //$this->set('couparray',$coup);
            if (isset($coup) && !empty($coup)) {

                $this->Session->write('Coupon', $coup);
                $this->Session->setFlash('Promo code applied successfully!');
            } else {
                
                 $this->Session->delete('Coupon');
                 $this->Session->write('promo_code', '');

                $this->Session->setFlash('Sorry,Invalid promo code!');
            }

            $this->Session->write('promo_code', $_POST["code"]);
            //$this->set('promo_code',$_POST["code"]);
        } else {

               
                 $this->Session->delete('Coupon');
                 $this->Session->write('promo_code', '');
                 $this->Session->write('couparray', '');              
                 $this->Session->write('Coupon', "");
                
            //$this->Session->setFlash(' ');
        }

     }  


else if(isset($_POST["btn_remove"]) && trim($_POST["btn_remove"]) == 'Remove'){

                 $this->Session->delete('Coupon');
                 $this->Session->write('promo_code', '');
                 $this->Session->write('couparray', '');              
                 $this->Session->write('Coupon', "");

                  $this->Session->setFlash('Promo code removed successfully!');

  }    

    else { 

        //Checking For Valid Coupon Code ends here..
        if(sizeof($_POST["id"])<1){
             $this->Session->delete('Coupon');
             $this->Session->write('promo_code', '');
        }
        //print '<pre />';print_r($_POST["id"]);exit;
        for ($i = 0; $i < sizeof($_POST["id"]); $i++) {

            if ($_POST["ptype"][$i] <> 'G') {

                $cdet = $this->Cart->findById($_POST["id"][$i]);

                $pid = $cdet["Cart"]["product_id"];

                $pdet = $this->Product->findById($pid);

              

                #################(Added by Shyam) #################

                if ($pdet["Product"]["combination"] == 'Y') {

                    $stockcnt = $this->Productdetail->findById($_POST["optionid"][$i]);

                    if ($stockcnt["Productdetail"]["stock"] < $_POST["qty"][$i]) {

                        $this->Session->setFlash('Sorry,The stock is not enough for the product you requested!');
                    } else {

                        $this->Cart->update($_POST["id"][$i], $_POST["qty"][$i]);
                    }
                } else

                if ($pdet["Product"]["combination"] == '' || $pdet["Product"]["combination"] == 'N') {

                    if ($pdet["Product"]["stock"] < $_POST["qty"][$i]) {

                        $this->Session->setFlash('Sorry,The stock is not enough for the product you requested!');
                    } else {

                        $this->Cart->update($_POST["id"][$i], $_POST["qty"][$i]);
                    }
                }
            } else if ($_POST["ptype"][$i] == 'G') {

                $this->Cart->update($_POST["id"][$i], $_POST["qty"][$i]);
            }

            #################(Added by Shyam) #################
        }

    }    

        $this->redirect('/carts/show');

        exit;
    }

    ####### Function to delete from cart........................................

    function delete($id) {

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $this->Cart->del($id);

        if (!empty($sus) === true) {

            $userid = $sus["id"];

            $citem = $this->Cart->find('all', array('conditions' => array('user_id' => $userid)));

            if (count($citem) < 1) {

                if ($this->Session->check('Coupon') == true) {

                    $this->Session->delete('Coupon');
                   $this->Session->write('promo_code', '');
                }
            }
        }
        
         if ($this->Session->check('Userlog') === true) {

                $userid = $sus["Userlog"]["id"];

                $citem = $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'G', 'user_id' => $userid)));

                $gitem = $this->Cart->find('all', array('conditions' => array('Cart.type' => 'G', 'user_id' => $userid)));

         } else {

            $sessid = $this->Session->id();
             $citem = $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'G', 'sess_id' => $sessid)));

            $gitem = $this->Cart->find('all', array('conditions' => array('Cart.type' => 'G', 'sess_id' => $sessid)));
        }
        
         if (count($citem) < 1 || count($gitem) < 1) {

                if ($this->Session->check('Coupon') == true) {

                    $this->Session->delete('Coupon');
                    $this->Session->write('promo_code', '');
                }
            }

        $this->redirect('/carts/show');

        exit;
    }

####### Function to Send Fax to Admin Starts here (code added by shyam - April 9,2010)........................................

    function _sendFax($fax_email = '', $fax_number = '', $fax_content = '', $msg_opt = '') {
        $cnfg = Configure::read('Neutrino');
        if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
            include_once("../phpmailer/class.phpmailer.php");
        }else{
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        } 
        
        if ($msg_opt == 1) {

            $cnfg = Configure::read('Neutrino');

            $content = "Hi Admin,<br /><br />A New Order has been placed at " . $cnfg["site_name"] . ". The order details is follows.";

            $towrite = $content . $fax_content;
        } else {

            $towrite = $fax_content;
        }

        //--------------------Fax Email----------------------------

        $to = $fax_number . "@rcfax.com";

        $from = $fax_email;

        $subject = "Hi Admin,<br />A New Order has been  placed at Food Court.";

        //--------------------------------------------------------



        /* What we'll write to the file */

        $thefile = WWW_ROOT . "Fax/order.html";

        $openedfile = fopen($thefile, "w");

        fwrite($openedfile, $towrite);

        fclose($openedfile);



        $type = filetype($thefile);

        $mime_boundary = 'text/html';

        $name = "order.html";



        $message = '';

        if (file_exists($thefile)) {

            // open the file for a binary read

            $file = fopen($thefile, 'rb');

            // read the file content into a variable

            $data = fread($file, filesize($thefile));

            // close the file

            fclose($file);

            // now we encode it and split it into acceptable length lines

            $data = chunk_split(base64_encode($data));

            // now we'll build the message headers

            $headers = "From: $from\r\n" .
                    "MIME-Version: 1.0\r\n" .
                    "Content-Type: multipart/mixed;\r\n" .
                    " boundary=\"{$mime_boundary}\"";



            // next, we'll build the message body
            // note that we insert two dashes in front of the
            // MIME boundary when we use it

            $message = "This is a multi-part message in MIME format.\n\n" .
                    "--{$mime_boundary}\n" .
                    "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
                    "Content-Transfer-Encoding: 7bit\n\n" .
                    $message . "\n\n";



            // now we'll insert a boundary to indicate we're starting the attachment
            // we have to specify the content type, file name, and disposition as
            // an attachment, then add the file content and set another boundary to
            // indicate that the end of the file has been reached

            $message .= "--{$mime_boundary}\n" .
                    "Content-Type: {$type};\n" .
                    " name=\"{$name}\"\n" .
                    //"Content-Disposition: attachment;\n" .
                    //" filename=\"{$fileatt_name}\"\n" .

                    "Content-Transfer-Encoding: base64\n\n" .
                    $data . "\n\n" .
                    "--{$mime_boundary}--\n";

            // now we just send the message

            //@mail($to, $subject, $message, $headers);
                    
            $site_name      = "";
            $admin_email    = "";
            if(trim($cnfg["site_name"]) <> ""){
                $site_name  = trim($cnfg["site_name"]);                            
            }else{
                $site_name = $cnfg["smtp_user"];                            
            }  
            if(trim($cnfg["admin_email"]) <> ""){
                $admin_email = trim($cnfg["admin_email"]);
            }else{
                $admin_email = $cnfg["smtp_user"];
            }
            /******************************* MAIL TO THE USER ****************************/
            $mail             = new PHPMailer(true);                
            $body             = trim($mailcontent);
            //$body           = eregi_replace("[\]",'',$body);
            $mail->IsSMTP(); 
            $mail->SMTPSecure = 'tls';
            //$mail->SMTPDebug  = 2;                    
            $mail->SMTPAuth   = true;   
            
            
            $mail->Host       = $cnfg["smtp_host"]; 
            $mail->Port       = $cnfg["smtp_port"];   
            $mail->Username   = $cnfg["smtp_user"];
            $mail->Password   = $cnfg["smtp_password"];       
            $mail->SetFrom($from, $site_name);
            $mail->AddReplyTo($from,$site_name);
            $mail->Subject    = $subject;
            $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
            $mail->MsgHTML($body);                    
            $mail->AddAddress($to, ""); 
            $mail->Send();
            /******************************* MAIL TO THE USER ****************************/
        }
    }

    ###### Function to checkout.................................................

    function checkout(){

        $cnfg       = Configure::read('Neutrino');        
        if (trim($_SERVER['HTTP_HOST']) == 'localhost'){  
            include_once("../phpmailer/class.phpmailer.php");
        }else{
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        }
        
        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        //Saving the Billing and shipping addresses starts here
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            //updating Email Address for Guest in users table...

            if ($sus["reg_status"] == 'G') {

                //Sending login details mail to the Guest User starts here..
                $email_dups = $this->User->find('count', array('conditions' => array('User.email' => trim($_POST["bemail"]))));
               
                $emailsplit     =   explode("@",trim($_POST["bemail"]));            
                $uname          =   $emailsplit[0];

                if ($email_dups < 1) {

                    $emailsplit     =   explode("@",trim($_POST["bemail"]));            
                    $uname          =   $emailsplit[0];

                    $subject = "New login details at " . $cnfg["site_name"];
                    $headers = "From: " . $cnfg["site_name"] . "<" . $cnfg["admin_email"] . ">\r\n";
                    $headers .= "MIME-Version: 1.0\r\n";
                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                    $mailcontent = '<table width="27%" border="0" align="center">
                                    <tr><td colspan="3" align="center"><font color="#CC6600"><strong>Vista cart Login Details</strong></font></td></td></tr>
                                    <tr><td width="27%"><strong>Username</strong></td><td><strong>:</strong></td><td width="73%">' . $uname . '</td></tr>
                                    <tr><td><strong>Password</strong></td><td><strong>:</strong></td><td width="73%">' . $this->Session->read('guestpswd') . '</td></tr>
                                    </table>';
                    //$mailsent = mail($_POST["bemail"], $subject, $mailcontent, $headers);
                    
                    /*#################################### EMAIL SEGMENT ###############################*/
                        $site_name      = "";                       
                        $admin_email    = "";
                        
                        if(trim($cnfg["site_name"]) <> ""){
                            $site_name = trim($cnfg["site_name"]);
                        }else{
                            $site_name = $cnfg["smtp_user"];
                        }   
                        if(trim($cnfg["admin_email"]) <> ""){
                            $admin_email = trim($cnfg["admin_email"]);
                        }else{
                            $admin_email = $cnfg["smtp_user"];
                        }
                        /******************************* MAIL TO THE USER ****************************/
                        $mail             = new PHPMailer(true);                
                        $body             = trim($mailcontent);
                        //$body           = eregi_replace("[\]",'',$body);
                        $mail->IsSMTP(); 
                        $mail->SMTPSecure = 'tls';
                        //$mail->SMTPDebug  = 2;                    
                        $mail->SMTPAuth   = true;  
                    
                        
                    $mail->Host       = $cnfg["smtp_host"]; 
                    $mail->Port       = $cnfg["smtp_port"];   
                    $mail->Username   = $cnfg["smtp_user"];
                    $mail->Password   = $cnfg["smtp_password"];    
                        $mail->SetFrom($admin_email, $site_name);
                        $mail->AddReplyTo($admin_email, $site_name);
                        $mail->Subject    = $subject;
                        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
                        $mail->MsgHTML($body);                    
                        $mail->AddAddress($_POST["bemail"], ""); 
                        $mail->Send();
                    /******************************* MAIL TO THE USER ****************************/ 
                    
                    /*#################################### EMAIL SEGMENT ###############################*/
                    
                    $this->Session->delete('guestuser');
                    $this->Session->delete('guestpswd');
                
                   //Sending login details mail to the Guest User ends here..   

                    //Update username                  
                   $this->Cart->updateGuestUserName($user_id, $uname);

                   $this->Cart->updateGuestEmail($user_id, trim($_POST["bemail"]));

                }
                

                $sus["uname"] = $uname;
                $sus["email"] = $_POST["bemail"];
                
                $this->Session->write('Userlog', $sus);

                // Commented out the newsletter forwarding for guest user.


                /*$this->Newsletteruser->create($newsletteruser = array());

                $newsletteruser["id"] = $this->User->id;

                $newsletteruser["uname"] = $sus["uname"];

                $newsletteruser["email"] = $_POST["bemail"];

                $newsletteruser["sub_date"] = date('Y-m-d h:i:s');

                $newsletteruser["status"] = 'N';

                $dups = $this->Newsletteruser->findByEmail($_POST["bemail"]);

                if (empty($dups['Newsletteruser']['email']) === true)
                    $this->Newsletteruser->save($newsletteruser);

                unset($newsletteruser);*/
                
            }

            //Finding the product type in the cart

            $cart_item = $this->Cart->findAllByUserId($user_id);

            $ptype = 'Non-Digital';

            if (!empty($cart_item)) {

                foreach ($cart_item as $item) {

                    if (trim($item["Cart"]["prodtype"]) == "Digital") {

                        $ptype = 'Digital';
                    } else if(trim($item["Cart"]["type"])=="G") { // If the purchase is for gift card treat the product as digital
                        $ptype = 'Digital';
                    }
                }
            }



            $bill["email"] = $_POST["bemail"];

            $bill["fname"] = $_POST["bfname"];

            $bill["lname"] = $_POST["blname"];

            $bill["address"] = $_POST["baddress"];

            $bill["state"] = $_POST["bstate"];

            $bill["country"] = $_POST["data"]["bcountry"];

            if ($_POST["data"]["bcountry"] == 'US') {

                $bill["state"] = $_POST["us_bstate"];
            } else {

                $bill["state"] = $_POST["bstate"];

                unset($_POST["us_bstate"]);
            }

            $bill["city"] = $_POST["bcity"];

            $bill["zip"] = $_POST["bzip"];

            $bill["phone"] = $_POST["bphone"];

            $bill["fax"] = $_POST["bfax"];

            $bill["mobile"] = $_POST["bmobile"];

            $bill["user_id"] = $user_id;

            $bill["addr_type"] = "Billing";

            $this->UserAddress->deleteAll("UserAddress.user_id = " . $user_id . " AND UserAddress.addr_type = 'Billing'");

            $this->UserAddress->create($data = array());

            $data = $bill;

            $this->UserAddress->save($data);



            if ($ptype <> 'Digital') {

                $ship["fname"] = $_POST["sfname"];

                $ship["lname"] = $_POST["slname"];

                $ship["address"] = $_POST["saddress"];

                $ship["country"] = $_POST["data"]["scountry"];

                if ($_POST["data"]["scountry"] == 'US') {

                    $ship["state"] = $_POST["us_sstate"];
                } else {

                    $ship["state"] = $_POST["sstate"];

                    unset($_POST["us_sstate"]);
                }

                $ship["city"] = $_POST["scity"];

                $ship["zip"] = $_POST["szip"];

                $ship["phone"] = $_POST["sphone"];

                $ship["fax"] = $_POST["sfax"];

                $ship["mobile"] = $_POST["smobile"];

                $ship["user_id"] = $user_id;

                $ship["addr_type"] = "Shipping";

                $this->UserAddress->deleteAll("UserAddress.user_id = " . $user_id . " AND UserAddress.addr_type = 'Shipping'");

                $this->UserAddress->create($data = array());

                $data = $ship;

                $this->UserAddress->save($data);
            } else {

                $this->redirect('/carts/payment/');

                exit;
            }
        }

        //Saving the Billing and shipping addresses ends here
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..
        //Code Added By shyam for Category Menu Listing ends here..

        $shipmeth = '';

        if (isset($_POST["shipmeth"]) && $_POST["shipmeth"] <> '') {

            $shipmeth = str_replace("%20", " ", $_POST["shipmeth"]);
        }

        $shipadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Shipping'");

        $cntdet = $this->Country->findByCountryIsoCode_2($shipadd["UserAddress"]["country"]);

        //print_r($cntdet);exit;



        $shipadd["UserAddress"]["country_name"] = $cntdet["Country"]["country_name"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $shipweight = 0;

        $shipchrge = 0;

        $shipchrgeadd = 0;

        $qty = 0;

        $shipflag = 'yes';

        $prodtype = "Non-Digital";

        foreach ($citem as $item) {

            $shipweight += $item["Product"]["weight"] * $item["Cart"]["quantity"];

            $shipchrge += $item["Cart"]["shipping_charge"] * $item["Cart"]["quantity"];

            $qty = $qty + $item["Cart"]["quantity"];

            if ($item["Product"]["prodtype"] == "Digital") {

                $prodtype = "Digital";
            } else if($item["Cart"]["type"]=="G") { // If the purchase is for gift card treat the product as digital

                $prodtype = "Digital";
            }
        }





        if ($prodtype == "Digital") {

            $this->redirect('/carts/payment/');

            exit;
        }





        if ($qty > 0 && $prodtype != "Digital") {

            $shipchrge = $cnfg["flat_shipping_first"];

            $shipchrgeadd = $cnfg["flat_shipping_additional"] * ($qty - 1);

            $shipchrge = $shipchrge + $shipchrgeadd;
        } else {

            $shipchrge = 0;
        }



        $bxno = 1;

        $shipweight2 = $shipweight / $bxno;

        while ($shipweight2 > 149) {

            $bxno++;

            $shipweight2 = $shipweight / $bxno;
        }

        //echo $shipweight2."<br>".$bxno; exit;

        if ($shipweight2 == 0)
            $shipweight2 = 0.1;

        $module_shipping_ups_types = '1DM, 1DML, 1DA, 1DAL, 1DAPI, 1DP, 1DPL, 2DM, 2DML, 2DA, 2DAL, 3DS, GND, STD, XPR, XPRL, XDM, XDML, XPD';

        $origin_country = $cnfg["shipping_origin_country"];

        $origin_postal = $cnfg["shipping_origin_zip"];

        $destination_country = $shipadd["UserAddress"]["country"];

        $destination_postal = $shipadd["UserAddress"]["zip"];

        if ($destination_country == 'CA') {

            $prod = 'STD';
        } else {

            $prod = 'GNDRES';
        }

        $this->set('shipadd', $shipadd);



        if ($shipmeth == 'UPS') {

            $ups_action_code = '4';

            $text_shipping_weight = '&nbsp;lbs';

            ############# These parts has to make dynamic from dbtable###################3333

            $rate_chart = 'Letter+Center'; //$shipping_settings_row['vvalue'];

            $container_code = '00'; //$shipping_settings_row['vvalue'];

            $res_code = '1'; //$shipping_settings_row['vvalue'];

            $shipping_box_weight_display = '3'; //$shipping_settings_row['vvalue'];

            $shipping_num_boxes = $bxno; //$shipping_settings_row['vvalue'];

            $module_shipping_handling = '';

            ####################################################################################

            $shipopt = $this->Upsshipping->passValues($module_shipping_handling, $shipping_num_boxes, $shipping_box_weight_display, $res_code, $container_code, $rate_chart, $ups_action_code, $text_shipping_weight, $prod, $shipweight2, $origin_country, $origin_postal, $destination_country, $destination_postal, $module_shipping_ups_types);
            
            if (isset($shipopt) && empty($shipopt) === false) {

                $this->set('shipopt', $shipopt);
                $this->set('shipflag', 'yes');
            } else {

                $this->__setFlateRate($qty);

                $this->set('shipflag', 'no');
            }
        } elseif ($shipmeth == 'USPS') {



            ################## Portion for USPS Shipping Starts.........................................



            /* Correct working details

              $usps->setServer("http://testing.shippingapis.com/ShippingAPITest.dll");

              $usps->setUserName("599ARMIA0450");

              $usps->setPass("");

              $usps->setService("All");

              $usps->setDestZip("20008");

              $usps->setOrigZip("10022");

              $usps->setWeight(10, 5);

              $usps->setContainer("Flat Rate Box");

              $usps->setCountry("USA");

              $usps->setMachinable("true");

              $usps->setSize("LARGE");

            */

            ############# These parts has to make dynamic from dbtable###################3333

            $this->Usps->setServer("http://stg-production.shippingapis.com/ShippingAPI.dll");

            $this->Usps->setUserName($cnfg["USPS_Username"]);

            $this->Usps->setService("All");

            $this->Usps->setDestZip($destination_postal);

            $this->Usps->setOrigZip($origin_postal);

            ############# These parts has to make dynamic from dbtable###################3333

            $this->Usps->setWeight(10, 5);

           // $this->Usps->setContainer("Flat Rate Box");

            //$this->Usps->setCountry($destination_country);

            $this->Usps->setCountry('USA');

            $this->Usps->setMachinable("true");

            $this->Usps->setSize("REGULAR");

            $price = $this->Usps->getPrice();
            
            $MailArray = array();

            if ($price) {

                foreach ($price as $key => $value) {

                    if ($key == 'list') {

                        for ($it = 0; $it < count($value); $it++) {

                            $MailArray[$it]['title'] = $this->CheckValue($value[$it]);

                            $MailArray[$it]['cost'] = $this->CheckValuePrice($value[$it]);
                        }//end for loop
                    }//end if
                }//end foreach
            }

            //  $this->set('shipopt', $MailArray);

            if (isset($MailArray) && empty($MailArray) === false) {

                $this->set('shipopt', $MailArray);
                $this->set('shipflag', 'yes');
            } else {

                $this->__setFlateRate($qty);

                $this->set('shipflag', 'no');
            }
        } elseif ($shipmeth == 'Australiapost') {

            ################## Portion for USPS Shipping Starts.........................................
            ################## Portion for Australiapost Shipping.......................................



            $Pickup_Postcode = $origin_postal;

            $Destination_Postcode = $destination_postal;

            $Country = $destination_country;

            $Weight = $shipweight;

            $Service_Type = "STANDARD";

            $Length = "100";

            $Width = "100";

            $Height = "40";

            $Quantity = "1";



            $this->Australiapost->set_Pickup_Postcode($Pickup_Postcode);

            $this->Australiapost->set_Destination_Postcode($Destination_Postcode);

            $this->Australiapost->set_Country($Country);

            $this->Australiapost->set_Weight($Weight);

            $this->Australiapost->set_Service_Type($Service_Type);

            $this->Australiapost->set_Length($Length);

            $this->Australiapost->set_Width($Width);

            $this->Australiapost->set_Height($Height);

            $this->Australiapost->set_Quantity($Quantity);

            $auspost = $this->Australiapost->getRate();

            //$this->set('shipopt', $auspost);



            if (isset($auspost) && empty($auspost) === false) {

                $this->set('shipopt', $auspost);
                $this->set('shipflag', 'yes');
            } else {

                $this->__setFlateRate($qty);

                $this->set('shipflag', 'no');
            }
        } elseif ($shipmeth == 'Canadapost') {

            ################## Portion for Ausrtaliapost Shipping.......................................
            ################## Portion for Canadapost Shipping Starts...................................

            $this->Canadapost->setval($cnfg["canadamerchantid"], $cnfg["shipping_origin_zip"]);

            $this->Canadapost->setCustomer(array(
                    'city' => $shipadd["UserAddress"]["city"],
                    'provOrState' => $shipadd["UserAddress"]["state"],
                    'country' => $shipadd["UserAddress"]["country"],
                    'postalCode' => $shipadd["UserAddress"]["zip"]
                    )
            );



            $this->Canadapost->addProduct(array(
                    'quantity' => '1',
                    'weight' => $shipweight,
                    'length' => '1',
                    'width' => '1',
                    'height' => '1',
                    'description' => ' '
                    )
            );



            $assoc_Array = $this->Canadapost->getRates('array');

            if (!empty($assoc_Array["product"])) {

                $i = 0;

                foreach ($assoc_Array["product"] as $sv) {

                    $capost[$i]["title"] = $sv["name"];

                    $capost[$i]["cost"] = $sv["rate"];

                    $i++;
                }
            }

            //  if(isset($capost) && empty($capost)===false)
            //  $this->set('shipopt', $capost);

            if (isset($capost) && empty($capost) === false) {

                $this->set('shipopt', $capost);
                $this->set('shipflag', 'yes');
            } else {

                $this->__setFlateRate($qty);

                $this->set('shipflag', 'no');
            }
        } elseif ($shipmeth == 'FEDEX') {
               
          require_once '../library/class.fedex.php';
          
            require_once '../library/class.fedex.rate.php';
             
            require_once '../library/class.fedex.package.php'; 
        
         
            if ($shipadd["UserAddress"]["country"] == "United States" || $shipadd["UserAddress"]["country"] == "US") {

                $fedexService['PRIORITYOVERNIGHT'] = 'FedEx Priority Overnight';

                $fedexService['STANDARDOVERNIGHT'] = 'FedEx Standard Overnight';

                $fedexService['FIRSTOVERNIGHT'] = 'FedEx First Overnight';

                $fedexService['FEDEX2DAY'] = 'FedEx 2 Day';

                $fedexService['FEDEXEXPRESSSAVER'] = 'FedEx Express Saver';

                $fedexService['FEDEX1DAYFREIGHT'] = 'FedEx Overnight Freight';

                $fedexService['FEDEX2DAYFREIGHT'] = 'FedEx 2 day Freight';

                $fedexService['FEDEX3DAYFREIGHT'] = 'FedEx 3 day Freight';

                $fedexService['FEDEXGROUND'] = 'FedEx Ground';

                $fedexService['GROUNDHOMEDELIVERY'] = 'FedEx Home Delivery';
            } else {

                $fedexService['INTERNATIONALPRIORITY'] = 'FedEx International Priority';

                $fedexService['INTERNATIONALECONOMY'] = 'FedEx International Economy';

                $fedexService['INTERNATIONALFIRST'] = 'FedEx International First';
            }





            /*

              $fedexaccno='510088000';

              $fedexmeterno='100022250';

            */

            $fedexaccno = trim($cnfg["fedexbillaccno"]);

            $fedexmeterno = trim($cnfg["fedexmeterno"]);
            
             $fedexPassword = trim($cnfg["fedexpaswd"]);
             $fedexKey      = trim($cnfg["fedexkey"]);

            $weightunits = 'LBS';

            $server = 'test';

            $dropoff = 'REGULARPICKUP';

            $packageTypes = 'YOURPACKAGING';

            $currency = 'USD';
            

             //include_once(WWW_ROOT."Fedex/wsdl/RateService_v13.wsdl");
             //print '<pre />';print_r($rateResponseArr);exit; 
            $path_to_wsdl=WWW_ROOT.'Fedex/wsdl/RateService_v9.wsdl';
             
           /****** new fedex code ******************/
            
           $objRates   = new stdClass();
            $objRates->ship_account =trim($fedexaccno);
            $objRates->meter = trim($fedexmeterno);
            $objRates->password = trim($fedexPassword);
            $objRates->account         =    "";
            $objRates->bill_account         =    "";
            $objRates->duty_account         =    "";
            $objRates->account_to_validate  =    "";
            $objRates->track_account        =    "";
            $objRates->key                  =   trim($fedexKey);
            $objRates->wsdl_path            =   "RateService_v9.wsdl";
                        
                        $objRate = new fedexRates();
            $objRate->requestType("rate");

            $objRate->setData($objRates);

            $objRate->wsdl_root_path = "wsdl/";
                    
                        $client = new SoapClient($path_to_wsdl, array('trace' => 1)); 
                        
                      
            /****** new fedex code ******************/
           
            /*************** New Fedex code START HERE ****************************/
            if($cnfg["shipping_origin_city"]!=''){
                 $origin_city = $cnfg["shipping_origin_city"];
            }else{
                $origin_city = $cnfg["shipping_origin_state"];
            }       
           
            $aryShipper = array(
             'Contact' => array(
                    'PersonName' => 'Sendder name',
                    'CompanyName' => 'Test Company',
                    'PhoneNumber' => '9876543211'),
                    'Address' => array(
                            'StreetLines' => array('Address Line 1'),
                            'City' => $origin_city,
                            'StateOrProvinceCode' =>$cnfg["shipping_origin_state"],
                            'PostalCode' => $cnfg["shipping_origin_zip"],
                            'CountryCode' => $cnfg["shipping_origin_country"])
            );
            
            $aryRecipient = array(
                    'Contact' => array(
                            'PersonName' => 'James smith',
                            'CompanyName' => 'armia systems',
                            'PhoneNumber' => '9876543210'
                    ),
                    'Address' => array(
                            'StreetLines' => array('Address Line 1'),
                            'City' => $shipadd["UserAddress"]["city"],
                            'StateOrProvinceCode' => $shipadd["UserAddress"]["state"],
                            'PostalCode' => $shipadd["UserAddress"]["zip"],
                            'CountryCode' => $shipadd["UserAddress"]["country"],
                            'Residential' => false)
            );
            
            $fedexService                      =  array('PRIORITY_OVERNIGHT','STANDARD_OVERNIGHT','INTERNATIONAL_PRIORITY','FEDEX_GROUND','FIRST_OVERNIGHT','FEDEX2DAY');//array('FEDEX_GROUND');
            
            $rateResponseArr                   = array();
            
            foreach($fedexService as $serviceNames) {
            $packages = array();
            
            $aryPackage = array();
            
            $total_packages = 1;
             
            if($product_length==0 || $product_length>70)
            {
            $product_length = '17.88';
            }
             
            if($product_width==0 || $product_width>70)
            {
            $product_width = '12.88';
            }
             
            if($product_height==0 || $product_height>10)
            {
            $product_height = '3.00';
            }
             
            
            $packages[0] = new Package("FEDEX Package # 1", $total_packages, 1);
            $packages[0]->setPackageWeight($shipweight);     //Package Actual Weight
            $packages[0]->setPackageDimensions($product_length, $product_width, $product_height);       //Package (Length x Width x Height)
            $aryPackage[0] = $packages[0]->getObjectArray();
            
            $aryOrder = array(
                    'TotalPackages' => $total_packages,
                    'PackageType' => 'YOUR_PACKAGING',        #FEDEX_10KG_BOX, FEDEX_25KG_BOX, FEDEX_BOX, FEDEX_ENVELOPE, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
                    'ServiceType' => $serviceNames,
                    'TermsOfSaleType' => "DDU",         #    DDU/DDP
                    'DropoffType' => 'REGULAR_PICKUP'         # BUSINESS_SERVICE_CENTER, DROP_BOX, REGULAR_PICKUP, REQUEST_COURIER, STATION
            );
            
             
            $request = $objRate->rateRequest($aryRecipient,$aryShipper,$aryOrder,$aryPackage);
            
            //print '<pre />';print_r($request);
            
            $rateResponseArr[]    = $objRate->getRates($request,$client);
             
            }
            
            //print '<pre />';print_r($rateResponseArr);exit;
            
            $jt = 0;
            
            if(!empty($rateResponseArr))  {
            foreach($rateResponseArr as $serviceVals)
            {
            if(@$serviceVals->error=='' && $serviceVals->ServiceName!=''){
             
            $fed[$jt]["title"] = @$serviceVals->ServiceName;
            $fed[$jt]["cost"] = @$serviceVals->amount;
            
            $jt++;
            }
            }
             
             
            }  
            
            /*************** New Fedex code End HERE ****************************/


            if (isset($fed) && empty($fed) === false) {

                $this->set('shipopt', $fed);
                $this->set('shipflag', 'yes');
            } else {

                $this->__setFlateRate($qty);
                $shipmeth = 'Flat Rate Shipping';
                $this->set('shipflag', 'no');
            }

            ################## Portion for Fedex Shipping..........................................
        } else {

            ######@@@@@@@@@@@@@@@ Section for Flat rate shippings;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

            $shipme = $this->Setting->findByValue($shipmeth);

            $this->__getFlateRate($shipmeth, $qty);

            $this->set('shipflag', 'yes');

            ######@@@@@@@@@@@@@@@ Section for Flat rate shippings;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
        }





        $citem = $this->Cart->findAllByUserId($user_id);

        $this->set('prodtype', "Non-digital");

        if (!empty($citem)) {

            foreach ($citem as $it) {

                if ($it["Product"]["prodtype"] == "Digital") {

                    $this->set('prodtype', "Digital");
                }else if(trim($it["Cart"]["type"])=="G") { // If the purchase is for gift card treat the product as digital
                       $this->set('prodtype', "Digital");
                    }
            }
        }
       

        $this->set('shippingmethod', $shipmeth);
        
        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', $curr["Currency"]["logo"]);

    }


    function __setFlateRate($qty = 0) {

        $cnfg = Configure::read('Neutrino');

        $ship_method = '';

        if ($cnfg["fflat_shipping_require"] == "Y") {

            $ship_method = $cnfg["flat_ship_name"];
        } else if ($cnfg["sflat_shipping_require"] == "Y") {

            $ship_method = $cnfg["secflat_ship_name"];
        } else if ($cnfg["tflat_shipping_require"] == "Y") {

            $ship_method = $cnfg["thirdflat_ship_name"];
        }

        if ($cnfg["foflat_shipping_require"] == "Y") {

            $ship_method = $cnfg["forthflat_ship_name"];
        }

        $this->__getFlateRate($ship_method, $qty);
    }

    function __getFlateRate($ship_method = '', $qty = 0) {

        $cnfg = Configure::read('Neutrino');

        $shipme = $this->Setting->findByValue($ship_method);

        if ($shipme["Setting"]["fieldname"] == "flat_ship_name") {

            $shipchrge = $cnfg["flat_shipping_first"];

            $shipchrgeadd = $cnfg["flat_shipping_additional"] * ($qty - 1);

            $shipchrge = $shipchrge + $shipchrgeadd;

            $shiph[0]["title"] = $ship_method;

            $shiph[0]["cost"] = $shipchrge;

            $this->set('first_item', $cnfg["flat_shipping_first"]);

            $this->set('additional_item', $cnfg["flat_shipping_additional"]);

            $this->set('shipopt', $shiph);

            $this->set('pshipchrg', $shipchrge);
        } elseif ($shipme["Setting"]["fieldname"] == "secflat_ship_name") {

            $shipchrge = $cnfg["secflat_shipping_first"];

            $shipchrgeadd = $cnfg["secflat_shipping_additional"] * ($qty - 1);

            $shipchrge = $shipchrge + $shipchrgeadd;

            $shiph[0]["title"] = $ship_method;

            $shiph[0]["cost"] = $shipchrge;

            $this->set('first_item', $cnfg["secflat_shipping_first"]);

            $this->set('additional_item', $cnfg["secflat_shipping_additional"]);

            $this->set('shipopt', $shiph);

            $this->set('pshipchrg', $shipchrge);
        } elseif ($shipme["Setting"]["fieldname"] == "thirdflat_ship_name") {

            $shipchrge = $cnfg["thirdflat_shipping_first"];

            $shipchrgeadd = $cnfg["thirdflat_shipping_additional"] * ($qty - 1);

            $shipchrge = $shipchrge + $shipchrgeadd;

            $shiph[0]["title"] = $ship_method;

            $shiph[0]["cost"] = $shipchrge;

            $this->set('first_item', $cnfg["thirdflat_shipping_first"]);

            $this->set('additional_item', $cnfg["thirdflat_shipping_additional"]);

            $this->set('shipopt', $shiph);

            $this->set('pshipchrg', $shipchrge);
        } elseif ($shipme["Setting"]["fieldname"] == "forthflat_ship_name") {

            $shipchrge = $cnfg["forthflat_shipping_first"];

            $shipchrgeadd = $cnfg["forthflat_shipping_additional"] * ($qty - 1);

            $shipchrge = $shipchrge + $shipchrgeadd;

            $shiph[0]["title"] = $ship_method;

            $shiph[0]["cost"] = $shipchrge;

            $this->set('first_item', $cnfg["forthflat_shipping_first"]);

            $this->set('additional_item', $cnfg["forthflat_shipping_additional"]);

            $this->set('shipopt', $shiph);

            $this->set('pshipchrg', $shipchrge);
        } else {

            $this->set('first_item', 0);

            $this->set('additional_item', 0);

            $this->set('shipopt', '');

            $this->set('pshipchrg', 0);
        }
        global $currency;

        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', $curr["Currency"]["logo"]);
    }

    function payment() {

        $ship = "";
        
        $cnfg = Configure::read('Neutrino');

        $this->set('cnfg', $cnfg);
        
        //print '<pre />';print_r($cnfg);
        if (isset($_POST["ship_method"])) {
            if ($this->Session->check('SESS_SHIPMENT')) {
                $this->Session->delete('SESS_SHIPMENT');
            }
        }
        
        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $user_id = $sus["id"];

        $creditBalance = $this->Product->formatToPrice($this->User->getUserCredits($user_id));

        $this->set('creditBalance', $creditBalance);

        $dataUserArr = $this->User->getUserCredits($user_id);

        $cnfg = Configure::read('Neutrino');

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);

        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        



        ########################## Getting total price from cart ******************************************

        $citem = $this->Cart->findAllByUserId($user_id);

        if (count($citem) < 1) {
            $this->redirect(array('controller' => 'pages', 'action' => 'display'));
            exit();
        }

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                     
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        $this->set('prodtype', $prod_type);
        //Getting the product type in the cart
        
        /**************** Shiiping ***********************  */
        
        $ship = '';

        $shippingMethod = '';

        $shippingServ = '';

        $shipping_cost = 0;

 
        if (isset($_POST["ship_method"])) {

            $ship = $_POST["ship_method"];

            if ($ship <> '') {

                $shipp = explode('|~@~|', $ship);

                $shippingMethod = $shipp[0];

                $shippingServ = $shipp[1];

                $shipping_cost = $shipp[2];

                $this->Session->write('SESS_SHIPMENT', $ship);
            } else {

                $ship = '';

                $shippingMethod = '';

                $shippingServ = '';

                $shipping_cost = 0;
            }
        } else {
            if($prod_type=='Digital'){
                if ($this->Session->check('SESS_SHIPMENT')) {
                $this->Session->delete('SESS_SHIPMENT');
                }
            }else {

            if ($this->Session->check('SESS_SHIPMENT')) {
                

                $ship = $this->Session->read('SESS_SHIPMENT');

                if ($ship <> '') {

                    $shipp = explode('|~@~|', $ship);

                    $shippingMethod = $shipp[0];

                    $shippingServ = $shipp[1];

                    $shipping_cost = $shipp[2];
                }

            }else {

                $ship = '';

                $shippingMethod = '';

                $shippingServ = '';

                $shipping_cost = 0;
            }

              $this->Session->write('SESS_SHIPMENT', $ship);
            }
        }
        
        /******************** Shipping ******************** */


        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }

        $this->set('totaltopay', number_format($tot_price, 2, ".", ""));



        ########################## Getting total price from cart ******************************************
        ######################### Section to find and add tax amount.............................

        $taxamt = 0;

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }



        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {


            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }
            else {
                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';



        if ($this->Session->check('Coupon') == true) {
            $couparray = $this->Session->read('Coupon');
            $tdat = date("Y-m-d");

            if (strtotime($tdat) >= strtotime($couparray["Coupon"]["from_date"]) && strtotime($tdat) <= strtotime($couparray["Coupon"]["to_date"]) && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    //$discamt  =   $couparray["Coupon"]["giftvalue"];

                    if ($couparray["Coupon"]["giftvalue"] >= $tot_price)
                        $discamt = $tot_price;

                    else
                        $discamt = $couparray["Coupon"]["giftvalue"];
                }else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = number_format(($tot_price - $discamt), 2, ".", "");

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        //exit();
        ########################## Coupon code section ******************************************
        ######################### End of Section to find and add tax amount......................
        //$totaltopay =     number_format($tot_price,2,".","");

        if ($tot_price > 0)
            $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");

        else
            $gtotal = number_format(0.00 + $shipping_cost, 2, ".", "");
        
         if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
            //$gtotal = $gtotal-  $giftcardamt;  
            $gtotal = number_format($gtotal,2,".","");
            
        }

        $paymentMethod = "CC";

        $trans_id = '';

        $giftcard_cnt = $this->GiftcardDetail->find('count', array('conditions' => array('GiftcardDetail.user_id' => $user_id)));

        $this->set('giftcard_cnt', $giftcard_cnt);
        $this->set('gift_crd_discount', 0);
        
        /**************************************** IF USING GIFT CARD **********************************/
        if (isset($_POST["giftcard"]) == "yes" && $_POST["giftcode"] <> ''){ 
            $gdet = $this->GiftcardDetail->find('first', array('conditions' => array('GiftcardDetail.card_code' => trim($_POST["giftcode"]))));

            $avail_balance = 0;
            if (isset($gdet) && !empty($gdet)){
                $gdetuser_id        = $gdet["GiftcardDetail"]["user_id"];
                $avail_balance      = $gdet["GiftcardDetail"]["balance"];
                $this->card_id      = $gdet["GiftcardDetail"]["card_id"];
                $this->usercard_id  = $gdet["GiftcardDetail"]["id"];                
                $this->amnt_used    = $gtotal;                
            
                if ($avail_balance >= $gtotal){
                    //Updating the Amount for gift card....
                    $gftdetbl   = $this->Cart->getTableName("giftcard_details");
                    $gftres     = $this->Giftcard->query("UPDATE " . $gftdetbl . " set balance =( balance - " . $gtotal . ") where card_code='" . trim($_POST["giftcode"]) . "' and  user_id='" . $gdetuser_id . "'");
                    $shipadd    = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Shipping'");
                    $cntdet     = $this->Country->findByCountryIsoCode_2($shipadd["UserAddress"]["country"]);
                    $shipadd["UserAddress"]["country_name"] = $cntdet["Country"]["country_name"];
                    $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $taxState, $taxCountry, $couponcode, $discamt, 'Gift Card' , $trans_id,$subtotal_amount);                                 
                    exit;
                }else{       
                    if ($avail_balance > 0){
                        $gftdetbl   = $this->Cart->getTableName("giftcard_details");
                        $gftres     = $this->Giftcard->query("UPDATE " . $gftdetbl . " set balance = 0 where card_code='" . trim($_POST["giftcode"]) . "' and  user_id='" . $gdetuser_id . "'");
                        $shipadd    = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Shipping'");
                        $cntdet     = $this->Country->findByCountryIsoCode_2($shipadd["UserAddress"]["country"]);
                        $shipadd["UserAddress"]["country_name"] = $cntdet["Country"]["country_name"];
                        
                        $gtotal     = $gtotal - $avail_balance;                        
                        
                        if($this->Session->check('GiftCardDiscount') == true){
                            $this->set('giftcardamt', $avail_balance);
                        }
                        $this->Session->write('GiftCardDiscountAmount',$avail_balance); 
                        $availbl_balance = $avail_balance;
                        $this->set('gift_crd_discount', $availbl_balance);
                        $avail_balance = 0;
                    }else{                    
                        $this->Session->setFlash(__('Sorry,You you don\'t have sufficient balance to make this purchase.Your balance is '.$curr["Currency"]["logo"].$avail_balance.'', true));                 
                        $this->redirect(array('controller' => 'carts', 'action' => 'payment'));
                        exit();
                    }
                }
            }else{
                $this->Session->setFlash(__('Sorry, the gift card does not exists!', true));                 
                $this->redirect(array('controller' => 'carts', 'action' => 'payment'));
                exit();
            }
        }
        /**************************************** IF USING GIFT CARD **********************************/
   
        /* if (isset($_POST["giftcard"]) == "yes" && $_POST["giftcode"] <> '') {         
             

            $gdet = $this->GiftcardDetail->find('first', array('conditions' => array('GiftcardDetail.card_code' => trim($_POST["giftcode"]))));

            $avail_balance = 0;
            
           

            if (isset($gdet) && !empty($gdet)) {

                $gdetuser_id = $gdet["GiftcardDetail"]["user_id"];

                $avail_balance = $gdet["GiftcardDetail"]["balance"];

                $this->card_id = $gdet["GiftcardDetail"]["card_id"];

                $this->usercard_id = $gdet["GiftcardDetail"]["id"];
                
                $this->amnt_used = $gtotal;
                
           

            if ($avail_balance >= $gtotal) {

                //Updating the Amount for gift card....
                
                 $this->Session->write('GiftCard', $gdet);

                $gftdetbl = $this->Cart->getTableName("giftcard_details");

                $gftres = $this->Giftcard->query("update " . $gftdetbl . " set balance=(balance-" . $gtotal . ") where card_code='" . trim($_POST["giftcode"]) . "' and  user_id='" . $gdetuser_id . "'");


                $shipadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Shipping'");

                $cntdet = $this->Country->findByCountryIsoCode_2($shipadd["UserAddress"]["country"]);

                $shipadd["UserAddress"]["country_name"] = $cntdet["Country"]["country_name"];
                $giftcard_amt  = number_format($gtotal,2,".","");
                $gtotal = 0;  
                $gtotal = number_format($gtotal,2,".","");
                

                $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Gift Card' , $trans_id,'',$giftcard_amt);
                
                 
                exit;
            }else if($avail_balance>0){
               
                $this->Session->write('GiftCardDiscount', $gdet);
                $this->Session->write('Gstatus',1);
                
                if ($this->Session->check('GiftCardDiscount') == true) {
                        $this->set('giftcardamt', $avail_balance);
                }
                $this->Session->setFlash(__('Gift card appied successfully!!', true));
                $this->redirect(array('controller' => 'carts', 'action' => 'payment'));
                 exit();
                
                 
            }else {
                $this->Session->delete('GiftCardDiscount');
                $this->Session->write('Gstatus',0);
                $this->Session->setFlash(__('Sorry,You don\'t have sufficient balance to make this purchase.Your balance is '.$avail_balance.'', true));
                 
                 $this->redirect(array('controller' => 'carts', 'action' => 'payment'));
                 exit();
            }
          }else {
              
               $this->Session->delete('GiftCardDiscount');
                $this->Session->write('Gstatus',0);
                $this->Session->setFlash(__('Sorry,You have entered an Invalid Gift Card Code.', true));
                 
                 $this->redirect(array('controller' => 'carts', 'action' => 'payment'));
                 exit();
              
          }
        } */

        // Use Balance Credits

        if (isset($_POST["credits"]) == "yes" && $_POST["credits"] <> '') {

            if ($creditBalance >= $gtotal) {

                //Deduct user credits
                $this->User->updateUserCredits($user_id, $gtotal);
                
                $gtotal = number_format($gtotal,2,".","");
                
              
                $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Credits' , $trans_id,'',$giftcardamt);

                exit;
            }
        }

        // End Use Balance credits

        //Paypla pro cash limit
        $paypalpropaylimit = 10000;
        if($curr['Currency']['code'] == 'GBP')
            $paypalpropaylimit = 5500;
        elseif($curr['Currency']['code'] == 'CAD')
            $paypalpropaylimit = 12500;
        //starting session for holding "Shipment type and amount"

        $this->set('taxamnt', $taxamt);

        $this->set('gtotal', $gtotal);

        $this->set('discount', $discamt);

        $this->set('userid', $user_id);

        $this->set('paymentMethod', $paymentMethod);

        $this->set('shipping_cost', $shipping_cost);

        $this->set('ship', $ship);

        $this->set('cnfg', $cnfg);

        $this->set('ship', $ship);

        $this->set('cnfg', $cnfg);

        $this->set('paypalpropaylimit', $paypalpropaylimit);
        


        //$this->set('catmenu', $lst);
    }

    function paypal($ship = '') {

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        //$lst              =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }

        $cnfg = Configure::read('Neutrino');

        $txtPaypalEmail = $cnfg["paypal_email"];

        $txtPaypalSandbox = $cnfg["paypal_testmode"];

        if ($txtPaypalSandbox == "Y") {

            //$paypalurl        =   "http://192.168.0.11/sudheesh/paypal.php";

            $paypalurl = "https://www.sandbox.paypal.com/cgi-bin/webscr";

            $paypalbuttonurl = "https://www.sandbox.paypal.com/en_US/i/btn/x-click-but23.gif";
        } else {

            //$paypalurl        =   "http://192.168.0.11/sudheesh/paypal.php";

            $paypalurl = "https://www.paypal.com/cgi-bin/webscr";

            $paypalbuttonurl = "https://www.paypal.com/en_US/i/btn/x-click-but23.gif";
        }

        //$referrer     `           =   $_SERVER["HTTP_REFERER"];

        $shipping_form = "<input type='hidden' name='shipping' value='$shipping_cost'>";

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"])=="G") { // If the purchase is for gift card treat the product as digital
                      $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }



        ########################## Coupon code section ******************************************

        $discamt = 0;

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

         
            $tdat = date("Y-m-d");

            $curdate =  strtotime($tdat);
            $todate  =  strtotime($couparray["Coupon"]["to_date"]);

            //echo "<br>---".$curdate."----".$todate;

        if (($curdate < $todate) && ($tot_price >= $couparray["Coupon"]["minamt"])) {

               // echo $tot_price."===fsdfhjsdf";

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            

            $tot_price = $tot_price - $discamt;

            $couparray["Coupon"]["discount"] = $discamt;

            $this->Session->write('Coupon', $couparray);
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {


                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }



        $this->Session->write('Taxamount', $taxamt);

        $this->Session->write('Taxname', $taxname);

        ######################### End of Section to find and add tax amount......................
        
        

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
         
        if($this->Session->check('GiftCardDiscountAmount') == true) { //echo "GiftCardDiscAmount = ".$this->Session->read('GiftCardDiscountAmount');
            $giftcarddiscamount = $this->Session->read('GiftCardDiscountAmount');
            if($giftcarddiscamount){
                $gtotal = $gtotal - $giftcarddiscamount;
            }
            $this->set('giftcarddiscamount', $giftcarddiscamount);
        }else{
            $this->set('giftcarddiscamount', 0);
        }
         
        $this->set('totaltopay', $totaltopay);

        $this->set('paypalurl', $paypalurl);

        $this->set('paypalbuttonurl', $paypalbuttonurl);

        $this->set('txtPaypalEmail', $txtPaypalEmail);

        $this->set('shipping_form', $shipping_form);

        $this->set('shipping_cost', $shipping_cost);

        $this->set('cnfg', $cnfg);
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
             $this->set('gift_discount', $giftcardamt);
            //$this->set('gift_card_amt', $giftcardamt);
              
            $gtotal = $gtotal - $giftcardamt;
            
            $gtotal  = number_format($gtotal, 2, ".", "");
            
        }
        $this->set('gtotal', $gtotal);

        $this->Session->write('Payamount', $gtotal);

        $this->Session->write('Shipmethod', $shippingMethod);

        $this->Session->write('Shipserv', $shippingServ);

        $this->Session->write('Shipcost', $shipping_cost);

        //print_r($cnfg["site_name"]);exit;
    }

    function paysuccess() {

        $this->__validateLoginStatus();

        $cnfg = Configure::read('Neutrino');

        $auth_token = $cnfg["paypal_idtoken"];

        $tx_token = '';

        if (isset($_GET['tx'])) {

            $tx_token = $_GET['tx'];
        }

        $txtPaypalEmail = $cnfg["paypal_email"];

        $txtPaypalSandbox = $cnfg["paypal_testmode"];

        if ($txtPaypalSandbox == "Y") {

             $pp_hostname = "www.sandbox.paypal.com";
        } else {

             $pp_hostname = "www.paypal.com";
        }

        $flag_to_continue = false;

        $paypal_check = 0;

        $req = 'cmd=_notify-synch';

$req .= "&tx=$tx_token&at=$auth_token";
 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://$pp_hostname/cgi-bin/webscr");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
//set cacert.pem verisign certificate path in curl using 'CURLOPT_CAINFO' field here,
//if your server does not bundled with default verisign certificates.
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: $pp_hostname"));
$res = curl_exec($ch);
curl_close($ch);



if(!$res){
    //HTTP ERROR
}else{
     // parse the data
    $lines = explode("\n", trim($res));
    $keyarray = array();

    if (strcmp ($lines[0], "SUCCESS") == 0) {
        for ($i = 1; $i < count($lines); $i++) {
            $temp = explode("=", $lines[$i],2);
            $keyarray[urldecode($temp[0])] = urldecode($temp[1]);
        }

         $flag_to_continue = true;
    
    }
    else if (strcmp ($lines[0], "FAIL") == 0) {
        // log for manual investigation
         $flag_to_continue = false;
    }
}

 
        if ($flag_to_continue == true) {

            // echo "successs"; exit;

            ;
        } else {

            $this->Session->setFlash('Invalid request.Please try again later.');

            $this->redirect('/carts/show');

            exit;
        }
        $trans_id = $_GET['tx'];
//print_r($_SESSION);exit;
        $amount_compare = number_format($_GET['amt'], 2, ".", "");

        $sessPayamt = $this->Session->read('Payamount');

        $sessTaxamt = $this->Session->read('Taxamount');

        $sessTaxnam = $this->Session->read('Taxname');

        $sessShipmeth = $this->Session->read('Shipmethod');

        $sessShipserv = $this->Session->read('Shipserv');

        $sessShipcost = $this->Session->read('Shipcost');

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $discamt = $couparray["Coupon"]["discount"];

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $couparray["Coupon"]["discount"];

            $couponcode = $couparray["Coupon"]["code"];
        }
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
            // $gtotal = $gtotal-  $giftcardamt;    
            
        }

        ########################## Coupon code section ******************************************

        if (isset($sesspayamt) && $sesspayamt != "") {

            if ($sesspayamt != $amount_compare) {

                $paypal_check = 1;
            }
        }

        if ($paypal_check == 1) {

            $this->Session->setFlash('Order Cannot be Processed, Please contact the Administrator!!');

            $this->redirect('/index.php');

            exit;
        } else {

            $this->sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $sessTaxamt, $sessTaxnam, $couponcode, $discamt, 'PayPal' , $trans_id,'',$giftcardamt);

            exit;
        }
    }

    function payfailure() {

        $this->Session->setFlash('Payment Failure! <br> Your order can not be processed !<br> Try again!');

        $this->redirect('/index.php');

        exit;
    }

    function paypalexpress($ship = '') {

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }



        ########################## Coupon code section ******************************************

        $discamt = 0;

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $couparray["Coupon"]["discount"] = $discamt;

            $this->Session->write('Coupon', $couparray);
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        $this->Session->write('Taxamount', $taxamt);

        $this->Session->write('Taxname', $taxname);

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $gtotal = $gtotal-  $giftcardamt; 
             
             $gtotal = number_format($gtotal,2,".","");
            
         }

        $this->Session->write('Payamount', $gtotal);

        $this->Session->write('Shipmethod', $shippingMethod);

        $this->Session->write('Shipserv', $shippingServ);

        $this->Session->write('Shipcost', $shipping_cost);

        //--------------------------------The API call------------------------------//
        $credential_array['api_uname']    = $cnfg["paypal_express_username"];
        $credential_array['api_pass']     = $cnfg["paypal_express_password"];
        $credential_array['api_sig']      = $cnfg["paypal_express_signature"];

        $txtPaypalExpressSandbox = $cnfg["paypal_express_testmode"];

        if ($txtPaypalExpressSandbox == "Y") {
            $credential_array['api_env']    = "sandbox";
        }
        else {
            $credential_array['api_env']    = "live";
        }

        //set the return urls
        $return_url = FULL_BASE_URL.$cnfg["sitebasefolder"].'/carts/paypalexpressreturn';
        $fail_url   = FULL_BASE_URL.$cnfg["sitebasefolder"].'/carts/paypalexpressfail';

        //prevent timeout
        set_time_limit(0);

        $this->Paypal->setCredentials($credential_array);
        $do_transaction = $this->Paypal->setExpressCheckout("PAYMENTACTION=Sale&AMT={$gtotal}&RETURNURL={$return_url}&CANCELURL={$fail_url}");

        if($do_transaction) {
            $paypalurl = $this->Paypal->getPaypalUrl();

            header("location:$paypalurl&useraction=commit");
        }
        else {
            exit;
            $this->redirect(array('controller' => 'carts', 'action' => 'paypalexpressfail'));
        }

        exit;
    }

    function paypalexpressreturn() {
        //complete the transaction
        $coupon         = $this->Session->read('Coupon');
        $discamt        = $coupon["Coupon"]["discount"];
        $couponcode     = $coupon["Coupon"]["code"];
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
          
        }


        $this->sendOrderMail($this->Session->read('Shipmethod'), $this->Session->read('Shipcost'), $this->Session->read('Shipserv'), $this->Session->read('Payamount'), $this->Session->read('Taxamount'), $this->Session->read('Taxname'), $couponcode, $discamt, 'PayPal Express' , $_GET['token'],'',$giftcardamt);
        exit;
    }

    function paypalexpressfail() {
        $this->Session->setFlash('Payment Failure! <br> Your order can not be processed !<br> Try again!');

        $this->redirect('/index.php');

        exit;
    }

    function delcart($uid) {

        $this->Cart->deleteAll("Cart.user_id = " . $uid, $cascade = true);

        return true;
    }

    function ccard($ship = '') {
        $cnfg   = Configure::read('Neutrino');
        if(trim($_SERVER['HTTP_HOST']) == 'localhost'){             
            include("../phpmailer/class.phpmailer.php");
        }else{            
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        }



        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);



        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {

            $shipp = explode('|~@~|', $ship);

            $shippingMethod = $shipp[0];

            $shippingServ = $shipp[1];

            $shipping_cost = $shipp[2];
        } else {

            $shippingMethod = '';

            $shippingServ = '';

            $shipping_cost = 0;
        }

        //$cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        if (count($citem) < 1) {
            $this->Session->setFlash(__('Your cart is empty.Please add products to the cart.', true));
            $this->redirect(array('controller' => 'carts', 'action' => 'show'));
            exit();
        }

        //$citem    =   $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'giftcard','user_id' => $user_id)));

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }



        $this->set('totaltopay', number_format($tot_price, 2, ".", ""));







        ######################### Section to find and add tax amount.............................

        $taxamt = 0;

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if (strtotime($tdat) >= strtotime($couparray["Coupon"]["from_date"]) && strtotime($tdat) <= strtotime($couparray["Coupon"]["to_date"]) && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    //$discamt  =   $couparray["Coupon"]["giftvalue"];

                    if ($couparray["Coupon"]["giftvalue"] >= $tot_price)
                        $discamt = $tot_price;

                    else
                        $discamt = $couparray["Coupon"]["giftvalue"];
                }else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        ########################## Coupon code section ******************************************       ss
        ######################### End of Section to find and add tax amount......................

        $this->set('taxamnt', $taxamt);

        //$totaltopay =     number_format($tot_price,2,".","");
        //$gtotal       =   number_format(($tot_price + $shipping_cost),2,".","");

        if ($tot_price > 0)
            $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");

        else
            $gtotal = number_format(0.00 + $shipping_cost, 2, ".", "");
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $gtotal = $gtotal-  $giftcardamt;    
             
             $gtotal = number_format($gtotal,2,".","");
            
        }
        
        $giftcarddiscamount = 0;
        if($this->Session->check('GiftCardDiscountAmount') == true) { //echo "GiftCardDiscAmount = ".$this->Session->read('GiftCardDiscountAmount');
            $giftcarddiscamount = $this->Session->read('GiftCardDiscountAmount');
            if($giftcarddiscamount){
                $gtotal = $gtotal - $giftcarddiscamount;
            }
            $this->set('giftcarddiscamount', $giftcarddiscamount);
        }else{
            $this->set('giftcarddiscamount', 0);
        }
        //$this->Session->read('GiftCardDiscAmount',$avail_balance); 

        $paymentMethod = "CC";

        $this->set('taxamnt', $taxamt);

        $this->set('gtotal', $gtotal);

        $this->set('discount', $discamt);

        //$this->set('totaltopay', $totaltopay);

        $this->set('userid', $user_id);

        $this->set('paymentMethod', $paymentMethod);

        $this->set('shipping_cost', $shipping_cost);

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $txtAuthorizeEmail = $cnfg["authorize_email"];

        $txtAuthorizeTestMode = $cnfg["authorize_testmode"];

        $txtAuthorizeLoginId = $cnfg["authorize_loginid"];

        $txtAuthorizeTransKey = $cnfg["authorize_transactionkey"];

        //$txtAuthorizePassword     =   $cnfg["authorize_password"];

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {


            $res = $this->Authorizepayment->authpay($billadd["UserAddress"], $txtEmail, $_POST["txtCCNumber"], $_POST["txtCVV2"], $_POST["txtMM"], $_POST["txtYY"], $txtAuthorizeLoginId, $txtAuthorizeTransKey, $cnfg["currency"], $_POST["cart_total"], $txtAuthorizeEmail, $Company, $user_id, $newinvid, $cnfg["site_name"], $txtAuthorizeTestMode);

           

            if ($res["status"] == 1) {

                //$gtotal                           =   number_format(($totaltopay + $shipping_cost),2,".","");

                $sessPayamt = $gtotal;

                $sessShipmeth = $shippingMethod;

                $sessShipserv = $shippingServ;

                $sessShipcost = $shipping_cost;

                $trans_id = $res["msg"];
                
                if(trim($giftcarddiscamount) <> "" && $giftcarddiscamount > 0){
                   $discamt = $discamt =  $giftcarddiscamount;
                }
                $this->sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $taxamt, $taxname, $couponcode, $discamt, 'Authorize' , $trans_id, $coupon_id,$giftcardamt);

                exit;
            } else {

                $this->Session->setFlash($res["msg"]);

                //$this->redirect('/index.php');
                //exit;
            }
        }
    }

    ################# Offline creditcard payment starts here #################

    function offlinepay($ship = '') {

        $ship = "";
        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        //$lst              =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }

        $cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }



        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
        if($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    
                     $gtotal = $gtotal-  $giftcardamt;  
                     $gtotal = number_format($gtotal, 2, ".", "");
          
                }
        
        
        
        

        $paymentMethod = "Offline Payment";
        
        

        $this->set('totaltopay', $totaltopay);

        $this->set('userid', $user_id);

        $this->set('paymentMethod', $paymentMethod);

        $this->set('shipping_cost', $shipping_cost);

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $txtAuthorizeEmail = $cnfg["authorize_email"];

        $txtAuthorizeTestMode = $cnfg["authorize_testmode"];

        $txtAuthorizeLoginId = $cnfg["authorize_loginid"];

        $txtAuthorizeTransKey = $cnfg["authorize_transactionkey"];

        //$txtAuthorizePassword     =   $cnfg["authorize_password"];

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);



        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            $card_type = $_POST["txtCCType"];

            $card_holder = $_POST["txtCCHolder"];

            $card_number = $_POST["txtCCNumber"];

            $card_validation_code = $_POST["txtCVV2"];

            $card_expiry_date = $_POST["txtMM"] . "-" . $_POST["txtYY"];

            $status = 1;

            if ($status == 1) {

                $gtotal = number_format(($totaltopay + $shipping_cost), 2, ".", "");
                
                 if($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    
                     $gtotal = $gtotal-  $giftcardamt;  
                     $gtotal = number_format($gtotal, 2, ".", "");
          
                }

                $sessPayamt = $gtotal;
                
                $sessShipmeth = $shippingMethod;

                $sessShipserv = $shippingServ;

                $sessShipcost = $shipping_cost;

                //$trans_id                     =   $res["msg"];

                $this->sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $taxamt, $taxname, $couponcode, $discamt, $paymentMethod , $trans_id,'',$giftcardamt);

                exit;
            } else {

                $this->Session->setFlash($res["msg"]);

                //$this->redirect('/index.php');
                //exit;
            }
        }
    }

    ################# Offline payment ends here #################
    ################# Function to place order using Blue pay................................

    function bluepay($ship = '') {
        $ship = "";
        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        //$lst              =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }


        $cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
         if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                     $gtotal = $gtotal-  $giftcardamt; 
                     
                     $gtotal = number_format($gtotal, 2, ".", "");

        }

        $paymentMethod = "CC";

        $this->set('totaltopay', $totaltopay);

        $this->set('userid', $user_id);
        
        $this->set('gtotal', $gtotal);

        $this->set('paymentMethod', $paymentMethod);

        $this->set('shipping_cost', $shipping_cost);

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        #$txtUrPayDemo  =   "YES";

        $bp_testmode = $cnfg["bp_testmode"];
        if ($bp_testmode == "Y") {
            $bp_testmode = "TEST";
        } else {
            $bp_testmode = "LIVE";
        }

        $bp_secret = $cnfg["bp_secret"];

        $bp_account = $cnfg["bp_account"];




        # BILLING INFO 4111111111111111

        $bad = $billadd["UserAddress"];

        $txtEmail = $sus["email"];


        ############################################

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            $cardNumber = urlencode($_POST["txtCCNumber"]);

            $myorder["cardexpmonth"] = $_POST["txtMM"];            


            $expireMonthYear = $_POST["txtMM"] . substr($_POST["txtYY"], -2);
            $cardExpire = $expireMonthYear;
            //echo $cardExpire;exit;
            $myorder["chargetotal"] = urlencode($_POST["cart_total"]);
            /*             * ******* Section to post data into bluepay*********************************** */
            $this->Bluepay->setValue("ACCOUNT_ID", $bp_account);       # Johns account id -> 100036521127
            $this->Bluepay->setValue("SECRET_KEY", $bp_secret);  # Johns Secret key -> ROQYX69Y6CYPXXZ2DRFOCAF.EGCS0CDK
            $this->Bluepay->setValue("TRANS_TYPE", 'SALE');
            $this->Bluepay->setValue("MODE", $bp_testmode);         # Default is TEST --> Set to LIVE for live tx
            $this->Bluepay->setValue("AMOUNT", $_POST["cart_total"]);          # ODD returns Approved, EVEN returns Declined in TEST mode
            $this->Bluepay->setValue("PAYMENT_ACCOUNT", $cardNumber);      # VISA Test Card
            $this->Bluepay->setValue("CARD_EXPIRE", $cardExpire);
            $this->Bluepay->setValue("NAME1", $bad["fname"]);
            $this->Bluepay->setValue("NAME2", $bad["lname"]);
            $this->Bluepay->setValue("PHONE", $bad["phone"]);
            $this->Bluepay->setValue("EMAIL", $sus["email"]);
            $this->Bluepay->setValue("COMPANY_NAME", 'NA');
            $tamperProofSeal = md5($bp_secret . $bp_account . $_POST["cart_total"] . $bp_testmode);
            $this->Bluepay->setValue("TAMPER_PROOF_SEAL", $tamperProofSeal);
            $this->Bluepay->setValue("ADDR1", $bad["address"]);
            $this->Bluepay->setValue("CITY", $bad["city"]);
            $this->Bluepay->setValue("STATE", $bad["state"]);
            $this->Bluepay->setValue("ZIP", $bad["zip"]);
            $this->Bluepay->setValue("COUNTRY", $bad["country"]);
            
           
            $response = $this->Bluepay->bp20post($bp_testmode);

            //echopre($response);

            /*             * ******* Section to post data into bluepay*********************************** */
            /*             * ********** Section to return the result************** */

            $transactionid = $this->Bluepay->getValue("TRANS_ID");
            $status = $this->Bluepay->getValue("STATUS");
            $avs = $this->Bluepay->getValue("AVS");
            $cvv2 = $this->Bluepay->getValue("CVV2");
            $authcode = $this->Bluepay->getValue("AUTH_CODE");
            $message = $this->Bluepay->getValue("MESSAGE");
            $rebid = $this->Bluepay->getValue("REBID");           
           
           //echo $status."<br>".$avs."<br>".$cvv2."<br>".$authcode."<br>".$message."<br>".$rebid;exit();
            /*             * ********** Section to return the result************** */
           
            if ($status == "E") {

                $paymentsuccessful = false;

                $paymenterror = "Error";

                $paymenterror = $message;
            } else {

                if($status==1)
                {
                     $paymentsuccessful = true;

                    $transactionid = $transactionid;
                }

               else { // transaction failed, print the reason
                    $paymentsuccessful = false;

                    $paymenterror = "Error";


                    $paymenterror = $message;
                    ;

                    $this->Session->setFlash($paymenterror);
                    
                    $res["msg"] = $paymenterror;

                    //print "Status: $result[r_approved]\n";
                    //print "Error: $result[r_error]\n";
                } 
            }

            //$paymentsuccessful = true;

            $ship = $this->Session->read('SESS_SHIPMENT');
            //print_r($ship);exit;
            if ($ship <> '') {
                $shipp = explode('|~@~|', $ship);
                $shippingMethod = $shipp[0];
                $shippingServ = $shipp[1];
                $shipping_cost = $shipp[2];
            } else {
                $shippingMethod = '';
                $shippingServ = '';
                $shipping_cost = 0;
            }

            if ($paymentsuccessful == true) {

                $gtotal = number_format(($totaltopay + $shipping_cost), 2, ".", "");
                if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                     $gtotal = $gtotal-  $giftcardamt;    

                }

                

                $sessPayamt = $gtotal;

                $sessShipmeth = $shippingMethod;

                $sessShipserv = $shippingServ;

                $sessShipcost = $shipping_cost;

                $trans_id = 0; //$transactionid;

                $this->sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $taxamt, $taxname, $couponcode, $discamt, 'BluePay' , $trans_id,'',$giftcardamt);
            } else {
                if(trim($res["msg"])==''){
                  $res["msg"] = 'Sorry, the transaction cannot be processed';
                
                    
                }
                $this->Session->setFlash($res["msg"]);

                //$this->redirect('/index.php');
                //exit;
            }
        }
    }

    ################# Function to place order using Blue pay................................
    ################# Function to place order using your pay................................

    function yourpay($ship = '') {

        $ship = "";
        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        //$lst              =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }


        $cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                   $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                     $gtotal = $gtotal-  $giftcardamt;  
                      $gtotal = number_format($gtotal, 2, ".", "");

       }

        $paymentMethod = "CC";

        $this->set('totaltopay', $totaltopay);

        $this->set('userid', $user_id);

        $this->set('paymentMethod', $paymentMethod);

        $this->set('shipping_cost', $shipping_cost);

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        #$txtUrPayDemo  =   "YES";

        $txtUrPayDemo = $cnfg["yourpay_testmod"];

        $txtYourpayStoreId = $cnfg["yourpay_storeid"];

        #$txtYourpayStoreId     = "123" ;

        $pemfolder = $cnfg["yourpay_certificate_file"];

        //$myorder["host"]          = "secure.linkpt.net";

        $myorder["port"] = "1129";

        $myorder["keyfile"] = IMAGES . $pemfolder;

        #$myorder["keyfile"]    = IMAGES."1211447989_1001168167.pem"; # Change this to the name and location of your certificate file

        $myorder["configfile"] = urlencode($txtYourpayStoreId);        # Change this to your store number

        $myorder["ordertype"] = "SALE";

        if ($txtUrPayDemo == "YES") {
            $myorder["host"] = "staging.linkpt.net";
            $myorder["result"] = "GOOD"; # For a test, set result to GOOD, DECLINE, or DUPLICATE
        } else {
            $myorder["host"] = "secure.linkpt.net";
            $myorder["result"] = "LIVE";
        }


        # BILLING INFO 4111111111111111

        $bad = $billadd["UserAddress"];

        $txtEmail = $sus["email"];

        $myorder["name"] = urlencode($bad["fname"]) . " " . urlencode($bad["lname"]);

        $myorder["company"] = "-NA-";

        $myorder["address1"] = urlencode($bad["address"]);

        $myorder["city"] = urlencode($bad["city"]);

        $myorder["state"] = urlencode($bad["state"]);

        $myorder["country"] = urlencode($bad["zip"]);

        $myorder["phone"] = urlencode($bad["country"]);

        $myorder["email"] = urlencode($txtEmail);
        $myorder["addrnum"] = "125";   # Required for AVS. The numeric portion of the street address If not provided, transactions will downgrade.
        //$myorder["debugging"] = "true";  # for development only - not intended for production use
        ############################################

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);

        if ($_SERVER['REQUEST_METHOD'] == 'POST') {

            $myorder["cardnumber"] = urlencode($_POST["txtCCNumber"]);

            $myorder["cardexpmonth"] = $_POST["txtMM"];

            $myorder["cardexpyear"] = $_POST["txtYY"];

            $myorder["chargetotal"] = urlencode($_POST["cart_total"]);

            $result = $this->Yourpay->curl_process($myorder);  # use curl methods
            ///////////////////
            if ($result["r_approved"] != "APPROVED") { // transaction failed, print the reason
                $paymentsuccessful = false;
                $paymenterror = "Error: " . $result["r_error"];
                $this->Session->setFlash($paymenterror);
            } else { // success
                $paymentsuccessful = true;
                $transactionid = $result["r_ordernum"];
            }
            /////////////////

            if ($paymentsuccessful == true) {

                $gtotal = number_format(($totaltopay + $shipping_cost), 2, ".", "");
                
                 if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                     $gtotal = $gtotal-  $giftcardamt;  
                      $gtotal = number_format($gtotal, 2, ".", "");

                }

                $sessPayamt = $gtotal;

                $sessShipmeth = $shippingMethod;

                $sessShipserv = $shippingServ;

                $sessShipcost = $shipping_cost;

                $trans_id = 0; //$transactionid;

                $this->sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $taxamt, $taxname, $couponcode, $discamt, 'YourPay' , $trans_id,'',$giftcardamt);

                exit;
            }

        }
    }

    ############### Function tointegrate world pay.......................

    function worldpay($ship = '') {

        $ship = "";
        $ship = $this->Session->read('SESS_SHIPMENT');


        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        //$lst              =   $this->Catmenu->getCatList(1);
        //$this->set('catmenu', $lst);
        //Code Added By shyam for Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        //Code Added By shyam for Category Menu Listing ends here..

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }


        $cnfg = Configure::read('Neutrino');

        $worldpaytestmode = $cnfg["worldpay_testmode"];

        $Instid = $cnfg["worldpay_inst_Id"];

        $worldpayEmail = $cnfg["worldpay_email"];

        $worldauthmode = $cnfg["worldpay_transact_method"];



        switch ($worldpaytestmode) {

            case "100":

                $worldpayserver = "https://select-test.worldpay.com/wcc/purchase";

                break;



            case "0":

                $worldpayserver = "https://select.worldpay.com/wcc/purchase";

                break;



            default:

                $worldpayserver = "https://select.worldpay.com/wcc/purchase";

                break;
        }

        //$referrer     `           =   $_SERVER["HTTP_REFERER"];

        $shipping_form = "<input type='hidden' name='shipping' value='$shipping_cost'>";

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $umail = $sus["email"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $couparray["Coupon"]["discount"] = $discamt;

            $this->Session->write('Coupon', $couparray);
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $billaddsu = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        $this->Session->write('Taxamount', $taxamt);

        $this->Session->write('Taxname', $taxname);

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");
        
         if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                     $gtotal = $gtotal-  $giftcardamt;  
                      $gtotal = number_format($gtotal, 2, ".", "");

       }

        $this->set('taxamt', $taxamt);

        $this->set('taxname', $taxname);

        $this->set('address', $billaddsu["UserAddress"]);

        $this->set('cartAmount', $totaltopay);

        $this->set('Shipmethod', $shippingMethod);

        $this->set('Shipcost', $shipping_cost);

        $this->set('Shipservice', $shippingServ);

        $this->set('worldpayserver', $worldpayserver);

        $this->set('worldpaytestmode', $worldpaytestmode);

        $this->set('shipping_form', $shipping_form);

        $this->set('shipping_cost', $shipping_cost);

        $this->set('umail', $umail);

        $this->set('user_id', $user_id);

        $this->set('Instid', $Instid);

        $this->set('cnfg', $cnfg);

        $this->Session->write('taxamt', $taxamt);

        $this->Session->write('Payamount', $gtotal);

        $this->Session->write('Instid', $Instid);

        $this->Session->write('umail', $umail);

        $this->Session->write('Shipmethod', $shippingMethod);

        $this->Session->write('Shipcost', $shipping_cost);

        $this->Session->write('Shipservice', $shippingServ);

        $this->Session->write('address', $billadd["UserAddress"]);

        //print_r($cnfg["site_name"]);exit;
    }

    ########### Function to update order after return from world pay.......................

    function worldpayback() {

        if ($_REQUEST["transStatus"] == "Y") {

            $user_id = $_REQUEST["cartId"];

            $usr = $this->User->findById($user_id);

            $cnfg = Configure::read('Neutrino');

            if (!empty($usr["User"]["id"])) {

                $sessPayamt = $_REQUEST["amount"];

                $sessTaxamt = $_REQUEST["MC_taxamt"];

                $sessTaxnam = $_REQUEST["MC_taxname"];

                $sessShipmeth = $_REQUEST["MC_Shipmethod"];

                $sessShipcost = $_REQUEST["MC_Shipcost"];

                ########################## Coupon code section ******************************************

                $discamt = 0;

                $couponcode = '';

                if ($this->Session->check('Coupon') == true) {

                    $couparray = $this->Session->read('Coupon');

                    $order["coupon_id"] = $couparray["Coupon"]["id"];

                    $order["discount"] = $couparray["Coupon"]["discount"];

                    $couponcode = $couparray["Coupon"]["code"];
                }
                
                 if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
                    //$this->set('gift_card_amt', $giftcardamt);
                    // $gtotal = $gtotal-  $giftcardamt;  
                      //$gtotal = number_format($gtotal, 2, ".", "");

                }

                ########################## Coupon code section ******************************************

                $this->sendOrderMail($sessShipmeth, $sessShipcost, $_REQUEST["MC_Shipservice"], $sessPayamt, $sessTaxamt, $sessTaxnam, $couponcode, $discamt, 'WorldPay' , $_REQUEST["transId"],'',$giftcardamt);

                exit;
            } else {

                $this->Session->setFlash('Payment Failure! <br> Your order can not be processed !<br> Try again!');

                $this->redirect('/index.php');

                exit;
            }
        } else {

            $this->Session->setFlash('Payment Failure! <br> Your order can not be processed !<br> Try again!');

            $this->redirect('/index.php');

            exit;
        }
    }

    function CheckValue($Array) {

        foreach ($Array as $key => $val) {

            if ($key == 'mailservice') {

                return (html_entity_decode($val));
            }//end if
        }//end foreach
    }

//end funciton

    function CheckValuePrice($Array) {

        foreach ($Array as $key => $val) {

            if ($key == 'rate') {

                return ($val);
            }//end if
        }//end foreach
    }

//end funciton
    #################### Function for google checkout.........................................

    function googlechk($ship = '') {

        $ship = "";
        $ship = $this->Session->read('SESS_SHIPMENT');
        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        $cnfg = Configure::read('Neutrino');

        if ($ship <> '') {
            $shipp = explode('|~@~|', $ship);
            $shippingMethod = $shipp[0];
            $shippingServ = $shipp[1];
            $shipping_cost = $shipp[2];
        } else {
            $shippingMethod = '';
            $shippingServ = '';
            $shipping_cost = 0;
        }


        $gmerchantId = $cnfg["google_merchantId"]; //"643760143118924";

        $gmerchantkey = $cnfg["google_merchantkey"]; //"jk0ACPM8RdntndpuFbqjew";

        $gtestmode = $cnfg["google_testmode"]; //"YES";

        $currency = $cnfg["currency"];

        if ($gtestmode == "Yes")
            $server_type = "sandbox";
        else
            $server_type = "checkout";

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $umail = $sus["email"];

        $citem = $this->Cart->findAllByUserId($user_id);

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;

        $couparray["Coupon"]["id"] = 0;

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if ($tdat > $couparray["Coupon"]["from"] && $tdat < $couparray["Coupon"]["to"] && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    $discamt = $couparray["Coupon"]["giftvalue"];
                } else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;
        }

        ########################## Coupon code section ******************************************
        ######################### Section to find and add tax amount.............................

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $billaddsu = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        } else {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = '0.00';
        }

        $this->Session->write('Taxamount', $taxamt);

        $this->Session->write('Taxname', $taxname);

        ######################### End of Section to find and add tax amount......................

        $totaltopay = number_format($tot_price, 2, ".", "");

        $gtotal = number_format(($tot_price + $shipping_cost + $taxamt), 2, ".", "");
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
            $gtotal = $gtotal-  $giftcardamt;  
            $gtotal = number_format($gtotal,2,".","");
            
        }

        

        ############################################################################

        $this->Googlecart->GoogleCartch($gmerchantId, $gmerchantkey, $server_type, $currency);

        $total = 0;

        $cartitems = "";

        $price = 0;

        $this->Googleitem->GoogleItemch("Shopping", // Item name
                "Shopping With " . $cnfg["site_name"], // Item description
                1, // Quantity
                $gtotal); // Unit price



        $cart_no = $this->Googleitem;

        $this->Googlecart->AddItem($cart_no);

        //print_r($gtotal);
        // Adding Merchant private Data



       // $order = $user_id . '-***-' . $gtotal . '-***-' . $taxamt . '-***-' . $taxname . '-***-' . $ship . '-***-' . $couparray["Coupon"]["id"] . '-***-' . $discamt;
        $order = $user_id . '*' . $gtotal . '*' . $taxamt . '*' . $taxname . '*' . $shippingMethod . '*' . $shipping_cost .'*'.$shippingServ. '*' . $couparray["Coupon"]["id"] . '*' . $discamt;
         $this->Session->write('orderdata', $order);
        $this->Googlecart->SetMerchantPrivateData($order);

        // continue link page



       // $this->Googlecart->SetContinueShoppingUrl(FULL_BASE_URL . $cnfg["sitebasefolder"] . "/index.php");
        $this->Googlecart->SetContinueShoppingUrl(FULL_BASE_URL . $cnfg["sitebasefolder"] . "/carts/googleback/sucess");



        $this->Googlecart->AddRoundingPolicy("HALF_UP", "PER_LINE");

        // Display Google Checkout button

        $this->set('logo', $this->Googlecart->CheckoutButtonCode("LARGE"));

        $this->set('total', $totaltopay);

        $this->set('taxamt', $taxamt);

        $this->set('shipamt', $shipping_cost);

        $this->set('gtotal', $gtotal);
        
        $curr = $this->Currency->findByCode($currency);

        $this->set('curlogo', $curr["Currency"]["logo"]);
        //echo $this->Googlecart->CheckoutButtonCode("LARGE");
        //exit;
        ############################################################################
    }

    #################### Function for google checkout.........................................
    ##################### Function for google checkout updating...............................

    function googleback($sucess="") {

        // Retrieve the XML sent in the HTTP POST request to the ResponseHandler
       if(isset ($sucess) && $sucess == 'sucess'){

           $order = $this->Session->read('orderdata');
            
            $arr = explode('*', $order);
           
            $user_id = $arr[0];

           $shippingMethod = $arr[4];

           $shipping_cost = $arr[5];

            $shipping_service = $arr[6];

            $sessPayamt = $arr[1];

            $sessTaxamt = $arr[2];

            $sessTaxnam = $arr[3];

            $couponcode = $arr[7];

            $discount = $arr[8];

            ################# Section to place order....................................

            $usr = $this->User->findById($user_id);

            if (!empty($usr["User"]["id"])) {
                 if ($this->Session->check('GiftCardDiscount') == true) {
            
                    $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                    $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                    $giftcardamt = number_format($giftcardamt,2,".","");
            
            
                }

                $this->sendOrderMail($shippingMethod, $shipping_cost, $shipping_service, $sessPayamt, $sessTaxamt, $sessTaxnam, $couponcode, $discount, 'Google Checkout' , 'N.A','',$giftcardamt);
                exit;
            }
        
       }else{

            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;
       }

       /* $xml_response = $GLOBALS['HTTP_RAW_POST_DATA'];
        
        $keyword = preg_match_all("/<merchant-private-data>(.*?)<\/merchant-private-data>/", $xml_response, $matchkeyword);

        //$xml_responsetest=$matchkeyword[1][0];
        //$xml_response =   "1-***-ups-***-firstflight-***-230";

        $cnfg = Configure::read('Neutrino');

        if (get_magic_quotes_gpc()) {

            $xml_response = stripslashes($xml_response);

        }

        if (trim($xml_response) != '') {

            $gc_flag = true;

            $gc_status = 'success';

            $keyword = preg_match_all("/<merchant-private-data>(.*?)<\/merchant-private-data>/", $xml_response, $matchkeyword);

            $str = $matchkeyword[1][0];

            $arr = explode("-***-", $str);

            //print_r($arr);exit;

            $user_id = $arr[0];

            $shippingMethod = $arr[4];

            $shipping_cost = $arr[6];

            $shipping_service = $arr[5];

            $sessPayamt = $arr[1];

            $sessTaxamt = $arr[2];

            $sessTaxnam = $arr[3];

            $couponcode = $arr[7];

            $discount = $arr[8];

            ################# Section to place order....................................

            $usr = $this->User->findById($user_id);

            if (!empty($usr["User"]["id"])) {

                $this->sendOrderMail($shippingMethod, $shipping_cost, $shipping_service, $sessPayamt, $sessTaxamt, $sessTaxnam, $couponcode, $discount, 'Google Checkout' , 'N.A');

            }

            ################# Section to place order....................................
        }*/
    }

    ##################### Function for google checkout updating...............................
    ##################### Ajax Functions for validate Giftcard starts here #####################

    function checkgiftcard($code = '') {

        $this->layout = null;

        $cnfg = Configure::read('Neutrino');

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $this->set('curlogo', $curr["Currency"]["logo"]);

        $valid = '';

        $gdet = $this->GiftcardDetail->find('first', array('conditions' => array('GiftcardDetail.card_code' => $code)));
        if (isset($gdet) && !empty($gdet)) {

            $valid = 'yes';

            $this->set('valid', $valid);

            $this->set('cardet', $gdet);
            
        } else {

            $valid = 'no';

            $this->set('valid', $valid);
            $this->Session->delete('GiftCardDiscount');
            $this->Session->delete('Gstatus');
           
           
        }
    }

    function setgiftcard($code = '', $amnt = '') {

        $this->layout = null;

        $cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $gdet = $this->GiftcardDetail->find('first', array('conditions' => array('GiftcardDetail.card_code' => $code)));

        if (isset($gdet) && !empty($gdet)) {

            $gdet["GiftcardDetail"]["entered_amnt"] = $amnt;

            $this->Session->write('Giftcard', $gdet);

            $this->set('cardet', $gdet);
        } else {
            return false;
        }
    }

    function cleargiftsession() {

        $this->layout = null;

        $this->Session->delete('Giftcard');
         $this->Session->delete('GiftCardDiscount');
    }

    ##################### Ajax Function for validate Giftcard ens here#####################

    function sendMailReorderAlert($prd_id) {
        $cnfg = Configure::read('Neutrino');
        
        if(trim($_SERVER['HTTP_HOST']) == 'localhost'){ 
            include_once("../phpmailer/class.phpmailer.php");
        }else{
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        }

        global $currency;
        $curr       =   $this->Currency->findByCode($currency);

        $product_details = $this->Product->findById($prd_id);
        $prd_name = $product_details['Product']['pname'];
        $prd_desc = $product_details['Product']['descr'];
        $prd_retPrice = $product_details['Product']['price'];
        $prd_wholePrice = $product_details['Product']['wholesale_price'];
        $prd_stock = $product_details['Product']['stock'];
        $prd_reorder = $product_details['Product']['reorderlevel'];

        $pdt1 = $this->Cmspage->findByTitle('Admin order confirm mail');

        $headers = "From: " . $cnfg["site_name"] . "<" . $cnfg["admin_email"] . ">\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

        $mailcontent1 = "<p>&nbsp;</p>
                         <p>Dear Administrator,</p>
                         <p>&nbsp;&nbsp;&nbsp;&nbsp; The stock of Product : " . $prd_name . " is running low.</p>";

        $mailcontent1 = "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='left'>

      <tr>

        <td colspan='2' align='left'>

        <p>Dear Administrator,</p>

                The stock of Product : <b>" . $prd_name . "</b> is running low.</br>.
                <br> <b>Product Details :</b><br>
                Product Name &nbsp; : &nbsp; "  . $prd_name . "<br>
                Product Description &nbsp; : &nbsp; "  . $prd_desc . "<br>
                Product Retail Price &nbsp; : &nbsp; "  .$curr["Currency"]["logo"].' '. $prd_retPrice . "<br>
                Product Wholesale Price &nbsp; : &nbsp; "  .$curr["Currency"]["logo"].' '. $prd_wholePrice . "<br>
                Product Stock &nbsp; : &nbsp; "  . $prd_stock . "<br>
                Product Re-Order Level &nbsp; : &nbsp; "  . $prd_reorder . "<br>

        </td>

      </tr>
          <tr>
          <td> Thanks and Regards,<br>
          " . $cnfg["site_name"] . "
          </td></tr>
          </table>";

        $path       =   "SiteLogo_disp.gif";

        $mcont      =   "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>

              <tr><td><a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'><img src='".FULL_BASE_URL. $cnfg["sitebasefolder"]."/app/webroot/".IMAGES_URL.$path."' border='0'></a></td></tr></table>";

        //$cnfg["site_name"]    =   "<a href='".FULL_BASE_URL. $cnfg["sitebasefolder"]."' target='_blank'>".$cnfg["site_name"]."</a>";

       
        $mailcontent12 = $mcont.$mailcontent1;


              
        //echo $mailcontent12.'subject'.'Product Stock Alert - ' . $cnfg["site_name"];exit;
        //mail($cnfg["admin_email"], 'Product Stock Alert - ' . $cnfg["site_name"], $mailcontent12, $headers);
        
        /*#################################### EMAIL SEGMENT ###############################*/
        $site_name      = "";           
        $admin_email    = "";
        $subject        = "";
        if(trim($cnfg["site_name"]) <> ""){
            $site_name  = trim($cnfg["site_name"]);
            $subject    = 'Notification On Product Stock - '.trim($site_name);
        }else{
            $site_name = $cnfg["smtp_user"];
            $subject    = 'Notification On Product Stock';
        }                    
        if(trim($cnfg["admin_email"]) <> ""){
            $admin_email = trim($cnfg["admin_email"]);
        }else{
            $admin_email = $cnfg["smtp_user"];
        }



        /******************************* MAIL TO THE ADMINISTRATOR ****************************/
        $mail             = new PHPMailer(true);                
        $body             = trim($mailcontent12);
        //$body           = eregi_replace("[\]",'',$body);
        $mail->IsSMTP(); 
        $mail->SMTPSecure = 'tls';
        //$mail->SMTPDebug  = 2;                    
        $mail->SMTPAuth   = true;  

                    $mail->Host       = $cnfg["smtp_host"]; 
                    $mail->Port       = $cnfg["smtp_port"];   
                    $mail->Username   = $cnfg["smtp_user"];
                    $mail->Password   = $cnfg["smtp_password"];       
        $mail->SetFrom($admin_email,$site_name);
        $mail->AddReplyTo($admin_email,$site_name);
        $mail->Subject    = $subject;
        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
        $mail->MsgHTML($body);                    
        $mail->AddAddress($admin_email, "Administrator - ".trim($site_name)); 
        $mail->Send();
        /******************************* MAIL TO THE ADMINISTRATOR ****************************/    
        
        /*#################################### EMAIL SEGMENT ###############################*/
       //  echo "<br>Admin email---".$admin_email;

        Configure::write('debug', 0);
        $this->autoRender = false;
    }


    /*---------------------------Generic function to send order confirmation mail----------------------------*/
    function sendOrderMail($sessShipmeth, $sessShipcost, $sessShipserv, $sessPayamt, $sessTaxamt, $sessTaxnam, $couponcode = '', $discount = '', $paymentMode = 'N.A', $transID = 'N.A',$couon_id='',$gift_card_discount='') {
        $cnfg = Configure::read('Neutrino');


                        
        if (trim($_SERVER['HTTP_HOST']) == 'localhost'){             
            include_once("../phpmailer/class.phpmailer.php");
        }else{           
            include_once($_SERVER["DOCUMENT_ROOT"].$cnfg["sitebasefolder"]."/app/phpmailer/class.phpmailer.php");
        }

        

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $shipadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Shipping'");

        $cntdet = $this->Country->findByCountryIsoCode_2($shipadd["UserAddress"]["country"]);

        $shipadd["UserAddress"]["country_name"] = $cntdet["Country"]["country_name"];

        $citem = $this->Cart->findAllByUserId($user_id);
        
        $prodtype = "Non-Digital";
        $discamt = number_format(0, 2, '.', '');

        if (!empty($citem)) {

            foreach ($citem as $it) {

                if (trim($it["Cart"]["prodtype"]) == "Digital") {

                    $prodtype = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prodtype = "Digital";
                }
            }
        }

        $order["date"] = date("Y-m-d H:i:s");

        $order["user_id"] = $user_id;

        if ($prodtype == "Digital") {

            $order["shipping_method"] = "Not Applicable";

            $tm = time() + $cnfg["digitalproduct_download_limit"] * 60 * 60;

            $exptm = date("Y-m-d H:i:s", $tm);

            $order["exp_time"] = $exptm;
        } else {

            $order["shipping_method"] = $sessShipmeth;
        }

        $sessShipmeth = str_replace("%20", " ", $sessShipmeth);

        $order["shipping_service"] = $sessShipserv;

        $order["shipping_price"] = $sessShipcost;

        $order["tax_price"] = $sessTaxamt;

        $order["tax_name"] = $sessTaxnam;

        $order["total_price"] = $sessPayamt;
        
         $order["discount"] = $discount;

        $order["order_status_id"] = 1;

        if ($prodtype <> "Digital") {

            $order["ship_fname"] = $shipadd["UserAddress"]["fname"];

            $order["ship_lname"] = $shipadd["UserAddress"]["lname"];

            $order["ship_address"] = $shipadd["UserAddress"]["address"];

            $order["ship_city"] = $shipadd["UserAddress"]["city"];

            $order["ship_state"] = $shipadd["UserAddress"]["state"];

            $order["ship_country"] = $shipadd["UserAddress"]["country_name"];

            $order["ship_zip"] = $shipadd["UserAddress"]["zip"];

            $order["ship_phone"] = $shipadd["UserAddress"]["phone"];

            $order["ship_mobile"] = $shipadd["UserAddress"]["mobile"];

            $order["ship_fax"] = $shipadd["UserAddress"]["fax"];
        }

        $order["transaction_id"] = $transID;

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $bcntdet = $this->Country->findByCountryIsoCode_2($billadd["UserAddress"]["country"]);

        $billadd["UserAddress"]["country_name"] = $bcntdet["Country"]["country_name"];

        $order["bill_fname"] = $billadd["UserAddress"]["fname"];

        $order["bill_lname"] = $billadd["UserAddress"]["lname"];

        $order["bill_address"] = $billadd["UserAddress"]["address"];

        $order["bill_city"] = $billadd["UserAddress"]["city"];

        $order["bill_state"] = $billadd["UserAddress"]["state"];

        $order["bill_country"] = $billadd["UserAddress"]["country_name"];

        $order["bill_zip"] = $billadd["UserAddress"]["zip"];

        $order["bill_phone"] = $billadd["UserAddress"]["phone"];

        $order["bill_mobile"] = $billadd["UserAddress"]["mobile"];

        $order["bill_fax"] = $billadd["UserAddress"]["fax"];

        $order["payment_method"] = $paymentMode;

        $order["currency_type"] = $cnfg["currency"];
        
        if($couponcode!=''){
            if($couponcode['coupon_id']!=''){
             //$order["coupon_id"] = $couponcode['coupon_id'];
            }
        }
        
         if ($this->Session->check('Coupon') == true) {
                $couparray = $this->Session->read('Coupon');

                $order["coupon_id"] = $couparray["Coupon"]["id"];
         }
         
         if (isset($gift_card_discount) && $gift_card_discount>0) {
            
          
            $order["gift_card_discount"] = $gift_card_discount;
             
            
        }
      //print '<pre />';print_r($order);exit;
        
        $this->Order->save($order);
       
        $order_id = $this->Order->id;




        foreach ($citem as $item) {

            $this->OrderDetail->create($odet = array());



            $odet["order_id"] = $order_id;

            $odet["product_id"] = $item["Cart"]["product_id"];

            $odet["product_price"] = $item["Cart"]["product_price"];

            $odet["prodtype"] = $item["Cart"]["prodtype"];

            $odet["discount_type"] = $item["Cart"]["discount_type"];

            $odet["discount"] = $item["Cart"]["discount"];

            $odet["extra_price"] = $item["Cart"]["extra_price"];

            $odet["quantity"] = $item["Cart"]["quantity"];

            if ($item["Cart"]["option_id"] > 0 && $item["Cart"]["type"] <> 'G') {

                $odet["combination_id"] = $item["Cart"]["option_id"];
            }

            $odet["type"] = $item["Cart"]["type"];

            $odet["price_type"] = $item["Cart"]["price_type"];

          

            $this->OrderDetail->save($odet);

            

            ######## ( Code Added by Shyam) ########

            if ($item["Cart"]["option_id"] > 0 && $item["Cart"]["type"] <> 'G') {

                $this->Product->updatecombnstock($item["Cart"]["product_id"], $item["Cart"]["option_id"], $item["Cart"]["quantity"]);

                $prodid[] = $item["Cart"]["product_id"];
            } else if ($item["Cart"]["option_id"] == 0 || $item["Cart"]["option_id"] == '' && $item["Cart"]["type"] <> 'G') {

                $this->Product->updatestock($item["Cart"]["product_id"], $item["Cart"]["quantity"]);
            }



            //check if reorder level has been breached
            $reorder_breached = $this->Product->threshold_breached($item["Cart"]["product_id"]);

            
        //echo $reorder_breached;exit;
            if ($reorder_breached<>0) {

                

                $this->sendMailReorderAlert($item["Cart"]["product_id"]);
            }

            

            if ($item["Cart"]["type"] == 'G') {
                
                $this->Giftcard->updateCardStock($item["Cart"]["product_id"], $item["Cart"]["quantity"]);
                
            }

            ######## ( Code Added by Shyam) ########
        }



        
        //Storing the Gift card transaction details
        if($paymentMode == 'Gift Card') {
        

                $this->Giftcarduser->create($gusrdet = array());

                $gusrdet["user_id"]         =   $user_id;

                $gusrdet["order_id"]        =   $order_id;

                $gusrdet["card_id"]         =   $this->card_id;

                $gusrdet["usercard_id"]     =   $this->usercard_id;

                $gusrdet["date"]            =   date("Y-m-d");

                $gusrdet["amnt_used"]       =   $this->amnt_used;

               

                $this->Giftcarduser->save($gusrdet);

                
        }
        //Storing the Gift card transaction details
        
        //Generating unique code for Giftcards


        

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        $currlogo = $curr["Currency"]["logo"];

        $gftbl = $this->Cart->getTableName("giftcards");

        $gftbl = str_replace('`', '', $gftbl);

        //$rntbl=$this->Cart->getTableName("randoms");

        $giftcards = array();

        foreach ($citem as $item) {

            $card_price = 0;

            if ($item["Cart"]["type"] == 'G') {

                $card_qty = $item["Cart"]["quantity"];

                for ($i = 0; $i < $card_qty; $i++) {

                    $card_id = $item["Cart"]["product_id"];

                    $card_price = $item["Cart"]["product_price"];

                    $gcardet = $this->Giftcard->query("select gift_code from " . $gftbl . " where id='" . $card_id . "'");

                    $card_name = $gcardet[0][$gftbl]["gift_code"];

                    $newid = $this->Giftcard->generateCardid();

                    $this->GiftcardDetail->create($gdet = array());

                    $gdet["user_id"] = $user_id;

                    $gdet["order_id"] = $order_id;

                    $gdet["card_id"] = $card_id;

                    $gdet["card_code"] = $newid;

                    $gdet["amount"] = $card_price;

                    $gdet["balance"] = $card_price;

                    $giftcards[] = "<b>GIFT CARD NAME :</b>" . $card_name . "<br /><b>GIFT CARD CODE :</b>" . $newid . "<br /><b>GIFT AMOUNT :</b>" . $currlogo . $card_price;
                    $this->GiftcardDetail->save($gdet);
                }
            }
        }

        //Generating unique code for Giftcards

        if (!empty($prodid)) {

            $prodid = array_unique($prodid);

            foreach ($prodid as $val) {
                $this->Product->updateTotalStock($val);
            }
        }

        $this->delcart($user_id);

        ################################## Section to send order confirmation mail................................

         $this->Order->id = $order_id;

        $data = $this->Order->read();




        //print '<pre />';print_r($data);
         $cmbtype_flag='no';
        if(count($data["OrderDetail"])>0) {
            foreach($data["OrderDetail"] as $det) {
             //print '<pre />';print_r($det["Product"]);exit;
                if($det["OrderDetail"]["combination_id"] <> '0')
                    $cmbtype_flag='yes';
            }
        }
       // echo $cmbtype_flag;exit;

        for ($j = 0; $j < sizeof($data["OrderDetail"]); $j++) {

            if ($data["OrderDetail"][$j]["type"] == 'P') {

                $pdet = $this->Product->findById($data["OrderDetail"][$j]["product_id"]);

                $data["OrderDetail"][$j]["Product"] = $pdet["Product"]["pname"];
            } else if ($data["OrderDetail"][$j]["type"] == 'G') {

                $gdet = $this->Giftcard->findById($data["OrderDetail"][$j]["product_id"]);

                $data["OrderDetail"][$j]["Product"] = $gdet["Giftcard"]["gift_code"] . '(Gift Card)';

                $data["OrderDetail"][$j]["product_price"] = $gdet["Giftcard"]["gift_amnt"];
            }
            
             $data["OrderDetail"][$j]["combinations"]= '--';
           
            if($data["OrderDetail"][$j]["type"]=='P') {
                if($data["OrderDetail"]["combination_id"]!='0') {

                    $pcombndet  =   $this->Productdetail->findById($data["OrderDetail"][$j]["combination_id"]);

                    $pcmbnid=explode(',',$pcombndet["Productdetail"]["customvalue_id"]);

                    foreach($pcmbnid as $key => $val) {

                        if($val!='') {

                            $combnstr[]=$this->Product->getpdctcmbn($val);

                            $combinations=implode(" ,",$combnstr);

                            $data["OrderDetail"][$j]["combinations"]= $combinations;

                        }

                    }

                    $data["OrderDetail"][$j]["skuno"]= $pcombndet["Productdetail"]["skuno"];

                    unset($combnstr);
                    unset($combinations);

                }
                   
                
            }
            //Fetching the  product combination details
        }
        
        //echo $combinations;exit;

       // print '<pre />';print_r($data["OrderDetail"]);
        $shipadd = $this->UserAddress->findAll("UserAddress.user_id=" . $data["User"]["id"] . " AND UserAddress.addr_type='Shipping'");

        $billadd = $this->UserAddress->findAll("UserAddress.user_id=" . $data["User"]["id"] . " AND UserAddress.addr_type='Billing'");

        $odr = $data;

        if ($prodtype <> "Digital") {

            $ship = $shipadd[0]["UserAddress"];
        }

        $bill = $billadd[0]["UserAddress"];
        //print_r($data["OrderDetail"]);exit;
        $content = "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>

      <tr>

        <td colspan='2' align='center'>

        <h2>Order Details</h2>

        </td>

      </tr>

      <tr>

        <td colspan='2' align='center'>

            <table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

             <tr>

                <td><strong>Order Number</strong></td>

                <td><strong>Order Status</strong></td>

                <td><strong>Order Date</strong></td>

                <td><strong>User Name</strong></td>

                <td><strong>Currency</strong></td>

              </tr>

              <tr>

                <td>&nbsp;</td>

                <td>&nbsp;</td>

                <td>&nbsp;</td>

                <td>&nbsp;</td>

                <td>&nbsp;</td>

              </tr>

              <tr>

                <td> " . $order_id . "</td>
                <td>" .
                $odr['OrderStatus']['name'] . "

                </td>

                <td>";


        $dt = strtotime($odr['Order']['date']);

        $edt = strtotime($odr['Order']['exp_time']);

        $content .= date('m-d-Y', $dt);

        $content .= "</td>

                <td> " . $odr['User']['uname'] . "</td>

                <td>" . $odr["Order"]["currency_type"] . "</td>

              </tr>

            </table>

        </td>

      </tr>

      <tr>

        <td colspan='2' align='center'><h3>Item Details</h3></td>



      </tr>

      <tr>

        <td colspan='2'><table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

      <tr>

        <td colspan='2'><strong>Product Name</strong></td>";
                if($cmbtype_flag == 'yes') { 
                    $content .= "<td><strong>Combination</strong></td>";       
                }
    $content .= "<td><strong>Quantity</strong></td>

        <td><strong>Unit Price</strong></td>

        <td><strong>Extra Price</strong></td>

        <td><strong>Discount</strong></td>

        <td><strong>Price</strong></td>";

        if ($data["OrderDetail"]["0"]["prodtype"] == "Digital") {
            $content .= "<td><strong>Expiry Date</strong></td>

        <td><strong>Download</strong></td>";
        } else {
            $content .= "<td><strong></strong></td>

        <td><strong></strong></td>";
        }

        $content .= "</tr>

      <tr>

        <td colspan='3'>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>";



        $amt = 0;

        //print_r($odr);exit;

        foreach ($odr['OrderDetail'] as $det) {
          // print '<pre />';print_r($det);
            
            $price = 0;

            $combined_price = 0;

            $dis_amnt = 0;

            if ($det["discount_type"] == 'per' && $det["discount"] > 0)
                $dis_amnt = (($det["product_price"] + $det["extra_price"]) * $det["discount"]) / 100;

            else if ($det["discount_type"] == 'amnt' && $det["discount"] > 0)
                $dis_amnt = $det["discount"];

            $dis_amnt = ($dis_amnt) * ($det["quantity"]);

            $dis_amnt = number_format($dis_amnt, 2, '.', '');



            $combined_price = ($det["product_price"] + $det["extra_price"]);

            if (isset($det["discount_type"]) && $det["discount_type"] <> '') {

                if ($det["discount_type"] == 'per') {

                    if (isset($det["discount"]) && $det["discount"] <> '' && $det["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $det['discount']) / 100));

                        $price = ($discounted_price) * ($det['quantity']);

                        $amt+= $price;
                    }

                    else
                        $amt+= ( $combined_price) * ($det['quantity']);
                }

                else if ($det["discount_type"] == 'amnt') {

                    if (isset($det["discount"]) && $det["discount"] <> '' && $det["discount"] > 0) {

                        $discounted_price = ($combined_price - $det['discount']);

                        $price = ($discounted_price) * ($det['quantity']);

                        $amt+= $price;
                    }

                    else
                        $amt+= ( $combined_price) * ($det['quantity']);
                }
            }

            else {

                $price = ($combined_price) * ($det['quantity']);

                $amt+= $price;
            }

            $price = number_format($price, 2, ".", "");

            $amt = number_format($amt, 2, ".", "");



            if (trim($det['prodtype']) == "Digital") {

                $content .= " <tr>

            <td colspan='2'>" . $det['Product'] . "</td>";
                   
          if($cmbtype_flag == 'yes') { 
                    $content .= "<td>".$det["combinations"]."</td>";       
                  }

        $content .= "<td> " . $det['quantity'] . " </td>

            <td> " . $det['product_price'] . " </td>

            <td> " . $det['extra_price'] . " </td>

            <td> " . $dis_amnt . " </td>

            <td>" . $price . " </td>";



                if (trim($det['type']) <> 'G') {

                    $content .= " <td>" . date('m-d-Y', $edt) . "</td>

             <td><a href='" . FULL_BASE_URL . $cnfg["sitebasefolder"] . "/Orders/pdctdownload/" . $det['order_id'] . "/" . $det['product_id'] . "/' target='_blank'>Download Now</a></td>";
                } else {

                    $content .= " <td>N/A</td>

             <td>N/A</td>";
                }

                $content .= "</tr>

          <tr>

            <td colspan='3' height='15'>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

          </tr>";
            } else {
              
                $content .= " <tr>

            <td colspan='2'>" . $det['Product'] . "</td>";
                  if($cmbtype_flag == 'yes') { 
                    $content .= "<td>".$det["combinations"]."</td>";       
                  }

         $content .="<td> " . $det['quantity'] . " </td>

            <td> " . $det['product_price'] . " </td>

            <td> " . $det['extra_price'] . " </td>

            <td> " . $dis_amnt . " </td>

            <td>" . $price . " </td>

            <td></td>

            <td></td>

          </tr>

          <tr>

            <td colspan='3' height='15'>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

            <td>&nbsp;</td>

          </tr>";
            }
        }



        if ($odr["Order"]["discount"] > 0)
            $discamt = number_format($odr["Order"]["discount"], 2, '.', '');

        // else
        // $discamt=number_format($odr["Order"]["discount"],2,'.','');

        $content .= "</table>

    </td>

      </tr>

      <tr>

        <td width='50%'>";

        if ($det['prodtype'] <> "Digital") {

            $content .="<table width='100%'border='0' cellpadding='0' cellspacing='0'>

        <tr><td>

        <table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

              <tr>

                <td width='50%'><strong>Shipping Method</strong></td>

                <td  width='5%'>:</td>

                <td width='45%'>" . $odr['Order']['shipping_method'] . "</td>

              </tr>

              <tr>

                <td><strong>Shipping Service</strong></td>

                <td>:</td>

                <td>" . $odr['Order']['shipping_service'] . " </td>

              </tr>

            </table>

        </td></tr>

        <tr><td>

        <table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

              <tr>

                <td width='50%'><strong>Payment Method</strong></td>

                <td width='5%'>:</td>

                <td width='45%'> " . $odr['Order']['payment_method'] . "</td>

              </tr>";
            if($odr['Order']['transaction_id'] != 0 && $odr['Order']['transaction_id'] != ''){

        $content .=   "<tr>

                <td><strong>Transaction Id</strong></td>

                <td>:</td>

                <td> " . $odr['Order']['transaction_id'] . " </td>

              </tr>";
            }

        $content .= "</table>

        </td></tr>

        </table>";
        }



        $content .="</td>

        <td width='50%'><table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

              <tr>

                <td><strong>Total Price</strong></td>

                <td>:</td>

                <td>" . $amt . "</td>

              </tr>

              <tr>

                <td><strong>Tax Name</strong></td>

                <td>:</td>

                <td> " . $odr['Order']['tax_name'] . "</td>

              </tr>

               <tr>

                <td><strong>Tax</strong></td>

                <td>:</td>

                <td> " . $odr['Order']['tax_price'] . "</td>

              </tr>

               <tr>

                <td><strong>Gift Card/Promocode Discount </strong></td>

                <td>:</td>

                <td> " . $discamt . " </td>

              </tr>";
        if($gift_card_discount>0){
           $content .="<tr>

                <td><strong>Gift Card Discount </strong></td>

                <td>:</td>

                <td> " . $gift_card_discount . " </td>

              </tr>";
        }


        if ($det['prodtype'] <> "Digital") {

            $content .="<tr>

                <td><strong>Shipping</strong></td>

                <td>:</td>

                <td> " . $odr['Order']['shipping_price'] . " </td>

              </tr>";
        }

        /* Specials */
        //specials
        $specialsArr = array();

        if(isset($odr['Order']['specials'])) {
            if(!empty($odr['Order']['specials'])) {

                $specialsArr = json_decode($odr['Order']['specials']);
                if(!empty($specialsArr)) {
                    foreach($specialsArr as $specials) {

                        $content .="<tr>
                 <td>".$specials->note."</td>
                     <td>:</td>
                 <td>".number_format($specials->cost,2,'.','')."</td>
               </tr>";

                    }
                } // End If
            }
        } // End If

        /* End Specials */

        $content .="

               <tr>

                <td><strong>Grand Total</strong></td>

                <td>:</td>

                <td><b> " . $odr['Order']['total_price'] . " </b></td>

              </tr>

            </table></td>

      </tr>

       <tr height='15'>

        <td colspan='2' align='center'>&nbsp;

        </td>

      </tr>

      <tr>

      <td>";



        if ($det['prodtype'] <> "Digital") {

            $content .="<table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

      <tr>

        <td><h3>Shipping Address</h3></td>

      </tr>

      <tr>

        <td> " . $odr['Order']['ship_fname'] . "&nbsp;&nbsp;  " . $odr['Order']['ship_lname'] . " </td>

      </tr>

      <tr>

        <td> " . $odr['Order']['ship_address'] . " </td>

      </tr>

      <tr>

        <td> " . $odr['Order']['ship_city'] . "&nbsp;&nbsp;&nbsp;" . $odr['Order']['ship_state'] . "&nbsp;&nbsp;&nbsp;" . $odr['Order']['ship_zip'] . " </td>

      </tr>

      <tr>

        <td> " . $odr['Order']['ship_country'] . " </td>

      </tr>

      <tr>

        <td>Phone &nbsp; : &nbsp; " . $odr['Order']['ship_phone'] . " </td>

      </tr>

      <tr>

        <td>Mobile &nbsp; : &nbsp;" . $odr['Order']['ship_mobile'] . "</td>

      </tr>

      <tr>

        <td>Fax &nbsp; : &nbsp; " . $odr['Order']['ship_fax'] . " </td>

      </tr>

      <tr>

        <td>&nbsp;</td>

      </tr>

    </table>";
        }



        $content .=" </td>

       <td><table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

      <tr>

        <td><h3> Billing Address</h3></td>

      </tr>

      <tr>

        <td> " . $odr['Order']['bill_fname'] . "&nbsp;&nbsp; " . $odr['Order']['bill_lname'] . " </td>

      </tr>

      <tr>

        <td> " . $odr['Order']['bill_address'] . "</td>

      </tr>

      <tr>

        <td>" . $odr['Order']['bill_city'] . "&nbsp;&nbsp;&nbsp;" . $odr['Order']['bill_state'] . "&nbsp;&nbsp;&nbsp;" . $odr['Order']['bill_zip'] . "</td>

      </tr>

      <tr>

        <td>" . $odr['Order']['bill_country'] . " </td>

      </tr>

      <tr>



        <td>Phone &nbsp; : &nbsp; " . $odr['Order']['bill_phone'] . "</td>

      </tr>

      <tr>

        <td>Mobile &nbsp; : &nbsp; " . $odr['Order']['bill_mobile'] . " </td>

      </tr>

      <tr>

        <td>Fax &nbsp; : &nbsp; " . $odr['Order']['bill_fax'] . "</td>

      </tr>

      <tr>

        <td>&nbsp;</td>

      </tr>

    </table></td>

      </tr>";

        if (isset($giftcards) && empty($giftcards) === false) {

            $content .="<tr>

      <td>

          <table width='90%' border='0' cellpadding='0' cellspacing='0' class='manage_table' align='center'>

          <tr>

            <td><h3>Gift Card Details </h3></td>

          </tr>";

            foreach ($giftcards as $val) {

                $content .="<tr>

            <td> " . $val . " </td>

          </tr>

          <tr>

            <td>&nbsp;</td>

          </tr>";
            }
        }

        $content .="<tr>

            <td>&nbsp;</td>

          </tr>

        </table>

      </td>

       <td>&nbsp;</td>

      </tr>

    </table>";



        $cnfg = Configure::read('Neutrino');



        $subject = "Order placed at " . $cnfg["site_name"];

        $headers = "From: " . $cnfg["site_name"] . "<" . $cnfg["admin_email"] . ">\r\n";

        $headers .= "MIME-Version: 1.0\r\n";

        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

        $pdt = $this->Cmspage->findByTitle('Order confirm mail');

        $path = "SiteLogo_disp.gif";

        $mcont = "<table width='90%'  border='0' cellspacing='2' cellpadding='2' align='center'>

          <tr><td><a href='" . FULL_BASE_URL . $cnfg["sitebasefolder"] . "' target='_blank'><img src='" . FULL_BASE_URL . $cnfg["sitebasefolder"] . "/app/webroot/" . IMAGES_URL . $path . "' border='0'></a></td></tr></table>";

        //$cnfg["site_name"] = "<a href='" . FULL_BASE_URL . $cnfg["sitebasefolder"] . "' target='_blank'>" . $cnfg["site_name"] . "</a>";

        //Mail for User

        $pdt = $this->Cmspage->findByTitle('Order confirm mail');

        $mailcontent = $mcont . $pdt["Cmspage"]["content"];

        $mailcontent = str_replace("[ORDER_DETAILS]", $content, $mailcontent);

        $mailcontent = str_replace("[User_Name]", $odr['User']['uname'], $mailcontent);

        $mailcontent = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent);

        //$mailsent = mail($odr['User']['email'], $subject, $mailcontent, $headers);

       //echo $mailcontent.'User'.$cmbtype_flag.'<br />';

        //Mail for Admin

        $pdt1 = $this->Cmspage->findByTitle('Admin order confirm mail');

        $mailcontent1 = $mcont . $pdt1["Cmspage"]["content"];

        $mailcontent1 = str_replace("[ORDER_DETAILS]", $content, $mailcontent1);

        $mailcontent1 = str_replace("[User_Name]", $odr['User']['uname'], $mailcontent1);

        $mailcontent1 = str_replace("[SITE_NAME]", $cnfg["site_name"], $mailcontent1);

        //$mailsent1 = mail($cnfg["admin_email"], $subject, $mailcontent1, $headers);

       

        /*#################################### EMAIL SEGMENT ###############################*/
        $site_name      = "";        
        $admin_email    = "";
        
        if(trim($cnfg["site_name"]) <> ""){
            $site_name = trim($cnfg["site_name"]);
        }else{
            $site_name = $cnfg["smtp_user"];
        }    
        if(trim($cnfg["admin_email"]) <> ""){
            $admin_email = trim($cnfg["admin_email"]);
        }else{
            $admin_email = $cnfg["smtp_user"];
        }
                    
        /******************************* MAIL TO THE USER ****************************/
        $mail             = new PHPMailer(true);                
        $body             = trim($mailcontent);
        //$body           = eregi_replace("[\]",'',$body);
        $mail->IsSMTP(); 
        $mail->SMTPSecure = 'tls';
        //$mail->SMTPDebug  = 2;                    
        $mail->SMTPAuth   = true;  
                    
        $mail->Host       = $cnfg["smtp_host"]; 
        $mail->Port       = $cnfg["smtp_port"];   
        $mail->Username   = $cnfg["smtp_user"];
        $mail->Password   = $cnfg["smtp_password"];      
        $mail->SetFrom($admin_email, $site_name);
        $mail->AddReplyTo($admin_email, $site_name);
        $mail->Subject    = $subject;
        $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
        $mail->MsgHTML($body);                    
        $mail->AddAddress($odr['User']['email'], ""); 
        $mail->Send();
        /******************************* MAIL TO THE USER ****************************/ 
        
        /************************** MAIL TO THE ADMINISTRATOR ************************/
        $admin_mail       = new PHPMailer(true);                
        $body             = trim($mailcontent1);
        //$body           = eregi_replace("[\]",'',$body);
        $admin_mail->IsSMTP(); 
        $admin_mail->SMTPSecure = 'tls';
        //$mail->SMTPDebug  = 2;                    
        $admin_mail->SMTPAuth   = true;  

        $admin_mail->Host       = $cnfg["smtp_host"]; 
        $admin_mail->Port       = $cnfg["smtp_port"];                 
        $admin_mail->Username   = $cnfg["smtp_user"]; 
        $admin_mail->Password   = $cnfg["smtp_password"];       
        $admin_mail->SetFrom($cnfg["admin_email"], $site_name);
        $admin_mail->Subject    = $subject;
        $admin_mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
        $admin_mail->MsgHTML($body);                    
        $admin_mail->AddAddress($cnfg["admin_email"], "Administrator"); 
        $admin_mail->Send();
        /************************** MAIL TO THE ADMINISTRATOR ************************/
        
        ################################### Sending Fax to Admin ###################################

        
        $cnfg = Configure::read('Neutrino');

        $fax_allow = $cnfg["allow_fax"];

        if ($fax_allow == 'Y' &&  $cnfg["fax_email"]!='') {

            $fax_email = $cnfg["fax_email"];

            $fax_number = $cnfg["fax_number"];

            $fax_content = $content;

            $fax_content = str_replace("[User_Name]", $odr['User']['uname'], $fax_content);

            $fax_content = str_replace("[SITE_NAME]", $cnfg["site_name"], $fax_content);

            $this->_sendFax($fax_email, $fax_number, $fax_content, 1);
        }
        
         if ($this->Session->check('GiftCardDiscount') == true) {
            
             $giftcardamtdetails =   $this->Session->read('GiftCardDiscount');
             $giftcardcode       = $giftcardamtdetails['GiftcardDetail']['card_code'];
             $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
             $giftcardamt = number_format($giftcardamt,2,".","");
            
             $gftdetbl = $this->Cart->getTableName("giftcard_details");

             $gftres = $this->Giftcard->query("update " . $gftdetbl . " set balance=(balance-" . $giftcardamt . ") where card_code='" . trim($giftcardcode) . "' and  user_id='" . $user_id . "'");
            
            
        }

        ################################### Sending Fax Ends here ###################################
        $this->Session->write('promo_code', "");
        
        if ($this->Session->check('Coupon') == true) {
            
            $this->Session->delete('Coupon');
        }
        if ($this->Session->check('GiftCard') == true) {
            
            $this->Session->delete('GiftCard');
        }
        if ($this->Session->check('GiftCardDiscount') == true) {
            
             $this->Session->delete('GiftCardDiscount');
        }
        



        $this->Session->setFlash('Your order has been successfully placed and an e-mail with order details has sent to your e-mail ID!!');

        $this->redirect(array('controller' => 'orders', 'action' => 'userorderdetails/' . $order_id));

        exit;
    }



    ################# Ak 2 co payment starts here #################

    function twocoPayment($ship = '') {


        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        //    $this->set('curlogo', $curr["Currency"]["logo"]);
        $testmode = $cnfg['twocheckout_testmode']; // test mode
        $tocoVendorid = $cnfg['twoco_vendorId'];// test id '1877160';

        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
            $gtotal = $gtotal-  $giftcardamt;  
            $gtotal = number_format($gtotal,2,".","");
            
        }


        /*  $this->Session->write('sessShipmeth', $shippingMethod);
        $this->Session->write('sessShipcost', $shipping_cost);
        $this->Session->write('sessShipserv', $shippingServ);
        $this->Session->write('Payamount', $gtotal);
        $this->Session->write('taxamt', $taxamt);
        $this->Session->write('taxname', $taxname);
        $this->Session->write('discamt', $discamt);
        $this->Session->write('couponcode', $couponcode);*/

        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $gtotal);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);
        $this->Session->write('testmode', $testmode);

        //***********2co payment ****************

        // print_r($cnfg);exit;


        $returnUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/copaysucess';

        // Specify your 2CheckOut vendor id
        $this->TwoCo->addField('sid', $tocoVendorid);

        // Specify the order information
        $this->TwoCo->addField('cart_order_id', rand(1, 1000));
        $this->TwoCo->addField('total', $gtotal);

        // Specify the url where authorize.net will send the IPN
        $this->TwoCo->addField('x_Receipt_Link_URL', $returnUrl);

        $this->TwoCo->addField('tco_currency', $curr["Currency"]["code"]);
        // $this->TwoCo->addField('custom', 'muri');


        // Enable test mode if needed
        if($testmode == "Y" || $testmode == 'Y')
            $this->TwoCo->enableTestMode();

        // Let's start the train!
        // $this->set('twocopayment',$this->TwoCo->submitPayment());
        $this->set('twocopayment',$this->TwoCo->submitPaymentDisplay());

        //****************2co payment  ends ****************
        //
        //    $this->Session->setFlash($res["msg"]);

        //  $this->redirect('/index.php');
        // exit;


    }
    function copaysucess() {

        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $testmode = $this->Session->read('testmode');
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
           
            
        }


        foreach ($_POST as $field=>$value) {
            $this->ipnData["$field"] = $value;
        }

        //  $vendorNumber   = ($this->ipnData["vendor_number"] != '') ? $this->ipnData["vendor_number"] : $this->ipnData["sid"];

        /*    $vendorNumber =$this->ipnData["sid"];
        $orderNumber    = $this->ipnData["order_number"];
        $orderTotal     = $this->ipnData["total"];*/

        // If demo mode, the order number must be forced to 1
        if($testmode == "Y" || $testmode == 'Y') {
            $orderNumber = "1";
        }

        // Calculate md5 hash as 2co formula: md5(secret_word + vendor_number + order_number + total)
        // $key = strtoupper(md5($this->TwoCo->secret . $vendorNumber . $orderNumber . $orderTotal));

        // verify if the key is accurate
        // if($this->ipnData["key"] == $key || $this->ipnData["x_MD5_Hash"] == $key)
        if($this->ipnData["key"] != '' && $this->ipnData["credit_card_processed"] == 'Y' && $this->ipnData["total"] == $gtotal) {

            $trans_id = $this->ipnData["key"];
            $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, '2Co Payment' , $trans_id,'',$giftcardamt);
            exit;
        }
        else {
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;

        }


    }

    function moneybookers($ship = '') {


        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);

        //    $this->set('curlogo', $curr["Currency"]["logo"]);
        // $testmode = $cnfg['twocheckout_testmode']; // test mode
        $pay_to_email = $cnfg['moneybookers_emailId'];// test id '1877160';

        $shippingMethod = $cartdetails['sessShipmeth'];
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt;    
             
             $cartdetails['Payamount'] = number_format($cartdetails['Payamount'],2,".","");
            
        }

        $gtotal = $cartdetails['Payamount'];

        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);
        $this->Session->write('pay_to_email', $pay_to_email);


        //***********2co payment ****************

        //  print_r($cnfg);exit;


        $returnUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/moneybookerssucesspost/return';
        //$postUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/moneybookerssucesspost/sucess';
        $postUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/moneybookersverify';

        // Specify your Moneybrokers email id
        $this->Moneybrokers->addField('pay_to_email', $pay_to_email);

        // Url getting return post data
        $this->Moneybrokers->addField('status_url', $postUrl);

        // Language
        $this->Moneybrokers->addField('language', 'EN');

        // Amount
        $this->Moneybrokers->addField('amount', $gtotal);
        $this->Moneybrokers->addField('currency', $curr["Currency"]["code"]);
        $this->Moneybrokers->addField('detail1_description', "Description:");
        $this->Moneybrokers->addField('detail1_text', "Order Purchase");
        $this->Moneybrokers->addField('return_url', $returnUrl);
        $this->Moneybrokers->addField('confirmation_note', "Payment Sucess");


        $this->set('moneybrokers',$this->Moneybrokers->submitPaymentDisplay());

        //****************2co payment  ends ****************
        //
        //    $this->Session->setFlash($res["msg"]);

        //  $this->redirect('/index.php');
        // exit;


    }
    function moneybookerssucess() {
//print_r($_REQUEST);
//echo 'sucess';exit;
        $moneybookerspaymentstatus =  $this->Session->read('moneybookerspayflage');
        if($moneybookerspaymentstatus) {
            $this->redirect('/orders/myorder');
            exit;
        }else {
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
        }


    }
    
    function moneybookersverify() {
        $file = fopen(WWW_ROOT.'moneybooker.txt',"w");
        fwrite($file,$_REQUEST["mb_transaction_id"]);
        fclose($file);
    }

function moneybookerssucesspost($return = "") {

        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $moneybrokerspostvalue = $_REQUEST; // get post value from money bookers
        $this->Session->read('couponcode');
        $this->Session->write('moneybookerspayflage', false);

        $mbfile = fopen(WWW_ROOT.'moneybooker.txt', "r") or die("Unable to open file!");
        $trans_id = fread($mbfile,filesize(WWW_ROOT.'moneybooker.txt'));
        fclose($mbfile);
        
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
        
            
        }


        /*if(count($moneybrokerspostvalue) > 0) {
            foreach ($moneybrokerspostvalue as $field=>$value) {
                $this->ipnData["$field"] = $value;
            }*/

            if($trans_id) //if apyment is sucess
            {
                //$trans_id = $this->ipnData["mb_transaction_id"];
                $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Money Bookers' , $trans_id,'',$giftcardamt);
                $this->Session->write('moneybookerspayflage', true);
                exit;
            }

            else {
                $this->Session->setFlash("Payment failed!");
                $this->Session->write('moneybookerspayflage', false);
                  $this->redirect('/carts/payment');
                exit;

            }
        /*}else {
            $this->Session->setFlash("Payment failed!");
            $this->Session->write('moneybookerspayflage', false);
             $this->redirect('/carts/payment');
            exit;

        }*/

    }


// Paypal pro payment

function paypalpropayment($ship = '') {

    $ship = "";

    $ship = $this->Session->read('SESS_SHIPMENT');

    $this->__validateLoginStatus();

    $sus = $this->Session->read('Userlog');

    $this->set('sus', $sus);

    $cnfg = Configure::read('Neutrino');

    $user_id = $sus["id"];
    $curr = $this->Currency->findByCode($cnfg["currency"]);
    //**********cart setting data
    $cartdetails = $this->__getCartDetailsArray($ship);
    //********************


    $this->set('totaltopay', $cartdetails['totaltopay']);
    $this->set('curlogo', $curr["Currency"]["logo"]);
    $this->set('taxamnt', $cartdetails['taxamt']);
    $this->set('discount', $cartdetails['discamt']);
    $this->set('shipping_cost', $cartdetails['sessShipcost']);
    if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt;    
             
             $cartdetails['Payamount'] = number_format($cartdetails['Payamount'],2,".","");
            
    }
    $this->set('gtotal', $cartdetails['Payamount']);


    $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

    $Company = "-NA-";

    $newinvid = $this->Order->getNewinvid();

    $txtEmail = $sus["email"];

    //set card for user on country


    if(isset($billadd)) {
        if($billadd['UserAddress']['country'] == 'GB') {
            $paymentmethod = array('Visa'=>'Visa','Visa Electron'=>'Visa Electron','Visa Debit'=>'Visa Debit','Maestro'=>'Maestro','Mastercard'=>'Mastercard');
        }elseif($billadd['UserAddress']['country'] == 'US') {
            $paymentmethod = array('Visa'=>'Visa','Mastercard'=>'Mastercard','Discover'=>'Discover','AmericanExpress'=>'American Express');
        }elseif($billadd['UserAddress']['country'] == 'CA') {
            $paymentmethod = array('Visa'=>'Visa','Mastercard'=>'Mastercard');
        }else {
            $paymentmethod = array('Visa'=>'Visa','Mastercard'=>'Mastercard');
        }
    }else {
        $paymentmethod = array('Visa'=>'Visa','Mastercard'=>'Mastercard');
    }
    $this->set('paymentmethod', $paymentmethod);


    $shippingMethod = $cartdetails['sessShipmeth'];
    $gtotal = $cartdetails['Payamount'];

    $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
    $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
    $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
    $this->Session->write('Payamount', $cartdetails['Payamount']);
    $this->Session->write('taxamt', $cartdetails['taxamt']);
    $this->Session->write('taxname', $cartdetails['taxname']);
    $this->Session->write('discamt', $cartdetails['discamt']);
    $this->Session->write('couponcode', $cartdetails['couponcode']);



    //***********Paypalpro payment ****************

    if(isset($_POST['btnCompleteOrderpaypro'])) {
        if($_POST['btnCompleteOrderpaypro']) { 
            // Set request-specific fields.
            $paymentType = urlencode('Sale');               // or 'Sale'   Authorization

            $creditCardType = urlencode($_POST['paymentmethod']); //urlencode('customer_credit_card_type');
            $creditCardNumber = urlencode($_POST['txtCCNumber']); //urlencode('customer_credit_card_number');
            $expDateMonth = $_POST['txtMM']; //'cc_expiration_month';
            // Month must be padded with leading zero
            $padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
            $expDateYear = urlencode($_POST['txtYY']); //urlencode('cc_expiration_year');
            $cvv2Number = urlencode($_POST['txtCVV2']); //urlencode('cc_cvv2_number');

            //user details

            $firstName = urlencode($billadd['UserAddress']['fname']); //urlencode('customer_first_name');
            $lastName = urlencode($billadd['UserAddress']['lname']); //urlencode('customer_last_name');
            $address1 = urlencode($billadd['UserAddress']['address']);
            //$address2 = urlencode($billadd['UserAddress']['fname']);
            $city = urlencode($billadd['UserAddress']['city']); //urlencode('customer_city');
            $state = urlencode($billadd['UserAddress']['state']); //urlencode('customer_state');
            $zip = urlencode($billadd['UserAddress']['zip']); //urlencode('customer_zip');
            $country = urlencode($billadd['UserAddress']['country']);// US or other valid country code


            //Admin paymnet details
            $this->Paypalpro->API_UserName = $cnfg['paypalpro_username'];
            $this->Paypalpro->API_Password = $cnfg['paypalpro_password'];
            $this->Paypalpro->API_Signature = $cnfg['paypalpro_signature'];


            // Specify payment action eg: Sales

            $this->Paypalpro->addField('PAYMENTACTION', $paymentType);

            // Paymnet amount
            $this->Paypalpro->addField('AMT', $gtotal);

            // Credit card type
            $this->Paypalpro->addField('CREDITCARDTYPE', $creditCardType);

            // Credit card number
            $this->Paypalpro->addField('ACCT', $creditCardNumber);
            // $this->Paypalpro->addField('ACCT','4055825683869610');

            // Currency Code
            $this->Paypalpro->addField('CURRENCYCODE', $curr["Currency"]["code"]);

            // Credit card Expiration Date
            $this->Paypalpro->addField('EXPDATE', $padDateMonth.$expDateYear);


            //enable test mode
            if($cnfg['paypalpro_testmode'] == 'Y')
                $this->Paypalpro->enableTestMode();


            $this->Paypalpro->addField('CVV2', $cvv2Number);
            // User Details
            $this->Paypalpro->addField('FIRSTNAME', $firstName);
            $this->Paypalpro->addField('LASTNAME', $lastName);
            $this->Paypalpro->addField('STREET', $address1);
            $this->Paypalpro->addField('CITY', $city);
            $this->Paypalpro->addField('STATE', $state);
            $this->Paypalpro->addField('ZIP', $zip);
            $this->Paypalpro->addField('COUNTRYCODE', $country);

            // BN Code
            $this->Paypalpro->addField('BUTTONSOURCE', $cnfg['paypalpro_bn_code']);

            $paymnetResult =  $this->Paypalpro->submitPaymentDisplay();

          //echopre($paymnetResult);exit;

            if(count($paymnetResult) > 0) {

                if($paymnetResult['ACK'] == 'Success' && $paymnetResult['AMT'] == $gtotal) {

                    $shippingMethod = $this->Session->read('sessShipmeth');
                    $shipping_cost = $this->Session->read('sessShipcost');
                    $shippingServ = $this->Session->read('sessShipserv');
                    $gtotal= $this->Session->read('Payamount');
                    $taxamt = $this->Session->read('taxamt');
                    $taxname = $this->Session->read('taxname');
                    $discamt = $this->Session->read('discamt');
                    $couponcode = $this->Session->read('couponcode');
                    $this->Session->read('couponcode');
                    $trans_id = $paymnetResult['TRANSACTIONID'];
                    if ($this->Session->check('GiftCardDiscount') == true) {
            
                        $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                        $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                        $giftcardamt = number_format($giftcardamt,2,".","");
                          

                    }
                    $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Paypalpro Payment' , $trans_id,'',$giftcardamt);
                    exit;
                }else {
                    $this->Session->setFlash("Payment failed!");
                    $this->redirect('/carts/payment');
                    exit;
                }
            }else {
                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;
            }
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;


        }
    }
 //****************paypal pro payment  ends ****************

}



// Paypal flow payment

    function paypalflowpayment($ship = '') {

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];
        $curr = $this->Currency->findByCode($cnfg["currency"]);
        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************


        $this->set('totaltopay', $cartdetails['totaltopay']);
        $this->set('curlogo', $curr["Currency"]["logo"]);
        $this->set('taxamnt', $cartdetails['taxamt']);
        $this->set('discount', $cartdetails['discamt']);
        $this->set('shipping_cost', $cartdetails['sessShipcost']);
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt;    
             $cartdetails['Payamount'] = number_format( $cartdetails['Payamount'],2,".","");
            
        }
        $this->set('gtotal', $cartdetails['Payamount']);


        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];



        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];

        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);



        //***********Paypalflow payment ****************


        if(isset($_POST['btnCompleteOrderpaypro'])) {
            if($_POST['btnCompleteOrderpaypro']) {

                // Set request-specific fields.
                $paymentType = urlencode('S');              // or 'Sale'   Authorization

                //$creditCardType = urlencode($_POST['paymentmethod']); //urlencode('customer_credit_card_type');
                $creditCardNumber = urlencode($_POST['txtCCNumber']); //urlencode('customer_credit_card_number');
                $expDateMonth = $_POST['txtMM']; //'cc_expiration_month';
                // Month must be padded with leading zero
                $padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
                $expDateYear = urlencode($_POST['txtYY']); //urlencode('cc_expiration_year');
                $cvv2Number = urlencode($_POST['txtCVV2']); //urlencode('cc_cvv2_number');

                //user details

                $firstName = urlencode($billadd['UserAddress']['fname']); //urlencode('customer_first_name');
                $lastName = urlencode($billadd['UserAddress']['lname']); //urlencode('customer_last_name');
                $address1 = urlencode($billadd['UserAddress']['address']);
                //$address2 = urlencode($billadd['UserAddress']['fname']);
                $city = urlencode($billadd['UserAddress']['city']); //urlencode('customer_city');
                $state = urlencode($billadd['UserAddress']['state']); //urlencode('customer_state');
                $zip = urlencode($billadd['UserAddress']['zip']); //urlencode('customer_zip');
                $country = urlencode($billadd['UserAddress']['country']);// US or other valid country code



                //Admin paymnet details
                $this->Paypalflow->API_UserName = $cnfg['paypalflow_vendorid'];
                $this->Paypalflow->API_Password = $cnfg['paypalflow_password'];
                $this->Paypalflow->API_partnerID = $cnfg['paypalflow_partnerid'];


                // Specify payment action eg: Sales

                $this->Paypalflow->addField('TRXTYPE', $paymentType);
                $this->Paypalflow->addField('TENDER', 'C');


                // Paymnet amount
                $this->Paypalflow->addField('AMT', $gtotal);

                // Credit card type
                // $this->Paypalpro->addField('CREDITCARDTYPE', $creditCardType);

                // Credit card number
                $this->Paypalflow->addField('ACCT', $creditCardNumber);
                // $this->Paypalpro->addField('ACCT','5105105105105100');//test account

                //Comment
                //
                $this->Paypalflow->addField('COMMENT1', 'Purchase using vistacart');
                // Currency Code
                //$this->Paypalflow->addField('CURRENCYCODE', $curr["Currency"]["code"]);

                // Credit card Expiration Date
                $this->Paypalflow->addField('EXPDATE', $padDateMonth.$expDateYear);

                $this->Paypalflow->addField('CVV2', $cvv2Number);


                //enable test mode
                if($cnfg['paypalflow_testmode'] == 'Y')
                    $this->Paypalflow->enableTestMode();



                // User Details
                $this->Paypalflow->addField('FIRSTNAME', $firstName);
                $this->Paypalflow->addField('LASTNAME', $lastName);
                $this->Paypalflow->addField('STREET', $address1);
                $this->Paypalflow->addField('CITY', $city);
                $this->Paypalflow->addField('STATE', $state);
                $this->Paypalflow->addField('ZIP', $zip);
                $this->Paypalflow->addField('COUNTRYCODE', $country);



                $paymnetResult =  $this->Paypalflow->submitPaymentDisplay();

                // print_r($paymnetResult);exit;

                if(count($paymnetResult) > 0) {

                    if($paymnetResult['RESULT'] == '0' && $paymnetResult['RESPMSG'] == 'Approved' && isset ($paymnetResult['PNREF']) ) {

                        $shippingMethod = $this->Session->read('sessShipmeth');
                        $shipping_cost = $this->Session->read('sessShipcost');
                        $shippingServ = $this->Session->read('sessShipserv');
                        $gtotal= $this->Session->read('Payamount');
                        $taxamt = $this->Session->read('taxamt');
                        $taxname = $this->Session->read('taxname');
                        $discamt = $this->Session->read('discamt');
                        $couponcode = $this->Session->read('couponcode');
                        $this->Session->read('couponcode');
                        $trans_id = $paymnetResult['PNREF'];
                        if ($this->Session->check('GiftCardDiscount') == true) {
            
                                $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                                $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                                $giftcardamt = number_format($giftcardamt,2,".","");
                                

                        }
                        $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Paypalflow Payment' , $trans_id,'',$giftcardamt);
                        exit;
                    }else {
                        $this->Session->setFlash("Payment failed!");
                        $this->redirect('/carts/payment');
                        exit;
                    }
                }else {
                    $this->Session->setFlash("Payment failed!");
                    $this->redirect('/carts/payment');
                    exit;
                }
                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;


            }
        }
//****************paypal flow payment  ends ****************

    }



// Ppaypaladvanced payment

    function paypaladvanced($ship = '') {

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];
        $curr = $this->Currency->findByCode($cnfg["currency"]);
        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************


        $this->set('totaltopay', $cartdetails['totaltopay']);
        $this->set('curlogo', $curr["Currency"]["logo"]);
        $this->set('taxamnt', $cartdetails['taxamt']);
        $this->set('discount', $cartdetails['discamt']);
        $this->set('shipping_cost', $cartdetails['sessShipcost']);
        
         if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
             $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt;   
             $cartdetails['Payamount'] = number_format( $cartdetails['Payamount'],2,".","");
            
        }
        $this->set('gtotal', $cartdetails['Payamount']);


        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];



        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];

        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);



        //***********Paypalflow payment ****************


        // Set request-specific fields.
        $paymentType = urlencode('A');              // or 'Sale'   Authorization



        //user details

        $firstName = urlencode($billadd['UserAddress']['fname']); //urlencode('customer_first_name');
        $lastName = urlencode($billadd['UserAddress']['lname']); //urlencode('customer_last_name');
        $address1 = urlencode($billadd['UserAddress']['address']);
        //$address2 = urlencode($billadd['UserAddress']['fname']);
        $city = urlencode($billadd['UserAddress']['city']); //urlencode('customer_city');
        $state = urlencode($billadd['UserAddress']['state']); //urlencode('customer_state');
        $zip = urlencode($billadd['UserAddress']['zip']); //urlencode('customer_zip');
        $country = urlencode($billadd['UserAddress']['country']);// US or other valid country code

        $returnUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvancedsucess';
        $cancelUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvancedsucess';
        $errorUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvancedsucess';

        /*  $returnUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvanced';
            $cancelUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvanced';
            $errorUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/paypaladvanced';*/

        //Admin paymnet details
        $this->Paypaladvanced->API_Vendor = $cnfg['paypal_advancedVENDOR'];
        $this->Paypaladvanced->API_Password = $cnfg['paypal_advancedPWD'];
        $this->Paypaladvanced->API_partnerID = $cnfg['paypal_advancedPARTNER'];


        $this->Paypaladvanced->addField('USER', $cnfg['paypal_advancedUSER']);

        // Specify payment action eg: Sales

        $this->Paypaladvanced->addField('TRXTYPE', $paymentType);
        $this->Paypaladvanced->addField('CREATESECURETOKEN', 'Y');


        // Paymnet amount
        $this->Paypaladvanced->addField('AMT', $gtotal);


        $this->Paypaladvanced->addField('CURRENCY', $curr["Currency"]["code"]);
        // '5105105105105100');//test account

        //Comment
        //
        $this->Paypaladvanced->addField('SECURETOKENID', uniqid('MySecTokenID-'));


        // RETURNURL
        $this->Paypaladvanced->addField('RETURNURL', $returnUrl);

        $this->Paypaladvanced->addField('CANCELURL', $cancelUrl);

        $this->Paypaladvanced->addField('ERRORURL', $errorUrl);


        //enable test mode
        if($cnfg['paypalflow_testmode'] == 'Y')
            $this->Paypaladvanced->enableTestMode();



        // User Details
        $this->Paypaladvanced->addField('BILLTOFIRSTNAME', $firstName);
        $this->Paypaladvanced->addField('BILLTOLASTNAME', $lastName);
        $this->Paypaladvanced->addField('BILLTOSTREET', $address1);
        $this->Paypaladvanced->addField('BILLTOCITY', $city);
        $this->Paypaladvanced->addField('BILLTOSTATE', $state);
        $this->Paypaladvanced->addField('BILLTOZIP', $zip);
        $this->Paypaladvanced->addField('BILLTOCOUNTRY', $country);


        $this->Paypaladvanced->addField('SHIPTOFIRSTNAME', $firstName);
        $this->Paypaladvanced->addField('SHIPTOLASTNAME', $lastName);
        $this->Paypaladvanced->addField('SHIPTOSTREET', $address1);
        $this->Paypaladvanced->addField('SHIPTOCITY', $city);
        $this->Paypaladvanced->addField('SHIPTOSTATE', $state);
        $this->Paypaladvanced->addField('SHIPTOZIP', $zip);
        $this->Paypaladvanced->addField('SHIPTOCOUNTRY', $country);

        // BN Code
        $this->Paypaladvanced->addField('BUTTONSOURCE', $cnfg['paypaladvanced_bn_code']);



        $paymnetResult =  $this->Paypaladvanced->submitPaymentDisplay();




        if ($paymnetResult['RESULT'] != 0) {
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;

        } else {
            $securetoken = $paymnetResult['SECURETOKEN'];
            $securetokenid = $paymnetResult['SECURETOKENID'];
        }
        if($cnfg['paypalflow_testmode'] == 'Y') $mode='TEST'; else $mode='LIVE';


        /* $paypaladvancedrender = '<div style="border: 1px dashed; margin-left:40px; width:492px; height:567px;">'; // wrap iframe in a dashed wireframe for demo purposes
            $paypaladvancedrender .= "  <iframe src='https://payflowlink.paypal.com?SECURETOKEN=$securetoken&SECURETOKENID=$securetokenid&MODE=$mode' width='490' height='565' border='0' frameborder='0' scrolling='no' allowtransparency='true'>\n</iframe>";
            $paypaladvancedrender .=  "</div>";*/
        $url = "https://payflowlink.paypal.com?SECURETOKEN=$securetoken&SECURETOKENID=$securetokenid&MODE=$mode";
        $this->redirect($url);
        exit;
//  $this->set('paypaladvancedrender', $paypaladvancedrender);

        /* exit;


//****************paypaladvanced payment  ends ****************
        */
    }
    function paypaladvancedsucess($ship = '') {
        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $testmode = $this->Session->read('testmode');
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
           
        }
        if(isset($_POST)) {
            if($_POST['RESPMSG'] == 'Approved' && $_POST['RESULT'] == 0 && $_POST['AMT'] == $gtotal) {
                $trans_id = $_POST['PNREF'];
                $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Paypal Advanced Payment' , $trans_id,'',$giftcardamt);
                exit;
            }else {
                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;
            }
        }else {
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;
        }


    }


// braintree payment

function braintreepayment($ship = '') {

    $ship = "";

    $ship = $this->Session->read('SESS_SHIPMENT');

    $this->__validateLoginStatus();

    $sus = $this->Session->read('Userlog');

    $this->set('sus', $sus);

    $cnfg = Configure::read('Neutrino');

    $user_id = $sus["id"];
    $curr = $this->Currency->findByCode($cnfg["currency"]);
    //**********cart setting data
    $cartdetails = $this->__getCartDetailsArray($ship);
    //********************
    


    $this->set('totaltopay', $cartdetails['totaltopay']);
    $this->set('curlogo', $curr["Currency"]["logo"]);
    $this->set('taxamnt', $cartdetails['taxamt']);
    $this->set('discount', $cartdetails['discamt']);
    $this->set('shipping_cost', $cartdetails['sessShipcost']);
    $this->set('gtotal', $cartdetails['Payamount']);
    
    if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            
            $cartdetails['totaltopay'] = $cartdetails['totaltopay']-  $giftcardamt;   
            $cartdetails['Payamount'] = number_format( $cartdetails['Payamount'],2,".","");
            
        }


    $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

    $Company = "-NA-";

    $newinvid = $this->Order->getNewinvid();

    $txtEmail = $sus["email"];



    $shippingMethod = $cartdetails['sessShipmeth'];
    $gtotal = $cartdetails['Payamount'];

    $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
    $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
    $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
    $this->Session->write('Payamount', $cartdetails['Payamount']);
    $this->Session->write('taxamt', $cartdetails['taxamt']);
    $this->Session->write('taxname', $cartdetails['taxname']);
    $this->Session->write('discamt', $cartdetails['discamt']);
    $this->Session->write('couponcode', $cartdetails['couponcode']);



    //***********Braintree payment ****************
//print_r($cnfg);exit;
try{
Braintree_Configuration::merchantId($cnfg['braintree_merchantId']);
Braintree_Configuration::publicKey($cnfg['braintree_publicKey']);
Braintree_Configuration::privateKey($cnfg['braintree_privateKey']);

//Check test mode


if($cnfg['braintree_testmode'] == 'Y'){ 
Braintree_Configuration::environment('sandbox');
}
//if sucess
 if (isset($_GET["id"])) {
  
   //$result = Braintree_TransparentRedirect::confirm($_SERVER['QUERY_STRING']);
   $result= $_GET;
    
}
}catch (Exception $e){ echo $e;}
//transactio sucess

// if (isset($result) && $result->success) {

if(isset($result) && $result['http_status'] == 200 && $result['kind'] == "create_transaction"){
        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $this->Session->read('couponcode');
       // $trans_id = $paymnetResult['PNREF'];
        $trans_id = time();
        $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Braintree Payment' , $trans_id);
        exit;
     
     
 }
 else{
     if (!isset($result)) { $result = null; }

   
     $form_url = Braintree_TransparentRedirect::url();
     $firstName = $billadd['UserAddress']['fname'];
     $lastName = $billadd['UserAddress']['lname'];
     $email = $billadd['UserAddress']['email'];
    $tr_data = Braintree_TransparentRedirect::transactionData(
                    array('redirectUrl' => "http://" . $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH),
                    'transaction' => array('amount' => $gtotal, 'type' => 'sale')));
    
    
    $this->set('form_url', $form_url);
    $this->set('firstName', $firstName);
    $this->set('lastName', $lastName);
    $this->set('email', $email);
    $this->set('tr_data', $tr_data);


  // exit;

 }

 
//****************braintree payment  ends ****************

}







 
#################  paypalflow link payment starts here #################

    function paypalflowlinkpayment($ship = '') {


        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);


        //    $this->set('curlogo', $curr["Currency"]["logo"]);
        $testmode = $cnfg['paypallink_testmode']; // test mode


        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];



        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);
        $this->Session->write('testmode', $testmode);

        //***********paypalflow link payment ****************

        // print_r($cnfg);exit;


        $returnUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/payflowlinksucess';

        // Specify your payflowlink vendor id
        $this->Payflowlink->addField('LOGIN', $cnfg['paypallink_vendorid']);

        $this->Payflowlink->addField('PARTNER', $cnfg['paypallink_partnerid']);

        $this->Payflowlink->addField('AMOUNT', $gtotal);

        $this->Payflowlink->addField('CUSTID', rand(1,10000));

        $this->Payflowlink->addField('RETURNURL', $returnUrl);

        $this->Payflowlink->addField('ORDERFORM', True);

        $this->Payflowlink->addField('SHOWCONFIRM', True);

        $this->Payflowlink->addField('TYPE', 'S');

        $this->Payflowlink->addField('METHOD', 'CC');


        // Enable test mode if needed
        if($testmode == "Y" || $testmode == 'Y')
            $this->Payflowlink->enableTestMode();

           

            // User Details
            $this->Payflowlink->addField('NAME', $billadd['UserAddress']['fname'] ." " . $billadd['UserAddress']['lname']);
            $this->Payflowlink->addField('ADDRESS',  $billadd['UserAddress']['address']);
            $this->Payflowlink->addField('CITY', $billadd['UserAddress']['city']);
            $this->Payflowlink->addField('STATE', $billadd['UserAddress']['state']);
            $this->Payflowlink->addField('COUNTRY', $billadd['UserAddress']['country']);
            $this->Payflowlink->addField('ZIP', $billadd['UserAddress']['zip']);
            $this->Payflowlink->addField('PHONE', $billadd['UserAddress']['phone']);
            $this->Payflowlink->addField('FAX', $billadd['UserAddress']['fax']);
          




        // Let's start the train!

        $this->set('payflowlink',$this->Payflowlink->submitPaymentDisplay());

        //****************paypalflowlinkpayment  ends ****************


    }

    function  payflowlinksucess() {

        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $testmode = $this->Session->read('testmode');
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
           
            
        }

        if(isset($_POST)) {
            if($_POST['RESPMSG'] == 'Approved' && $_POST['RESULT'] == 0 && $_POST['AMT'] == $gtotal) {
                $trans_id = $_POST['PNREF'];
                $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Payflowlink Payment' , $trans_id,'',$giftcardamt);
                exit;
            }else {
                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;
            }
        }else {
            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;
        }

    }



#################  pogone payment starts here #################

    function ogonepayment($ship = '') {


        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];

        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************

        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];

        $curr = $this->Currency->findByCode($cnfg["currency"]);


        //    $this->set('curlogo', $curr["Currency"]["logo"]);
        $testmode = $cnfg['ogone_testmode']; // test mode


        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];
         if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
            //$this->set('gift_card_amt', $giftcardamt);
            $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt;  
            $cartdetails['Payamount'] = number_format($cartdetails['Payamount'],2,".","");
            
        }



        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);
        $this->Session->write('testmode', $testmode);

        //***********ogone payment ****************

        //  print_r($cnfg);exit;


        $CANCELURL  = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/ogonesucess/cancel';
        $exceptionUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/ogonesucess/exception';
        $declineUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/ogonesucess/decline';
        $acceptUrl = FULL_BASE_URL . $cnfg["sitebasefolder"].'/carts/ogonesucess/success';
        $unique_id =RAND(10000,895689596);
        $logo = "http://localhost/vistacart/img/SiteLogo_disp.gif";
        // Specify your payflowlink vendor id
        $this->Ogone->addField('PSPID', $cnfg['ogone_PSPID']);

        $this->Ogone->passPhrase = $cnfg['ogone_passphrase'];

        $this->Ogone->addField('AMOUNT', $cartdetails['Payamount']);

        $this->Ogone->addField('CANCELURL', $CANCELURL);

        $this->Ogone->addField('DECLINEURL', $declineUrl);

        $this->Ogone->addField('EXCEPTIONURL', $exceptionUrl);

        $this->Ogone->addField('ACCEPTURL', $acceptUrl);

        $this->Ogone->addField('ORDERID', $unique_id);

        $this->Ogone->addField('CURRENCY', $cnfg['currency']);
      //  $this->Ogone->addField('CURRENCY', 'EUR');


        $this->Ogone->addField('LANGUAGE', 'en_us');

        $this->Ogone->addField('LOGO', $logo);

        $this->Ogone->addField('OPERATION','SAL');


        // Enable test mode if needed
        if($testmode == "Y" || $testmode == 'Y')
            $this->Ogone->enableTestMode();


        // User Details
        $this->Ogone->addField('CN', $billadd['UserAddress']['fname'] ." " . $billadd['UserAddress']['lname']);
        $this->Ogone->addField('EMAIL',  $billadd['UserAddress']['email']);


        // Let's start the train!
        // echo $this->Ogone->submitPaymentDisplay();exit;
        $this->set('ogone',$this->Ogone->submitPaymentDisplay());

        //****************ogone payment  ends ****************


    }

    function ogonesucess($action = "") {

        $shippingMethod = $this->Session->read('sessShipmeth');
        $shipping_cost = $this->Session->read('sessShipcost');
        $shippingServ = $this->Session->read('sessShipserv');
        $gtotal= $this->Session->read('Payamount');
        $taxamt = $this->Session->read('taxamt');
        $taxname = $this->Session->read('taxname');
        $discamt = $this->Session->read('discamt');
        $couponcode = $this->Session->read('couponcode');
        $testmode = $this->Session->read('testmode');
        
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
           
            
        }


       if(isset($_REQUEST)){
        if(($_REQUEST['NCERROR'] == '0' || $_REQUEST['NCERROR'] == 0)  && $_REQUEST['PAYID'] != "" && $_REQUEST['amount'] == $gtotal){
            $trans_id = $_REQUEST['PAYID'];
            $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Ogone Payment' , $trans_id,'',$giftcardamt);
            exit;
        }else{

                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;
            }
        }else {

            $this->Session->setFlash("Payment failed!");
            $this->redirect('/carts/payment');
            exit;
        }

    }

// ogone ends

    function  quickbookpayment($ship = '') {

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        $cnfg = Configure::read('Neutrino');

        $user_id = $sus["id"];
        $curr = $this->Currency->findByCode($cnfg["currency"]);
        //**********cart setting data
        $cartdetails = $this->__getCartDetailsArray($ship);
        //********************
        if ($this->Session->check('GiftCardDiscount') == true) {
            
            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
        $giftcardamt = number_format($giftcardamt,2,".","");
           
            $cartdetails['Payamount'] = $cartdetails['Payamount']-  $giftcardamt; 
            $cartdetails['Payamount'] = number_format($cartdetails['Payamount'],2,".","");
            
        }

        $this->set('totaltopay', $cartdetails['totaltopay']);
        $this->set('curlogo', $curr["Currency"]["logo"]);
        $this->set('taxamnt', $cartdetails['taxamt']);
        $this->set('discount', $cartdetails['discamt']);
        $this->set('shipping_cost', $cartdetails['sessShipcost']);
        $this->set('gtotal', $cartdetails['Payamount']);
        
        


        $billadd = $this->UserAddress->find("UserAddress.user_id =" . $user_id . " AND UserAddress.addr_type ='Billing'");

        $Company = "-NA-";

        $newinvid = $this->Order->getNewinvid();

        $txtEmail = $sus["email"];



        $shippingMethod = $cartdetails['sessShipmeth'];
        $gtotal = $cartdetails['Payamount'];
        
        

        $this->Session->write('sessShipmeth', $cartdetails['sessShipmeth']);
        $this->Session->write('sessShipcost', $cartdetails['sessShipcost']);
        $this->Session->write('sessShipserv', $cartdetails['sessShipserv']);
        $this->Session->write('Payamount', $cartdetails['Payamount']);
        $this->Session->write('taxamt', $cartdetails['taxamt']);
        $this->Session->write('taxname', $cartdetails['taxname']);
        $this->Session->write('discamt', $cartdetails['discamt']);
        $this->Session->write('couponcode', $cartdetails['couponcode']);



        //***********Paypalflow payment ****************

        if(isset($_POST['btnCompleteOrder'])) {
           // if($_POST['btnCompleteOrder']) {

                // Set request-specific fields.
                $paymentType = urlencode('S');              // or 'Sale'   Authorization

                //$creditCardType = urlencode($_POST['paymentmethod']); //urlencode('customer_credit_card_type');
                $creditCardNumber = urlencode($_POST['txtCCNumber']); //urlencode('customer_credit_card_number');
                $expDateMonth = $_POST['txtMM']; //'cc_expiration_month';
                // Month must be padded with leading zero
                $padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
                $expDateYear = urlencode($_POST['txtYY']); //urlencode('cc_expiration_year');
                $cvv2Number = urlencode($_POST['txtCVV2']); //urlencode('cc_cvv2_number');

                //user details

                $firstName = urlencode($billadd['UserAddress']['fname']); //urlencode('customer_first_name');
                $lastName = urlencode($billadd['UserAddress']['lname']); //urlencode('customer_last_name');
                $address1 = urlencode($billadd['UserAddress']['address']);
                //$address2 = urlencode($billadd['UserAddress']['fname']);
                $city = urlencode($billadd['UserAddress']['city']); //urlencode('customer_city');
                $state = urlencode($billadd['UserAddress']['state']); //urlencode('customer_state');
                $zip = urlencode($billadd['UserAddress']['zip']); //urlencode('customer_zip');
                $country = urlencode($billadd['UserAddress']['country']);// US or other valid country code


                //******************
               $quickbookSettings['quickbook_appname']          = $cnfg['quickbook_applicationname'];
        $quickbookSettings['quickbook_key']         = $cnfg['quickbook_key'];
        $quickbookSettings['quickbook_testmode']    = $cnfg['quickbook_testmode'];

            $quickbookSettings['qb_cardno']         = $creditCardNumber;
            $quickbookSettings['qb_expm']           = $padDateMonth;;
            $quickbookSettings['qb_expy']           = $expDateYear;
            $quickbookSettings['qb_cvno']           = $cvv2Number;
            $quickbookSettings['amount']            = $gtotal;

            $quickbookSettings['transid']           = rand(1, 1000);

            $quickbookSettings['datetime']          = date("Y-m-d H:i:s");
            if($quickbookSettings['quickbook_testmode'] == 'Y')
                $quickbookSettings['host'] = 'https://webmerchantaccount.ptc.quickbooks.com/j/AppGateway';
            else
                $quickbookSettings['host'] = 'https://merchantaccount.ptc.quickbooks.com/j/AppGateway';

            //print_r($quickbookSettings);
                $paymnetResult  = $this->Quickbook->doQuickbookPayment($quickbookSettings);
              
            

               //  print_r($paymnetResult);

                if(count($paymnetResult) > 0) {

                    if(($paymnetResult['success'] == 1 || $paymnetResult['success'] == '1') && $paymnetResult['TransactionId'] != "") {
                        $shippingMethod = $this->Session->read('sessShipmeth');
                        $shipping_cost = $this->Session->read('sessShipcost');
                        $shippingServ = $this->Session->read('sessShipserv');
                        $gtotal= $this->Session->read('Payamount');
                        $taxamt = $this->Session->read('taxamt');
                        $taxname = $this->Session->read('taxname');
                        $discamt = $this->Session->read('discamt');
                        $couponcode = $this->Session->read('couponcode');
                        $this->Session->read('couponcode');
                        $trans_id = $paymnetResult['TransactionId'];
                        
                        if ($this->Session->check('GiftCardDiscount') == true) {
            
                            $giftcardamtdetails =  $this->Session->read('GiftCardDiscount'); 
                            $giftcardamt       = $giftcardamtdetails['GiftcardDetail']['balance'];
                            $giftcardamt = number_format($giftcardamt,2,".","");
                           
                        }

                        $this->sendOrderMail($shippingMethod, $shipping_cost, $shippingServ, $gtotal, $taxamt, $taxname, $couponcode, $discamt, 'Paypalflow Payment' , $trans_id,'',$giftcardamt);
                        exit;
                    }else {
                        $this->Session->setFlash("Payment failed!");
                        $this->redirect('/carts/payment');
                        exit;
                    }
                }else {
                    $this->Session->setFlash("Payment failed!");
                    $this->redirect('/carts/payment');
                    exit;
                }
                $this->Session->setFlash("Payment failed!");
                $this->redirect('/carts/payment');
                exit;


           // }
        }
//****************paypal flow payment  ends ****************

    }


    function __getCartDetailsArray($ship = '') {

        $cartdetailsArray =array();

        $ship = "";

        $ship = $this->Session->read('SESS_SHIPMENT');

        $this->__validateLoginStatus();

        $sus = $this->Session->read('Userlog');

        $this->set('sus', $sus);

        // Category Menu Listing starts here..

        $lst = $this->Category->findAll();

        foreach ($lst as $det)
            $menu_array[$det["Category"]["id"]] = array('name' => $det["Category"]["cname"], 'parent' => $det["Category"]["parent_id"]);

        $this->set('menu_array', $menu_array);

        // Category Menu Listing ends here..

        if ($ship <> '') {

            $shipp = explode('|~@~|', $ship);

            $shippingMethod = $shipp[0];

            $shippingServ = $shipp[1];

            $shipping_cost = $shipp[2];
        } else {

            $shippingMethod = '';

            $shippingServ = '';

            $shipping_cost = 0;
        }

        $cnfg = Configure::read('Neutrino');

        $sus = $this->Session->read('Userlog');

        $user_id = $sus["id"];

        $citem = $this->Cart->findAllByUserId($user_id);

        if (count($citem) < 1) {
            $this->Session->setFlash(__('Your cart is empty.Please add products to the cart.', true));
            $this->redirect(array('controller' => 'carts', 'action' => 'show'));
            exit();
        }

        //$citem    =   $this->Cart->find('all', array('conditions' => array('Cart.type <>' => 'giftcard','user_id' => $user_id)));

        $tot_price = 0;

        $final_price = 0;

        //Getting the product type in the cart
        $prod_type = "Non-Digital";
        if (!empty($citem)) {
            foreach ($citem as $it) {
                if (trim($it["Cart"]["prodtype"]) == "Digital") {
                    $prod_type = "Digital";
                }else if(trim($it["Cart"]["type"]) == "G") {
                    $prod_type = "Digital";
                }
            }
        }
        //Getting the product type in the cart

        foreach ($citem as $item) {

            $combined_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]);

            if (isset($item["Cart"]["discount_type"]) && $item["Cart"]["discount_type"] <> '') {

                if ($item["Cart"]["discount_type"] == 'per') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $discounted_price = ($combined_price - (($combined_price * $item["Cart"]["discount"]) / 100));

                        $final_price = ($discounted_price) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }

                else if ($item["Cart"]["discount_type"] == 'amnt') {

                    if (isset($item["Cart"]["discount"]) && $item["Cart"]["discount"] <> '' && $item["Cart"]["discount"] > 0) {

                        $final_price = (($combined_price) - $item["Cart"]["discount"]) * $item["Cart"]["quantity"];
                    }

                    else
                        $final_price = ( $combined_price) * $item["Cart"]["quantity"];
                }
            }

            else {

                $final_price = ($item["Cart"]["product_price"] + $item["Cart"]["extra_price"]) * $item["Cart"]["quantity"];
            }

            $tot_price = $tot_price + $final_price;
        }


        ######################### Section to find and add tax amount.............................

        $taxamt = 0;

        if ($cnfg["taxto"] == "gtotal") {

            $taxableamt = $tot_price + $shipping_cost;
        } else {

            $taxableamt = $tot_price;
        }

        if ($cnfg["tax_option"] == "notax") {

            $taxperc = 0;

            $taxname = "No Tax is applicable";
        } elseif ($cnfg["tax_option"] == "fixedtax") {

            $taxperc = $cnfg["fixedtax_rate"];

            $taxname = $cnfg["fixedtax_name"];
        } else {

            if ($cnfg["taxable_address"] == "shipping") {
                if (trim($prod_type) == 'Digital')
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
                else
                    $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Shipping"');
            }else {

                $billadd = $this->UserAddress->find('UserAddress.user_id = ' . $user_id . ' AND UserAddress.addr_type = "Billing"');
            }

            $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code = "All"');

            if (!empty($stdetal["State"])) {

                $taxperc = $stdetal["State"]["tax_rate"];

                $taxname = $stdetal["State"]["tax_name"];
            } else {

                $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.code ="' . $billadd["UserAddress"]["state"] . '"');

                if (!empty($stdetal["State"])) {

                    $taxperc = $stdetal["State"]["tax_rate"];

                    $taxname = $stdetal["State"]["tax_name"];
                } else {

                    $stdetal = $this->State->find('State.country_id = "' . $billadd["UserAddress"]["country"] . '" AND State.name ="' . $billadd["UserAddress"]["state"] . '"');

                    if (!empty($stdetal["State"])) {

                        $taxperc = $stdetal["State"]["tax_rate"];

                        $taxname = $stdetal["State"]["tax_name"];
                    } else {

                        $taxperc = 0;

                        $taxname = "No Tax is applicable";
                    }
                }
            }
        }

        if ($tot_price > 0) {

            $taxamt = ($taxableamt * $taxperc) / 100;

            $taxamt = number_format($taxamt, 2, ".", "");

            $tot_price = $tot_price + $taxamt;
        }

        ########################## Coupon code section ******************************************

        $discamt = 0;
        $couponcode = '';

        if ($this->Session->check('Coupon') == true) {

            $couparray = $this->Session->read('Coupon');

            $tdat = date("Y-m-d");

            if (strtotime($tdat) >= strtotime($couparray["Coupon"]["from_date"]) && strtotime($tdat) <= strtotime($couparray["Coupon"]["to_date"]) && $tot_price >= $couparray["Coupon"]["minamt"]) {

                if ($couparray["Coupon"]["type"] == "Amt") {

                    //$discamt  =   $couparray["Coupon"]["giftvalue"];

                    if ($couparray["Coupon"]["giftvalue"] >= $tot_price)
                        $discamt = $tot_price;

                    else
                        $discamt = $couparray["Coupon"]["giftvalue"];
                }else {

                    $discamt = $tot_price * ($couparray["Coupon"]["giftvalue"] / 100);
                }
            }

            $tot_price = $tot_price - $discamt;

            $order["coupon_id"] = $couparray["Coupon"]["id"];

            $order["discount"] = $discamt;

            $couponcode = $couparray["Coupon"]["code"];
        }

        ########################## Coupon code section ******************************************       ss
        ######################### End of Section to find and add tax amount......................



        //$totaltopay =     number_format($tot_price,2,".","");
        //$gtotal       =   number_format(($tot_price + $shipping_cost),2,".","");

        if ($tot_price > 0)
            $gtotal = number_format(($tot_price + $shipping_cost), 2, ".", "");

        else
            $gtotal = number_format(0.00 + $shipping_cost, 2, ".", "");


        //************Set to array

        $tot_price = $tot_price - $taxamt;
        $shipping_cost = $shipping_cost==""?0:$shipping_cost;
        $cartdetailsArray['totaltopay'] = number_format($tot_price, 2, ".", "");
        $cartdetailsArray['sessShipmeth'] = $shippingMethod;
        $cartdetailsArray['sessShipcost'] = number_format($shipping_cost, 2, ".", "");
        $cartdetailsArray['sessShipserv'] = $shippingServ;
        $cartdetailsArray['Payamount'] = number_format($gtotal, 2, ".", "");
        $cartdetailsArray['taxamt'] = number_format($taxamt, 2, ".", "");
        $cartdetailsArray['taxname'] = $taxname;
        $cartdetailsArray['discamt'] = number_format($discamt, 2, ".", "");
        $cartdetailsArray['couponcode'] = $couponcode;

        return $cartdetailsArray;
    }

    ################# Ak  payment ends here #################

}
