<?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>                      |
// +----------------------------------------------------------------------+
App::import('Sanitize');
//include("../shippingclient/fedex_label/fedex.php");
include("../shippingclient/Fedex/fedex_new.php");
require_once('../shippingclient/Fedex/library/fedex-common.php');
include("../shippingclient/usps_label/createlabel.php");
class OrdersController extends AppController {
  
    var $name = "Order";
    var $helpers = array('Html', 'Form','Pagination','Csv','xls');
    var $components = array ('Catmenu','Pagination','Upsshipping','Upsshipping', 'Authorizepayment', 'Yourpay', 'Usps', 'Xmlparser', 'Australiapost', 'Canadapost', 'Fedex', 'Googlecart', 'Googleitem', 'Bluepay'); // Added
    var $uses = array('Order','Product','Category','Productdetail','Currency','UserAddress','OrderStatus','OrderDetail','User','Cart','Cmspage','Coupon','Country','Giftcard','Customfieldvalues', 'Customfields','State');
    var $paginate = array('limit' => 25,'order' => array('Order.date' => 'desc'));

var $countryList = array(
        'AF' => 'Afghanistan',
        'AX' => 'Aland Islands',
        'AL' => 'Albania',
        'DZ' => 'Algeria',
        'AS' => 'American Samoa',
        'AD' => 'Andorra',
        'AO' => 'Angola',
        'AI' => 'Anguilla',
        'AQ' => 'Antarctica',
        'AG' => 'Antigua and Barbuda',
        'AR' => 'Argentina',
        'AM' => 'Armenia',
        'AW' => 'Aruba',
        'AU' => 'Australia',
        'AT' => 'Austria',
        'AZ' => 'Azerbaijan',
        'BS' => 'Bahamas the',
        'BH' => 'Bahrain',
        'BD' => 'Bangladesh',
        'BB' => 'Barbados',
        'BY' => 'Belarus',
        'BE' => 'Belgium',
        'BZ' => 'Belize',
        'BJ' => 'Benin',
        'BM' => 'Bermuda',
        'BT' => 'Bhutan',
        'BO' => 'Bolivia',
        'BA' => 'Bosnia and Herzegovina',
        'BW' => 'Botswana',
        'BV' => 'Bouvet Island (Bouvetoya)',
        'BR' => 'Brazil',
        'IO' => 'British Indian Ocean Territory (Chagos Archipelago)',
        'VG' => 'British Virgin Islands',
        'BN' => 'Brunei Darussalam',
        'BG' => 'Bulgaria',
        'BF' => 'Burkina Faso',
        'BI' => 'Burundi',
        'KH' => 'Cambodia',
        'CM' => 'Cameroon',
        'CA' => 'Canada',
        'CV' => 'Cape Verde',
        'KY' => 'Cayman Islands',
        'CF' => 'Central African Republic',
        'TD' => 'Chad',
        'CL' => 'Chile',
        'CN' => 'China',
        'CX' => 'Christmas Island',
        'CC' => 'Cocos (Keeling) Islands',
        'CO' => 'Colombia',
        'KM' => 'Comoros the',
        'CD' => 'Congo',
        'CG' => 'Congo the',
        'CK' => 'Cook Islands',
        'CR' => 'Costa Rica',
        'CI' => 'Cote d\'Ivoire',
        'HR' => 'Croatia',
        'CU' => 'Cuba',
        'CY' => 'Cyprus',
        'CZ' => 'Czech Republic',
        'DK' => 'Denmark',
        'DJ' => 'Djibouti',
        'DM' => 'Dominica',
        'DO' => 'Dominican Republic',
        'EC' => 'Ecuador',
        'EG' => 'Egypt',
        'SV' => 'El Salvador',
        'GQ' => 'Equatorial Guinea',
        'ER' => 'Eritrea',
        'EE' => 'Estonia',
        'ET' => 'Ethiopia',
        'FO' => 'Faroe Islands',
        'FK' => 'Falkland Islands (Malvinas)',
        'FJ' => 'Fiji the Fiji Islands',
        'FI' => 'Finland',
        'FR' => 'France, French Republic',
        'GF' => 'French Guiana',
        'PF' => 'French Polynesia',
        'TF' => 'French Southern Territories',
        'GA' => 'Gabon',
        'GM' => 'Gambia the',
        'GE' => 'Georgia',
        'DE' => 'Germany',
        'GH' => 'Ghana',
        'GI' => 'Gibraltar',
        'GR' => 'Greece',
        'GL' => 'Greenland',
        'GD' => 'Grenada',
        'GP' => 'Guadeloupe',
        'GU' => 'Guam',
        'GT' => 'Guatemala',
        'GG' => 'Guernsey',
        'GN' => 'Guinea',
        'GW' => 'Guinea-Bissau',
        'GY' => 'Guyana',
        'HT' => 'Haiti',
        'HM' => 'Heard Island and McDonald Islands',
        'VA' => 'Holy See (Vatican City State)',
        'HN' => 'Honduras',
        'HK' => 'Hong Kong',
        'HU' => 'Hungary',
        'IS' => 'Iceland',
        'IN' => 'India',
        'ID' => 'Indonesia',
        'IR' => 'Iran',
        'IQ' => 'Iraq',
        'IE' => 'Ireland',
        'IM' => 'Isle of Man',
        'IL' => 'Israel',
        'IT' => 'Italy',
        'JM' => 'Jamaica',
        'JP' => 'Japan',
        'JE' => 'Jersey',
        'JO' => 'Jordan',
        'KZ' => 'Kazakhstan',
        'KE' => 'Kenya',
        'KI' => 'Kiribati',
        'KP' => 'Korea',
        'KR' => 'Korea',
        'KW' => 'Kuwait',
        'KG' => 'Kyrgyz Republic',
        'LA' => 'Lao',
        'LV' => 'Latvia',
        'LB' => 'Lebanon',
        'LS' => 'Lesotho',
        'LR' => 'Liberia',
        'LY' => 'Libyan Arab Jamahiriya',
        'LI' => 'Liechtenstein',
        'LT' => 'Lithuania',
        'LU' => 'Luxembourg',
        'MO' => 'Macao',
        'MK' => 'Macedonia',
        'MG' => 'Madagascar',
        'MW' => 'Malawi',
        'MY' => 'Malaysia',
        'MV' => 'Maldives',
        'ML' => 'Mali',
        'MT' => 'Malta',
        'MH' => 'Marshall Islands',
        'MQ' => 'Martinique',
        'MR' => 'Mauritania',
        'MU' => 'Mauritius',
        'YT' => 'Mayotte',
        'MX' => 'Mexico',
        'FM' => 'Micronesia',
        'MD' => 'Moldova',
        'MC' => 'Monaco',
        'MN' => 'Mongolia',
        'ME' => 'Montenegro',
        'MS' => 'Montserrat',
        'MA' => 'Morocco',
        'MZ' => 'Mozambique',
        'MM' => 'Myanmar',
        'NA' => 'Namibia',
        'NR' => 'Nauru',
        'NP' => 'Nepal',
        'AN' => 'Netherlands Antilles',
        'NL' => 'Netherlands the',
        'NC' => 'New Caledonia',
        'NZ' => 'New Zealand',
        'NI' => 'Nicaragua',
        'NE' => 'Niger',
        'NG' => 'Nigeria',
        'NU' => 'Niue',
        'NF' => 'Norfolk Island',
        'MP' => 'Northern Mariana Islands',
        'NO' => 'Norway',
        'OM' => 'Oman',
        'PK' => 'Pakistan',
        'PW' => 'Palau',
        'PS' => 'Palestinian Territory',
        'PA' => 'Panama',
        'PG' => 'Papua New Guinea',
        'PY' => 'Paraguay',
        'PE' => 'Peru',
        'PH' => 'Philippines',
        'PN' => 'Pitcairn Islands',
        'PL' => 'Poland',
        'PT' => 'Portugal, Portuguese Republic',
        'PR' => 'Puerto Rico',
        'QA' => 'Qatar',
        'RE' => 'Reunion',
        'RO' => 'Romania',
        'RU' => 'Russian Federation',
        'RW' => 'Rwanda',
        'BL' => 'Saint Barthelemy',
        'SH' => 'Saint Helena',
        'KN' => 'Saint Kitts and Nevis',
        'LC' => 'Saint Lucia',
        'MF' => 'Saint Martin',
        'PM' => 'Saint Pierre and Miquelon',
        'VC' => 'Saint Vincent and the Grenadines',
        'WS' => 'Samoa',
        'SM' => 'San Marino',
        'ST' => 'Sao Tome and Principe',
        'SA' => 'Saudi Arabia',
        'SN' => 'Senegal',
        'RS' => 'Serbia',
        'SC' => 'Seychelles',
        'SL' => 'Sierra Leone',
        'SG' => 'Singapore',
        'SK' => 'Slovakia (Slovak Republic)',
        'SI' => 'Slovenia',
        'SB' => 'Solomon Islands',
        'SO' => 'Somalia, Somali Republic',
        'ZA' => 'South Africa',
        'GS' => 'South Georgia and the South Sandwich Islands',
        'ES' => 'Spain',
        'LK' => 'Sri Lanka',
        'SD' => 'Sudan',
        'SR' => 'Suriname',
        'SJ' => 'Svalbard & Jan Mayen Islands',
        'SZ' => 'Swaziland',
        'SE' => 'Sweden',
        'CH' => 'Switzerland, Swiss Confederation',
        'SY' => 'Syrian Arab Republic',
        'TW' => 'Taiwan',
        'TJ' => 'Tajikistan',
        'TZ' => 'Tanzania',
        'TH' => 'Thailand',
        'TL' => 'Timor-Leste',
        'TG' => 'Togo',
        'TK' => 'Tokelau',
        'TO' => 'Tonga',
        'TT' => 'Trinidad and Tobago',
        'TN' => 'Tunisia',
        'TR' => 'Turkey',
        'TM' => 'Turkmenistan',
        'TC' => 'Turks and Caicos Islands',
        'TV' => 'Tuvalu',
        'UG' => 'Uganda',
        'UA' => 'Ukraine',
        'AE' => 'United Arab Emirates',
        'GB' => 'United Kingdom',
        'US' => 'United States',
        'UM' => 'United States Minor Outlying Islands',
        'VI' => 'United States Virgin Islands',
        'UY' => 'Uruguay, Eastern Republic of',
        'UZ' => 'Uzbekistan',
        'VU' => 'Vanuatu',
        'VE' => 'Venezuela',
        'VN' => 'Vietnam',
        'WF' => 'Wallis and Futuna',
        'EH' => 'Western Sahara',
        'YE' => 'Yemen',
        'ZM' => 'Zambia',
        'ZW' => 'Zimbabwe'
    );


        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;

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

        $sitefolder         =   $cnfg["sitebasefolder"];

        $currency           =   $cnfg["currency"];

        $meta_description   =   $cnfg["meta_description"];

        $meta_keywords      =   $cnfg["meta_keywords"];

        $page_title         =   $cnfg["page_title"];

        $allow_fedexlabel   =   $cnfg["allow_fedexlabel"];

        global $style;

        $style              =   $cnfg["style"];

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

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

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

        $this->pageTitle = $page_title  ;

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

        $this->paginate["limit"]=$cnfg["items_perpage"]; //Setting pagination limit per page.
        //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);

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

        $this->set('sitefolder', $sitefolder);
        $httpHost   =   $_SERVER['HTTP_HOST'];
        $this->set('sitebase','http://'.$httpHost);

        global $currency;
        $curr       =   $this->Currency->findByCode($currency);
        $this->set('curlogo',utf8_encode($curr["Currency"]["logo"]));

    }

    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);
        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);
        $footer_links = $this->Cmspage->find('list',array('conditions' => array('Cmspage.type' => 'content','Cmspage.status' => 'Y')));
        $this->set('footerlinks', $footer_links);

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

    }
    
    function index() {

        $this->__validateLoginStatus();
        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);

        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {

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

            exit();

        }

        $cmbSearchType  =   "";

        $txtSearch      =   "";

        /*

        if(isset($_GET["cmbSearchType"]) && isset($_GET["txtSearch"]))
        {
                        $cmbSearchType  =   $_GET["cmbSearchType"];
                        $txtSearch      =   $_GET["txtSearch"];
                        if($cmbSearchType == "oid"){
                            $data = $this->paginate('Order', array('Order.id  = ' => addslashes($txtSearch)));
                        }elseif($cmbSearchType == "orderstatus"){
                            $data = $this->paginate('Order', array('OrderStatus.name LIKE ' => addslashes($txtSearch)));
                        }elseif($cmbSearchType == "username"){
                            $data = $this->paginate('Order', array('User.uname LIKE ' => "%".addslashes($txtSearch)."%"));
                        }elseif($cmbSearchType == "dateoforder"){
                            $dt ='0000-00-00';
                            if($txtSearch!='' && strpos($txtSearch,"-")>0)
                            {
                            list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                            if(strlen($day)==1) $day = '0'.$day;
                            if(strlen($month)==1) $month = '0'.$month;
                            $dt = $year."-".$month."-".$day; //2010-08-13
                            }
                            $data = $this->paginate('Order', array('Order.date LIKE ' => "%".($dt)."%"));
                        }
                        else{
                            $data = $this->paginate('Order'); }
        }
        else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) &&
         $this->passedArgs["txtSearch"] <> '')
        {
            $cmbSearchType  =   $this->passedArgs["cmbSearchType"];
            $txtSearch      =   $this->passedArgs["txtSearch"];
            if($cmbSearchType == "id"){
                            $data = $this->paginate('Order', array('Order.id  = ' => addslashes($txtSearch)));
                        }elseif($cmbSearchType == "orderstatus"){
                            $data = $this->paginate('Order', array('OrderStatus.name LIKE ' => addslashes($txtSearch)));
                        }elseif($cmbSearchType == "username"){
                            $data = $this->paginate('Order', array('User.uname LIKE ' => "%".addslashes($txtSearch)."%"));
                        }elseif($cmbSearchType == "dateoforder"){
                            $dt ='0000-00-00';
                            if($txtSearch!='' && strpos($txtSearch,"-")>0)
                            {
                            list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                            if(strlen($day)==1) $day = '0'.$day;
                            if(strlen($month)==1) $month = '0'.$month;
                            $dt = $year."-".$month."-".$day; //2010-08-13
                            }
                            $data = $this->paginate('Order', array('Order.date LIKE ' => "%".($dt)."%"));
                        }
                        else{
                            $data = $this->paginate('Order'); }
        }
        else{
            $data = $this->paginate('Order');
        }
        */


        if(isset($_POST["cmbSearchType"])  && $_POST["cmbSearchType"] <> '' && isset($_POST["txtSearch"]) && $_POST["txtSearch"] <> '') {
            $cmbSearchType  =   $_POST["cmbSearchType"];
            $txtSearch      =   $_POST["txtSearch"];
            if($cmbSearchType == "oid") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.id =' => addslashes($txtSearch)));
                $cond=array('Order.id =' =>  addslashes($txtSearch));
            }
            elseif($cmbSearchType == "orderstatus") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                $cond=array('OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%");
            }
            elseif($cmbSearchType == "username") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                $cond=array('USR.uname  LIKE' =>  addslashes($txtSearch)."%");
            }elseif($cmbSearchType == "dateoforder") {
                $dt ='0000-00-00';
                if($txtSearch!='' && strpos($txtSearch,"-")>0) {
                    list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                    if(strlen($day)==1) $day = '0'.$day;
                    if(strlen($month)==1) $month = '0'.$month;
                    $dt = $year."-".$month."-".$day; //2010-08-13
                }
                $cond=array('Order.date  LIKE' =>  addslashes($dt)."%");
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%"));
            }
            else {
                $cond='';
            }
        }
        else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) && $this->passedArgs["txtSearch"] <> '') {
            $cmbSearchType  =   $this->passedArgs["cmbSearchType"];
            $txtSearch      =   $this->passedArgs["txtSearch"];
            if($cmbSearchType == "oid") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.id =' => addslashes($txtSearch)));
                $cond=array('Order.id =' =>  addslashes($txtSearch));
            }
            elseif($cmbSearchType == "username") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                $cond=array('USR.uname  LIKE' =>  addslashes($txtSearch)."%");
                
            }
            elseif($cmbSearchType == "orderstatus") {
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                $cond=array('OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%");
            }elseif($cmbSearchType == "dateoforder") {
                $dt ='0000-00-00';
                if($txtSearch!='' && strpos($txtSearch,"-")>0) {
                    list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                    if(strlen($day)==1) $day = '0'.$day;
                    if(strlen($month)==1) $month = '0'.$month;
                    $dt = $year."-".$month."-".$day; //2010-08-13
                }
                $cond=array('Order.date  LIKE' =>  addslashes($dt)."%");
                //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%"));
            }
            else {
                $cond='';
            }

        }
        else {
            $cond='';
        }


        //getting table names...
        $usrtbl=$this->Order->getTableName("users");
        $statustbl=$this->Order->getTableName("order_statuses");
        $this->paginate = array(
                'conditions' => array($cond),
                'fields' => array("Order.id,Order.date,Order.total_price,Order.user_id,ORS.name,USR.uname"),
                'order' => 'Order.id DESC',
                'limit' => $this->paginate["limit"],
                'joins' => array(
                        array(
                                'table' => $usrtbl,
                                'alias' => 'USR',
                                'type' => 'LEFT',
                                'conditions'=> array('Order.user_id = USR.id')
                        ),
                        array(
                                'table' => $statustbl,
                                'alias' => 'ORS',
                                'type' => 'LEFT',
                                'conditions'=> array( 'Order.order_status_id = ORS.id')
                        )
                ),
                'group' => '',
                'passit' => $this->passedArgs
        );
        $data = $this->paginate('Order');


        $this->set('cmbSearchType', $cmbSearchType);
        $this->set('txtSearch', $txtSearch);
        $this->passedArgs['limit']=$this->paginate["limit"];
        $this->set('passedarg',$this->passedArgs);
        $this->set('odr', $data);
        $this->layout = 'adm';
    }

    function getcsv() {

        $this->__validateLoginStatus();

        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {

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

            exit();

        }

        $data   =   $this->Order->findAll();

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

        $this->layout   =   'csvexp';

    }

    function getxls() {

        $this->__validateLoginStatus();

        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {

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

            exit();

        }

        $data   =   $this->Order->findAll();

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

        $this->layout   =   'csvexp';

    }

    function details($id) {



        $this->__validateLoginStatus();
        $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {

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

            exit();

        }

        $this->Order->id = $id;

        global $currency;

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

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

        $data = $this->Order->read();

//        echo '<pre>'; print_r($data); echo '</pre>';
        
        /* Specials */
        //specials
        $specialsArr = array();
        
        if(isset($data['Order']['specials'])){
            if(!empty($data['Order']['specials'])){
               
               $specialsArr = json_decode($data['Order']['specials']);
            }
        } // End If
        
        /* End Specials */

        for($j=0;$j < sizeof($data["OrderDetail"]);$j++) {

            //$pdet =   $this->Product->findById($data["OrderDetail"][$j]["product_id"]);

            //$data["OrderDetail"][$j]["Product"]   =   $pdet["Product"];

            //Fetching the  product combination details

            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)';
            }


            if($data["OrderDetail"][$j]["type"]=='P') {
                if($pdet["Product"]["combination"]=='Y') {

                    $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);

                }   //end of if stmt..
            }
            //Fetching the  product combination details

        } // end of for loop..


        //Finding the product type in the order detail
        $ptype_flag='Non-Digital';
        $cmbtype_flag='no';
        if(count($data["OrderDetail"])>0) {
            foreach($data["OrderDetail"] as $det) {
                $ptype_flag=$det["prodtype"];
                if($det["Product"]["combination"] <> '')
                    $cmbtype_flag='yes';
            }
        }
        $this->set('ptype_flag', $ptype_flag);
        $this->set('cmbtype_flag', $cmbtype_flag);


        $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'");

        $osts   =   $this->OrderStatus->find('list',array('fields'=>array('OrderStatus.id', 'OrderStatus.name')));
        
        $this->set('specialsArr',$specialsArr);
        
        $this->set('osts', $osts);

        $this->set('odr', $data);

        if(isset($shipadd[0]["UserAddress"]))
            $this->set('ship', $shipadd[0]["UserAddress"]);

        $this->set('bill', $billadd[0]["UserAddress"]);


        //****************
           //Shipping Label


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

   

 
      
$sendorCountyryCode = (strlen($cnfg['shipping_origin_country']) > 2 ? array_search($cnfg['shipping_origin_country'], $this->countryList) : $cnfg['shipping_origin_country']); // returns true

$receiverCountyryCode = (strlen($data['Order']['ship_country']) > 2 ? array_search($data['Order']['ship_country'], $this->countryList) : $data['Order']['ship_country']);

      //echo "<br>---".$sendorCountyryCode."----".$receiverCountyryCode;  
    
    $sender = array(
                    'first' => $cnfg['site_name'],
                    'last' => '',
                    'phone' => $cnfg['shipping_origin_phone'],
                    'street' => $cnfg['shipping_origin_street'],
                    'line2' => '',
                    'city' => $cnfg['shipping_origin_city'],
                    'state' => $cnfg['shipping_origin_state'],
                    'zip' => $cnfg['shipping_origin_zip'],
                    'country' => $cnfg['shipping_origin_country']

                );

                $recipient = array(
                    'first' => $data['Order']['ship_fname'],
                    'last' => $data['Order']['ship_lname'],
                    'phone' => $data['Order']['ship_phone'],
                    'street' => $data['Order']['ship_address'],
                    'line2' => $data['Order']['ship_address'],
                    'city' => $data['Order']['ship_city'],
                    'state' => $data['Order']['ship_state'],
                    'zip' => $data['Order']['ship_zip'],
                    'country' => $receiverCountyryCode

                );
                $fedexSettings = array(
                    'shipaccount' => $cnfg['fedexshipaccno'],
                    'billaccount' => $cnfg['fedexbillaccno'],
                    'dutyaccount' => $cnfg['fedexshipaccno'],
                    'accounttovalidate' => $cnfg['fedexshipaccno'],
                    'meter' => $cnfg['fedexmeterno'],
                    'key' => $cnfg['fedexkey'],
                    'password' => $cnfg['fedexpaswd'],

                );
                $orderWeight = 5;
                //******************************

/*
$sender["first"]="GeorgeS";
$sender["last"]="S";
$sender["phone"]="13900";
$sender["street"]="230 West Monroe Street";
$sender["line2"]="Suite 630";
$sender["city"]="Chicago";
$sender["state"]="IL";
$sender["zip"]="606060";
$sender['country']="US";


$recipient["first"]="Thomas";
$recipient["last"]="S";
$recipient["phone"]="13123900";
$recipient["street"]="230 West Monroe Street";
$recipient["line2"]="Suite 630";
$recipient["city"]="Chicago";
$recipient["state"]="IL";
$recipient["zip"]="606060";
$recipient['country']="US";

$fedexSettings['key']="VH9gpVObdc0EvOIQ";
$fedexSettings['password']="wQYp3s0PqmZYSM9piA7EdvWhJ";
$fedexSettings['shipaccount']="510088000";
$fedexSettings['meter']="100022250";
$fedexSettings['billaccount']="510088000";
$data['Order']['shipping_method']='FEDEX';
*/
                //******************


           // echo $data['Order']['shipping_method'];

                $uspsSettings = array(
                           'USPS_Username' => $cnfg['USPS_Username'],
                           'Weight' => $orderWeight
                        );
                $labelimage = "/img/No-Labels-image.jpg";
                $templabel = "";
                switch ($data['Order']['shipping_method']) {
                    case 'FEDEX':   

                    $templabel =  getfedexShippingLabel($sender, $recipient,$fedexSettings);
                    echopre($templabel);
                        break;
                    case 'USPS':
                        $uspsSettings = array(
                           'USPS_Username' => $cnfg['USPS_Username']
                        );
                        $templabel =  getuspsShippingLabel($sender, $recipient,$uspsSettings);
                        break;

                    default: $templabel =  "No-Labels-image.jpg";
                       // getfedexShippingLabel($sender, $recipient,$fedexSettings);
                        break;
                }


                if($templabel == 'error' || $templabel != "CODexpressreturnlabel.png"){
                    $labelimage = "/img/No-Labels-image.jpg";
                }else{
                    $labelimage =  "/img/".$templabel;
                }

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



        //*****************



        $this->layout = 'adm';

    }

    function change_status($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");
        }
        
        $this->__validateLoginStatus();
        $admsess = $this->Session->read('Admin');

        if($admsess["orders"] <> 1){
            $this->redirect(array('controller' => 'admins', 'action' => 'index'));
            exit();
        }

        $oid = $_POST["order_status"];
        if($oid){
            $re= $this->Order->changeStatus($id,$oid);
            if(!empty($re)){  
                $this->Session->setFlash('Order Status Changed Successfully.');
                $this->Order->id = $id;
                $data = $this->Order->read();

                for($j=0;$j < sizeof($data["OrderDetail"]);$j++){
                    $pdet   = $this->Product->findById($data["OrderDetail"][$j]["product_id"]);
                    $data["OrderDetail"][$j]["Product"] = $pdet["Product"];
                }

                //print_r($data); exit;

                $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;

                $ship   =   $shipadd[0]["UserAddress"];

                $bill   =   $billadd[0]["UserAddress"];

                $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 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>

              </tr>

              <tr>

                <td>".

                        $odr['OrderStatus']['name']."

                </td>

                <td>";



                $dt = strtotime($odr['Order']['date']);

                $content .= date('Y-m-d',$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>

        <td><strong>Quantity</strong></td>

        <td><strong>Unit Price</strong></td>

        <td><strong>Price</strong></td>

      </tr>

      <tr>

        <td colspan='2'>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>";



                $amt=0;

                //print_r($odr);exit;

                foreach($odr['OrderDetail'] as $det) {

                    $price = $det['product_price']*$det['quantity'];

                    $amt = $amt +($det['product_price']*$det['quantity']);

                    $content .= " <tr>

        <td colspan='2'>". $det['Product']['pname']."</td>

        <td> ".$det['quantity']." </td>

        <td> ".$det['product_price']." </td>

        <td>". $price." </td>

      </tr>

      <tr>

        <td colspan='2' height='15'>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>";

                }

                $content .= "</table>

    </td>

      </tr>

      <tr>

        <td width='50%'>

        <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>

              <tr>

                <td><strong>Transaction Id</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['transaction_id']." </td>

              </tr>

            </table>

        </td></tr>

        </table>



    </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>Shipping Price</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['shipping_price']." </td>

              </tr>

               <tr>

                <td><strong>Tax Price</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['tax_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><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'] .",".  $odr['Order']['ship_state']." </td>

      </tr>

      <tr>

        <td> ".$odr['Order']['ship_country']."  - ".$odr['Order']['ship_zip']." </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>

    </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']." ,".  $odr['Order']['bill_state'] ."</td>

      </tr>

      <tr>

        <td>". $odr['Order']['bill_country'] ." - ".$odr['Order']['bill_zip']." </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>

    </table> ";

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



                $subject        = "Order Status Changed 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 status change 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>";

                $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);

                //echo $mailcontent; exit;

                //$mailcontent  =   "Hi ".$user["uname"].", <br> Thank you for registering with ".$cnfg["site_name"]."<br> Thanks and Regards, <br> Administrator";

                //$mailcontentad    =   "Hi Admin, <br> ".$user["uname"]." registered  with ".$cnfg["site_name"]."<br> Thanks and Regards, <br> ".$user["uname"];

                //$mailsent         = mail($odr['User']['email'],$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(trim($odr['User']['email']), ""); 
                    $mail->Send();
                    /******************************* MAIL TO THE USER ****************************/ 
                    
                /*#################################### EMAIL SEGMENT ###############################*/

            }else {

                $this->Session->setFlash('Order Status Can\'t Change now .');

            }

        }

        $this->redirect(array('controller' => 'orders', 'action' => 'details/'.$id));

        exit;

    }

    function change_status_user($id) {

        $this->__validateLoginStatus('U');

        $oid = $_POST["order_status"];

        if($oid) {

            $re= $this->Order->changeStatus($id,$oid);

            if(!empty($re)) {

                $this->Session->setFlash('Order Status Changed Successfully.');

            }else {

                $this->Session->setFlash('Order Status Can\'t Change now .');

            }

        }

        $this->redirect(array('controller' => 'orders', 'action' => 'userorderdetails/'.$id));

        exit;

    }

    function __validateLoginStatus($typ='A') {

        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 delete($id) {

        $this->__validateLoginStatus();

        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {


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

            exit();

        }

        $this->Order->delete_order($id);

        $this->flash(' Order Removed from Database.', '/users');

        $this->redirect('index');
        $this->Session->setFlash('Selected Order(s)deleted successfully.');
        //$this->flash(' Order Removed from Database.', '/users');
    }
      
        ################ Function to view the orders placed by user######################

        function myorder() {
            $this->__validateLoginStatus('U');
            $sus        =   $this->Session->read('Userlog');
            global $currency;
            $curr       =   $this->Currency->findByCode($currency);
            $this->set('curlogo',utf8_encode($curr["Currency"]["logo"]));
            $this->set('sus', $sus);
            $user_id    =   $sus["id"];
            $cmbSearchType  =   "";
            $txtSearch      =   "";
            if(isset($_POST["cmbSearchType"])  && $_POST["cmbSearchType"] <> '' && isset($_POST["txtSearch"]) && $_POST["txtSearch"] <> '') {
                $cmbSearchType  =   $_POST["cmbSearchType"];
                $txtSearch      =   trim($_POST["txtSearch"]);
                if($cmbSearchType == "oid") {
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.id =' => addslashes($txtSearch)));
                    $cond=array('Order.user_id =' =>$user_id,'Order.id =' =>  addslashes($txtSearch));
                }
                elseif($cmbSearchType == "orderstatus") {
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                    $cond=array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%");
                }elseif($cmbSearchType == "dateoforder") {
                    $dt ='0000-00-00';
                    if($txtSearch!='' && strpos($txtSearch,"-")>0) {
                        list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                        if(strlen($day)==1) $day = '0'.$day;
                        if(strlen($month)==1) $month = '0'.$month;
                        $dt = $year."-".$month."-".$day; //2010-08-13
                    }
                    $cond=array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%");
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%"));
                }
                else {
                    $cond='Order.user_id ='.$user_id;
                }
            }
            else if(isset($this->passedArgs["cmbSearchType"]) && isset($this->passedArgs["txtSearch"]) &&
                    $this->passedArgs["txtSearch"] <> '') {
                $cmbSearchType  =   $this->passedArgs["cmbSearchType"];
                $txtSearch      =   trim($this->passedArgs["txtSearch"]);
                if($cmbSearchType == "oid") {
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.id =' => addslashes($txtSearch)));
                    $cond=array('Order.user_id =' =>$user_id,'Order.id =' =>  addslashes($txtSearch));
                }
                elseif($cmbSearchType == "orderstatus") {
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%"));
                    $cond=array('Order.user_id =' =>$user_id,'OrderStatus.name  LIKE' =>  addslashes($txtSearch)."%");
                }elseif($cmbSearchType == "dateoforder") {
                    $dt ='0000-00-00';
                    if($txtSearch!='' && strpos($txtSearch,"-")>0) {
                        list ($month, $day, $year) = split ("-", $txtSearch); //08-12-2010
                        if(strlen($day)==1) $day = '0'.$day;
                        if(strlen($month)==1) $month = '0'.$month;
                        $dt = $year."-".$month."-".$day; //2010-08-13
                    }
                    $cond=array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%");
                    //$data = $this->paginate('Order', array('Order.user_id =' =>$user_id,'Order.date  LIKE' =>  addslashes($dt)."%"));
                }
                else {
                    $cond='Order.user_id ='.$user_id;
                }

            }
            else {
                $cond='Order.user_id ='.$user_id;
            }


            //getting table names...
            $statustbl=$this->Order->getTableName("order_statuses");
            $this->paginate = array(
                    'conditions' => array($cond),
                    'fields' => array("Order.id,Order.date,Order.total_price,ORS.name"),
                    'order' => 'Order.id DESC',
                    'limit' => $this->paginate["limit"],
                    'joins' => array(
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => $this->passedArgs
            );
            $data = $this->paginate('Order');


            $this->set('cmbSearchType', $cmbSearchType);
            $this->set('txtSearch', $txtSearch);
            $this->passedArgs['limit']=$this->paginate["limit"];
            $this->set('passedarg',$this->passedArgs);
            $this->set('odr', $data);

        }

        function userorderdetails($id) {
            
            $this->__validateLoginStatus('U');

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

            global $currency;

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

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

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

            $this->Order->id = $id;

            $data = $this->Order->read();
            //print '<pre />';print_r($data);
            /* Specials */
            //specials
            $specialsArr = array();

            if(isset($data['Order']['specials'])){
                if(!empty($data['Order']['specials'])){

                   $specialsArr = json_decode($data['Order']['specials']);
                }
            } // End If

            /* End Specials */

            for($j=0;$j < sizeof($data["OrderDetail"]);$j++) {

                //$pdet =   $this->Product->findById($data["OrderDetail"][$j]["product_id"]);

                //$data["OrderDetail"][$j]["Product"]   =   $pdet["Product"];

                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)';
                }

                //Fetching the  product combination details
                if($data["OrderDetail"][$j]["type"]=='P') {
                    if($pdet["Product"]["combination"]=='Y') {

                        $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);

                    }
                } //end of if stmt..

                //Fetching the  product combination details

            } //end of for Loop..

            //Finding the product type in the order detail
            $ptype_flag='Non-Digital';
            if(count($data["OrderDetail"])>0) {
                foreach($data["OrderDetail"] as $det) {
                    $ptype_flag=$det["prodtype"];
                }
            }
            $this->set('ptype_flag', $ptype_flag);


            $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'");

            $this->set('specialsArr', $specialsArr);
            $this->set('odr', $data);

           //Shipping Label


        //****************
           //Shipping Label


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

    $sender = array(
                    'first' => $cnfg['site_name'],
                    'last' => '',
                    'phone' => $cnfg['shipping_origin_phone'],
                    'street' => $cnfg['shipping_origin_street'],
                    'line2' => '',
                    'city' => $cnfg['shipping_origin_city'],
                    'state' => $cnfg['shipping_origin_state'],
                    'zip' => $cnfg['shipping_origin_zip'],
                    'country' => $cnfg['shipping_origin_country']

                );

                $recipient = array(
                    'first' => $data['Order']['ship_fname'],
                    'last' => $data['Order']['ship_lname'],
                    'phone' => $data['Order']['ship_phone'],
                    'street' => $data['Order']['ship_address'],
                    'line2' => $data['Order']['ship_address'],
                    'city' => $data['Order']['ship_city'],
                    'state' => $data['Order']['ship_state'],
                    'zip' => $data['Order']['ship_zip'],
                    'country' => $data['Order']['ship_country']

                );
                $fedexSettings = array(
                    'shipaccount' => $cnfg['fedexshipaccno'],
                    'billaccount' => $cnfg['fedexbillaccno'],
                    'dutyaccount' => $cnfg['fedexshipaccno'],
                    'accounttovalidate' => $cnfg['fedexshipaccno'],
                    'meter' => $cnfg['fedexmeterno'],
                    'key' => $cnfg['fedexkey'],
                    'password' => $cnfg['fedexpaswd'],

                );
                $orderWeight = 5;
                //******************************


/*$sender["first"]="GeorgeS";
$sender["last"]="S";
$sender["phone"]="13900";
$sender["street"]="230 West Monroe Street";
$sender["line2"]="Suite 630";
$sender["city"]="Chicago";
$sender["state"]="IL";
$sender["zip"]="606060";
$sender['country']="US";


$recipient["first"]="Thomas";
$recipient["last"]="S";
$recipient["phone"]="13123900";
$recipient["street"]="230 West Monroe Street";
$recipient["line2"]="Suite 630";
$recipient["city"]="Chicago";
$recipient["state"]="IL";
$recipient["zip"]="606060";
$recipient['country']="US";

$fedexSettings['key']="VH9gpVObdc0EvOIQ";
$fedexSettings['password']="wQYp3s0PqmZYSM9piA7EdvWhJ";
$fedexSettings['shipaccount']="510088000";
$fedexSettings['meter']="100022250";
$fedexSettings['billaccount']="510088000";*/


                //******************





                $uspsSettings = array(
                           'USPS_Username' => $cnfg['USPS_Username'],
                           'Weight' => $orderWeight
                        );
                $labelimage = "/img/No-Labels-image.jpg";
                $templabel = "";
                switch ($data['Order']['shipping_method']) {
                    case 'FEDEX':   $templabel =  getfedexShippingLabel($sender, $recipient,$fedexSettings);
                        break;
                    case 'USPS':
                        $uspsSettings = array(
                           'USPS_Username' => $cnfg['USPS_Username']
                        );
                        $templabel =  getuspsShippingLabel($sender, $recipient,$uspsSettings);
                        break;

                    default: $templabel =  "No-Labels-image.jpg";
                        getfedexShippingLabel($sender, $recipient,$fedexSettings);
                        break;
                }


                if($templabel == 'error' || $templabel != "CODexpressreturnlabel.png"){
                    $labelimage = "/img/No-Labels-image.jpg";
                }else{
                    $labelimage =  "/img/".$templabel;
                }

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

                

        }

        ########### Function to place an order from admin side...............

        function addadminorder() {

            $this->__validateLoginStatus();

            $admsess    =   $this->Session->read('Admin');

            if($admsess["orders"] <> 1) {

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

                exit();

            }

            $uslist     =   $this->User->find('list',array('fields'=>array('User.id','User.uname')));

            $prlist     =   $this->Product->find('list',array('fields'=>array('Product.id', 'Product.pname'),'conditions' =>'Product.stock > 0'));

            $this->set('usrlist', $uslist);

            $this->set('prdlist', $prlist);

            $this->layout = 'adm';

            if (!empty($this->data)) {

                foreach($this->data["product_id"] as $pid) {

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

                    $dat["user_id"] =   $this->data["user_id"];

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

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

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

                        $dat["product_id"]      =   $pid;

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

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

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

                        $dat["quantity"]        =   1;

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

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

                        }else {

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

                        }

                    }

                }

                $this->redirect('/carts/showadmincart/'.$dat["user_id"]);

                exit;

            }

        }



        ############# Function to download digital product ....................................

        function pdctdownload($oid = 0 , $pid = 0) {

            $this->__validateLoginStatus('U');

            if($oid <> 0 && $pid <> 0) {

                $this->Order->id = $oid;

                $data = $this->Order->read();

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

                $user_id                        =   $sus["id"];

                if($user_id == $data["Order"]["user_id"]) {

                    if($data["Order"]["exp_time"]  > date("Y-m-d H:i:s")) {

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

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

                            $filename   =   $pdata["Product"]["pdctfile"];

                            //header('Content-type: application/zip');



                            // It will be called the file to download file

                            //header("Content-Disposition: attachment; filename=".$filename);



                            // The source file

                            //readfile("/img/products/".$filename);



                            $this->Order->changeStatus($oid,3);

                            if($filename <> '') {
                                $this->redirect('/Orders/tesdownload/'.$filename);
                                exit;
                            }
                            else {
                                $this->Session->setFlash('Sorry,There is no file to download.!');
                            }

                        }

                    }else {

                        $this->Session->setFlash('Sorry,The download time for this order is expired!');



                    }

                }else {

                    $this->Session->setFlash('Sorry, You are not authorrized to download the product. Please contact Administrator.!');

                }

            }

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

            exit;

        }

        function tesdownload($filename) {

            $this->view = 'Media';

            $this->__validateLoginStatus('U');

            $nfname =   explode(".",$filename);

            $params = array(

                    'id' => $filename,

                    'name' => $nfname[0],

                    'download' => true,

                    'extension' => $nfname[1],

                    'path' => 'webroot'.DS.'img'.DS.'products' . DS

            );

            $this->set($params);

        }



        ############## Function to reset download expiry date for digital products by admin........................................

        function reset_exp_date($id) {

            $this->__validateLoginStatus();

            $admsess    =   $this->Session->read('Admin');

            if($admsess["orders"] <> 1) {

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

                exit();

            }

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

            $tm                         =   time()+ $cnfg["digitalproduct_download_limit"] * 60 * 60;

            $exptm                          =   date("Y-m-d H:i:s",$tm);

            $this->Order->resetexpdate($id,$exptm);

            $this->redirect('/Orders/details/'.$id);

            exit;

        }

        ################### Function to add note on an order by admin...............................

        function addnote($id) {

            $this->__validateLoginStatus();

            $admsess    =   $this->Session->read('Admin');

            if($admsess["orders"] <> 1) {

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

                exit();

            }

            $not = $_POST["note"];

            if($id) {

                $re= $this->Order->addnote($id,$not);

                if(!empty($re)) {

                    $this->Session->setFlash('Order Note Updated Successfully.');

                }else {

                    $this->Session->setFlash('Order Note Can\'t Update now .');

                }

            }

            $this->redirect('/Orders/details/'.$id);

            exit;

        }

        ################### Function to add note on an order by admin...............................

        function addcomment($id) {

            $this->__validateLoginStatus();

            $admsess    =   $this->Session->read('Admin');

            if($admsess["orders"] <> 1) {

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

                exit();

            }

            $cmnt = $_POST["comment"];

            if($id) {

                $re= $this->Order->addcomment($id,$cmnt);

                if(!empty($re)) {

                    $this->Session->setFlash('Comments Updated Successfully.');

                }else {

                    $this->Session->setFlash('Comments Can\'t Update now .');

                }

            }

            $this->redirect('/Orders/details/'.$id);

            exit;

        }



        ##########################################################################################################
        ################################ Function to generate shipping label for FEDEX###########################
        ##########################################################################################################
        function fedexlabel($orderid='') {

            $ord_res=$this->Order->findById($orderid);
            $user_id=$ord_res["User"]["id"];

            //Deleting the pdf file if alredy exists
            /*(
        $this->Order->id = $orderid;
        $old_pdf=$ord_res["Order"]["label_pdf"];
        if(file_exists(WWW_ROOT.'Fedex/shipping_label/'.$old_pdf))
        unlink(WWW_ROOT.'Fedex/shipping_label/'.$old_pdf);
        $this->Order->saveField('tracking_no','');
        $this->Order->saveField('label_pdf','');


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


              /*Generating Fedex Labels*/
            //include(WWW_ROOT."Fedex/fedex-common.php");
            $path_to_wsdl=WWW_ROOT.'Fedex/ShipService_v8.wsdl';
            //$vshipping_name             = str_replace(' ','_',strtoupper($ord_res["Order"]["shipping_service"]));
            //$vshipping_name             = str_replace(' ','_',strtoupper('FedEx Priority Overnight'));
            /*
                if($vshipping_name!='FEDEX_GROUND') {
                $vshipping_name             = str_replace('FEDEX_','',$vshipping_name);
                }

                //$vshipping_name=strtoupper("FEDEX2DAY");  */

            $array_ReplaceWith=array("EUROPE_FIRST_INTERNATIONAL_PRIORITY",
                    "FEDEX_1_DAY_FREIGHT",
                    "FEDEX_2_DAY",
                    "FEDEX_2_DAY_FREIGHT",
                    "FEDEX_3_DAY_FREIGHT",
                    "FEDEX_EXPRESS_SAVER",
                    "FEDEX_GROUND",
                    "FIRST_OVERNIGHT",
                    "GROUND_HOME_DELIVERY",
                    "INTERNATIONAL_ECONOMY",
                    "INTERNATIONAL_ECONOMY_FREIGHT",
                    "INTERNATIONAL_FIRST",
                    "INTERNATIONAL_PRIORITY",
                    "INTERNATIONAL_PRIORITY_FREIGHT",
                    "PRIORITY_OVERNIGHT",
                    "STANDARD_OVERNIGHT");

            $array_Replace=array("EUROPE_FIRST_INTERNATIONAL_PRIORITY",
                    "FedEx Overnight Freight",
                    "FedEx 2 Day",
                    "FedEx 2 day Freight",
                    "FedEx 3 day Freight",
                    "FedEx Express Saver",
                    "FedEx Ground",
                    "FedEx First Overnight",
                    "FedEx Home Delivery",
                    "FedEx International Economy",
                    "INTERNATIONAL_ECONOMY_FREIGHT",
                    "FedEx International First",
                    "FedEx International Priority",
                    "INTERNATIONAL_PRIORITY_FREIGHT",
                    "FedEx Priority Overnight",
                    "FedEx Standard Overnight");

            $vshipping_name             = $ord_res["Order"]["shipping_service"];



            //Replace shipping service with proper naming
            $vshipping_name=str_replace($array_Replace,$array_ReplaceWith,$vshipping_name);

            $recipient_name             = $ord_res["Order"]["ship_fname"]." ".$ord_res["Order"]["ship_lname"];
            $recipient_company          = '';
            $recipient_phone            = $ord_res["Order"]["ship_phone"];
            $recipient_address          = $ord_res["Order"]["ship_address"];
            $recipient_city             = $ord_res["Order"]["ship_city"];
            //$recipient_state              = $pck_res["Packet"]["ship_state"];

            //$statedet                 =   $this->State->findByName($pck_res["Packet"]["ship_state"]);
            $recipient_state            =   $ord_res["Order"]["ship_state"];
            //$recipient_state          =   'CA';

            $recipient_postcode         =   $ord_res["Order"]["ship_zip"];
            //$recipient_postcode       =   '90001';

            //$recipient_country        = $pck_res["Packet"]["ship_country"];
            $cntdet                     =   $this->Country->findByCountryName($ord_res["Order"]["ship_country"]);
            $recipient_country          =   $cntdet["Country"]["country_iso_code_2"];
            $delivery_place_residential = 'false';


            /*
                $recipient_name             = 'fghgf hgfh';
                $recipient_company          = '';
                $recipient_phone            = '456546';
                $recipient_address          = 'gfhgf';
                $recipient_city             = 'gfhgf';
                $recipient_state            =   'AL';
                $recipient_postcode         =   '35060';
                $recipient_country          =   'US';
                $delivery_place_residential = 'false';
                echo "<br>".$recipient_name ;
                echo "<br>".$recipient_company;
                echo "<br>".$recipient_phone;
                echo "<br>".$recipient_address;
                echo "<br>".$recipient_city;
                echo "<br>".$recipient_state;
                echo "<br>".$recipient_postcode;
                echo "<br>".$recipient_country;
            */

            //Shipper Address Details
            $shipper_name           = 'Shipper Name';
            $shipper_company        = 'Shipper Company';
            $shipper_phone          = '713-932-6901';
            //$shipper_phone        = '404-299-0842'; //Original phone
            $shipper_address        = '1325 Remington Rd, Suite R';
            $shipper_city           = 'Schaumburg';
            $shipper_state          = 'IL';
            $shipper_postcode       = '60173';
            $shipper_pick_up_zip    = '60173';
            $shipper_country        = 'US';
            //Shipper Address Details


            /*Working FEDEX Credentials
                $key='VH9gpVObdc0EvOIQ';
                $password='wQYp3s0PqmZYSM9piA7EdvWhJ';
                $shipAccount='510088000';
                $meter='100022250';
                $billAccount='510088000';
                $dutyAccount='';
                Working FEDEX Credentials */

            /*Working FEDEX Credentials
                $width = '20';
                $height = '10';
                $length = '20';
                $units = '10';
                $weight = '50';
                Working FEDEX Credentials */

            $cnfg        = Configure::read('Neutrino');
            $key         = $cnfg["fedexkey"];
            $password    = $cnfg["fedexpaswd"];
            $shipAccount = $cnfg["fedexshipaccno"];
            $meter       = $cnfg["fedexmeterno"];
            $billAccount = $cnfg["fedexbillaccno"];
            $dutyAccount ='';

            $width = $_POST["fed_width"];
            $height = $_POST["fed_height"];
            $length = $_POST["fed_length"];
            $units = $_POST["fed_units"];
            $weight = $_POST["fed_weight"];


            ini_set("soap.wsdl_cache_enabled", "0");
            $client = new SoapClient($path_to_wsdl, array('trace' => true)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
            $request['WebAuthenticationDetail'] = array('UserCredential' =>
                    array('Key' => $key, 'Password' => $password));
            $request['ClientDetail'] = array('AccountNumber' => $shipAccount, 'MeterNumber' => $meter);
            $request['TransactionDetail'] = array('CustomerTransactionId' => '*** Express Domestic Shipping Request v8 using PHP ***');
            $request['Version'] = array('ServiceId' => 'ship', 'Major' => '8', 'Intermediate' => '0', 'Minor' => '0');

            $request['RequestedShipment'] = array('ShipTimestamp' => date('c'),
                    'DropoffType' => 'REGULAR_PICKUP', // valid values REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER and STATION
                    /*              'ServiceType' => strtoupper(str_replace(' ','_',$vshipping_name)),// valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... */
                    'ServiceType' => strtoupper($vshipping_name),// valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
                    'PackagingType' => 'YOUR_PACKAGING', // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
                    'TotalWeight' => array('Value' => $weight, 'Units' => 'LB'), // valid values LB and KG
                    'Shipper' => array('Contact' => array('PersonName' => $shipper_name,
                                    'CompanyName' => $shipper_company,
                                    'PhoneNumber' => $shipper_phone),
                            'Address' => array('StreetLines' => array($shipper_address),
                                    'City' => $shipper_city,
                                    'StateOrProvinceCode' => $shipper_state,
                                    'PostalCode' => $shipper_postcode,
                                    'CountryCode' => $shipper_country)),
                    'Recipient' => array('Contact' => array('PersonName' => $recipient_name ,
                                    'CompanyName' => $recipient_company,
                                    'PhoneNumber' => $recipient_phone),
                            'Address' => array('StreetLines' => array($recipient_address),
                                    'City' => $recipient_city,
                                    'StateOrProvinceCode' => $recipient_state,
                                    'PostalCode' => $recipient_postcode,
                                    'CountryCode' => $recipient_country),
                            'Residential' => $delivery_place_residential),
                    'ShippingChargesPayment' => array('PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
                            'Payor' => array('AccountNumber' => $billAccount,
                                    'CountryCode' => 'US')),
                    /*

                                          'InternationalDetail' => array('DutiesPayment' => array('PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
                                                                                                  'Payor' => array('AccountNumber' => $dutyAccount,
                                                                                                                   'CountryCode' => 'CA')),
                                                                         'DocumentContent' => 'DOCUMENTS_ONLY',
                                                                         'TermsOfSale' => 'CFR_OR_CPT', // valid values CFR_OR_CPT, CIF_OR_CIP, DDP, DDU, EXW and FOB_OR_FCA
                                                                         'CustomsValue' => array('Amount' => 100.00, 'Currency' => 'USD'),
                                                                         'Commodities' => array('0' => array('NumberOfPieces' => 1,
                                                                                                             'Description' => 'Books',
                                                                                                             'CountryOfManufacture' => 'US',
                                                                                                             'Weight' => array('Value' => 1.0, 'Units' => 'LB'), // valid values LB and KG
                                                                                                             'Quantity' => 1,
                                                                                                             'QuantityUnits' => 'EA',
                                                                                                             'UnitPrice' => array('Amount' => 1.000000, 'Currency' => 'USD'),
                                                                                                             'CustomsValue' => array('Amount' => 100.000000, 'Currency' => 'USD'))),
                                                                   'ExportDetail' => array('B13AFilingOption' => 'FILED_ELECTRONICALLY')),

                    */



                    'SpecialServicesRequested' => array(),
                    'LabelSpecification' => array('LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
                            'ImageType' => 'PDF',  // valid values DPL, EPL2, PDF, ZPLII and PNG
                            'LabelStockType' => 'PAPER_7X4.75'),
                    'RateRequestTypes' => array('ACCOUNT'), // valid values ACCOUNT and LIST
                    'PackageCount' => 1,
                    'PackageDetail' => 'INDIVIDUAL_PACKAGES',
                    'RequestedPackageLineItems' => array('0' => array('Weight' => array('Value' => $weight,
                                            'Units' => 'LB'))));
            /*
                echo "<pre>";
                print_r($request['RequestedShipment']);
                                echo "</pre>";
                //exit();
            */

            try {
                $response = $client->processShipment($request);  // FedEx web service invocation

                if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') {
                    $tracking_no=$response->CompletedShipmentDetail->CompletedPackageDetails->AstraLabelElements[5]->Content;
                    $pdftrackno=str_replace(" ", "",$tracking_no);
                    /*
                if(is_object($response->CompletedShipmentDetail->CodReturnDetail)) {
                $fp = fopen(WWW_ROOT.'Fedex/shipping_label/'.SHIP_CODLABEL, 'w+');
                fwrite($fp, $response->CompletedShipmentDetail->CodReturnDetail->Label->Parts->Image); //Create COD Return PNG or PDF file
                fclose($fp);
                }
                    */
                    define('SHIP_LABEL',$pdftrackno.'_label.pdf');  // PNG label file. Change to file-extension .pdf for creating a PDF label (e.g. shiplabel.pdf)
                    //define('SHIP_CODLABEL',$pckid.'_returnlabel.pdf');  // PNG label file. Change to file-extension .pdf for creating a PDF label (e.g. CODexpressreturnlabel.pdf)
                    $fp = fopen(WWW_ROOT.'Fedex/shipping_label/'.SHIP_LABEL, 'w+');
                    fwrite($fp, $response->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image); //Create PNG or PDF file
                    fclose($fp);

                    // Inserting the Trackinh number and PDF path
                    $this->Order->id = $ord_res["Order"]["id"];
                    $this->Order->saveField('tracking_no',$tracking_no);
                    $this->Order->saveField('label_pdf',SHIP_LABEL);

                }
                else {
                    $res=printError($client, $response);
                    //print_r($res);exit;
                    $cnt=   count($res);
                    $errMSGFromFedex="";
                    if($cnt>1) {
                        $errMSGFromFedex="The following error(s) has been returned from FedEx server<hr width='75%' align='left'><br>";
                        for ( $counter = 0; $counter <= $cnt-1; $counter += 1) {
                            $errMSGFromFedex.=   $res[$counter]->LocalizedMessage."<br>";
                        }
                    }elseif($cnt == 1) {
                        $errMSGFromFedex="The following error(s) has been returned from FedEx server<hr width='75%' align='left'><br>";
                        $errMSGFromFedex.=   $res->LocalizedMessage."<br>";
                    }else {
                        $errMSGFromFedex="The following error(s) has been returned from FedEx server<hr width='75%' align='left'><br>";
                        $errMSGFromFedex.=   $res."<br>";
                    }

                    if($errMSGFromFedex<>"") {
                        $errMSGFromFedex= $errMSGFromFedex.'Shipping label can\'t be created.';
                    }else {
                        $errMSGFromFedex= 'Shipping Label Cannot be Created.';
                    }

                    $this->Session->setFlash(__($errMSGFromFedex, true));
                    $this->redirect(array('controller' => 'orders', 'action' => 'details/'.$orderid));
                }

                //writeToLog($client);    // Write to log file

            } catch (SoapFault $exception) {
                printFault($exception, $client);
            }

            /*Generate Labels*/
            $this->Session->setFlash(__('Shipping Label Created Successfully.', true));
            $this->redirect(array('controller' => 'orders', 'action' => 'details/'.$orderid));
            exit();
        }


        ##########################################################################################################
        ################################ Function to generate shipping label ends here ###########################
        ##########################################################################################################

        ##########################################################################################################
        ################################ Function to download shipping label starts here ###########################
        ##########################################################################################################


        function dwnldlabel($file='') {
            $file_path=WWW_ROOT.'Fedex/shipping_label/'.$file;
            $pdfdat =   file_get_contents($file_path);
            header("Content-type: application/octet-stream");
            header("Content-Transfer-Encoding: binary");
            header("Content-Disposition: attachment; filename=\"$file\"");
            echo $pdfdat;
            exit;
        }

        ##########################################################################################################
        ################################ Function to download shipping label ends here ###########################
        ##########################################################################################################


        ##########################################################################################################
        ################################ Function to edit order details starts here ###########################
        ##########################################################################################################
        function editorder($id,$type='') {
            $this->__validateLoginStatus();
            $admsess    =   $this->Session->read('Admin');
            if($type=='ship') {
                $this->Order->id = $id;
                $this->Order->saveField('ship_fname',$_POST["editship_fname"]);
                $this->Order->saveField('ship_lname',$_POST["editship_lname"]);
                $this->Order->saveField('ship_address',$_POST["editship_address"]);
                $this->Order->saveField('ship_city',$_POST["editship_city"]);
                $this->Order->saveField('ship_state',$_POST["editship_state"]);
                $this->Order->saveField('ship_country',$_POST["editship_country"]);
                $this->Order->saveField('ship_zip',$_POST["editship_zip"]);
                $this->Order->saveField('ship_phone',$_POST["editship_phone"]);
                $this->Order->saveField('ship_mobile',$_POST["editship_mobile"]);
                $this->Order->saveField('ship_fax',$_POST["editship_fax"]);
            }
            if($type=='bill') {
                $this->Order->id = $id;
                $this->Order->saveField('bill_fname',$_POST["editbill_fname"]);
                $this->Order->saveField('bill_lname',$_POST["editbill_lname"]);
                $this->Order->saveField('bill_address',$_POST["editbill_address"]);
                $this->Order->saveField('bill_city',$_POST["editbill_city"]);
                $this->Order->saveField('bill_state',$_POST["editbill_state"]);
                $this->Order->saveField('bill_country',$_POST["editbill_country"]);
                $this->Order->saveField('bill_zip',$_POST["editbill_zip"]);
                $this->Order->saveField('bill_phone',$_POST["editbill_phone"]);
                $this->Order->saveField('bill_mobile',$_POST["editbill_mobile"]);
                $this->Order->saveField('bill_fax',$_POST["editbill_fax"]);
            }
            else if($type=='qty') {
                if(isset($_POST["hidtotcnt"])) {
                    for($i=1;$i<=$_POST["hidtotcnt"];$i++) {
                        $rowid=$_POST["row_id".$i];
                        $updqty=$_POST["edit_qty".$i];
                        $this->OrderDetail->id =  $rowid;
                        $this->OrderDetail->saveField('quantity',$updqty);
                    }
                }
            }
            $this->redirect(array('controller' => 'orders', 'action' => 'details/'.$id));
            exit();
        }






        //User Activity Report
        function useractivity() {
            $cnfg               =   Configure::read('Neutrino');
            $style              =   $cnfg["style"];
            $this->set('style', "admin/".$style);
            $ordtbl=$this->Order->getTableName("orders");
            if(isset($_POST["uid"]) && $_POST["uid"] <> '') {
                $uid=$_POST["uid"];
            }
            else if(isset($this->passedArgs["uid"]) &&  $this->passedArgs["uid"] <> '') {
                $uid=$this->passedArgs["uid"];
            }
            else {
                $minid=$this->Order->query("SELECT min(user_id) as default_id FROM ".$ordtbl);
                if(isset($minid) && empty($minid)===false)
                    $uid=$minid[0][0]["default_id"];
                else
                    $uid=0;
            }

            $ostbl=$this->Order->getTableName("order_statuses");
            $this->paginate = array(
                    'conditions' => array("Order.user_id='".$uid."'"),
                    'fields' => array("DATE_FORMAT(Order.date,'%m-%d-%Y')as ord_date ,Order.user_id,Order.ship_fname,Order.ship_lname,Order.ship_address, Order.ship_city, Order.ship_state, Order.ship_country, Order.ship_zip, Order.ship_phone,
             Order.ship_mobile, Order.ship_fax,Order.bill_fname, Order.bill_lname, Order.bill_address, Order.bill_city,
             Order.bill_state, Order.bill_country, Order.bill_zip, Order.bill_phone, Order.bill_mobile, Order.bill_fax,Order.total_price,vos.name"),
                    'order' => '',
                    'limit' => $this->paginate["limit"],
                    'joins' => array(
                            array(
                                    'table' => $ostbl,
                                    'alias' => 'vos',
                                    'type' => 'LEFT',
                                    'conditions'=> array('vos.id=Order.order_status_id')
                            )
                    ),
                    'group' => 'Order.id',
                    'passit' => $this->passedArgs
            );

            $reportdet = $this->paginate('Order');
            $this->set('reportdet',$reportdet);
            $usersList =$this->User->findAll();
            $this->set('usersList',$usersList);
            $this->passedArgs['limit']=$this->paginate["limit"];
            $this->set('passedarg',$this->passedArgs);
            $this->set('uid',$uid);
            $this->layout = 'adm';
        }

        //User Order Report
        function reports() {

            $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
            $sales_min_date=explode(" ",$this->Order->getSalesDates("min"));
//            $sales_max_date=explode(" ",$this->Order->getSalesDates("max"));
            $sales_max_date[0]  = date("m-d-Y");
            $this->set('dflt_mindate', $sales_min_date[0]); //Setting the max date for the calendar...
            $this->set('dflt_maxdate', $sales_max_date[0]); //Setting the max date for the calendar...

            if(isset($_POST["sales_fdate"]) &&  isset($_POST["sales_fdate"]) && $_POST["sales_tdate"]<>'' && $_POST["sales_tdate"]<>'') {
                $frmdate=$_POST["sales_fdate"];
                $todate=$_POST["sales_tdate"];
            }
            else if(isset($this->passedArgs["frmdate"]) && isset($this->passedArgs["todate"]) &&
                    $this->passedArgs["frmdate"] <> '' &&  $this->passedArgs["todate"] <> '') {
                $frmdate=$this->passedArgs["frmdate"];
                $todate= $this->passedArgs["todate"];
            }
            else {
                $frmdate=$sales_min_date[0];
                $todate=$sales_max_date[0];
            }
            //$cttbl=$this->Report->getTableName("users");
            $reportdet = array();
            if(isset($frmdate) && $frmdate <> '' && isset($todate) && $todate <> '') {

                $sdate=explode('-',$frmdate);
                $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
                $tdate=explode('-',$todate);
                $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

                //$cttb2=$this->User->getTableName("user_addresses");
                //getting table names...

                $ordtbl=$this->Order->getTableName("orders");
                $usrtbl=$this->Order->getTableName("users");
                $cpntbl=$this->Order->getTableName("coupons");
                $statustbl=$this->Order->getTableName("order_statuses");

                //getting table names...





                $this->paginate = array(
                        'conditions' => array("DATE_FORMAT(Order.date,'%Y-%m-%d')>= '".$srch_fdate."' AND
            DATE_FORMAT(Order.date,'%Y-%m-%d') <= '".$srch_tdate."'"),
                        'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                        'order' => 'Order.date DESC',
                        'limit' => $this->paginate["limit"],
                        'joins' => array(
                                array(
                                        'table' => $usrtbl,
                                        'alias' => 'USR',
                                        'type' => 'INNER',
                                        'conditions'=> array('Order.user_id = USR.id')
                                ),
                                array(
                                        'table' => $cpntbl,
                                        'alias' => 'CPN',
                                        'type' => 'LEFT',
                                        'conditions'=> array('Order.coupon_id = CPN.id')
                                ),
                                array(
                                        'table' => $statustbl,
                                        'alias' => 'ORS',
                                        'type' => 'LEFT',
                                        'conditions'=> array( 'Order.order_status_id = ORS.id')
                                )
                        ),
                        'group' => '',
                        'passit' => $this->passedArgs
                );

            }
            $reportdet = $this->paginate('Order');
            $this->set('reportdet',$reportdet);
            $this->set('mindate', $frmdate);
            $this->set('maxdate', $todate);
            $this->passedArgs['limit']=$this->paginate["limit"];
            $this->set('passedarg',$this->passedArgs);
            $this->layout = 'adm';

        }

        function salesxls() {
            //getting table names...
            $ordtbl=$this->Order->getTableName("orders");
            $usrtbl=$this->Order->getTableName("users");
            $cpntbl=$this->Order->getTableName("coupons");
            $statustbl=$this->Order->getTableName("order_statuses");
            //getting table names...


            /*
            $sdate=explode('-',$frmdate);
            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
            $tdate=explode('-',$todate);
            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];
            */

            $qry = array(
                    'conditions' => array(""),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => '',
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $tot_cnt=count($this->Order->find('all', $qry));

            $this->paginate = array(
                    'conditions' => array(""),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => $tot_cnt,
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $data = $this->paginate('Order');
            $this->set('data', $data);
            $this->layout = 'csvexp';
        }


        function salescsv() {
            //getting table names...
            $ordtbl=$this->Order->getTableName("orders");
            $usrtbl=$this->Order->getTableName("users");
            $cpntbl=$this->Order->getTableName("coupons");
            $statustbl=$this->Order->getTableName("order_statuses");
            //getting table names...

            /*
        $cttbl=$this->Report->getTableName("users");
            $sdate=explode('-',$frmdate);
            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
            $tdate=explode('-',$todate);
            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];
            */

            $qry = array(
                    'conditions' => array(""),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => '',
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $tot_cnt=count($this->Order->find('all', $qry));

            $this->paginate = array(
                    'conditions' => array(""),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => $tot_cnt,
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $data = $this->paginate('Order');
            $this->set('data', $data);
            $this->layout = 'csvexp';
        }



        //User Order Report
        function pcreports() 
        {
            $cnfg               =   Configure::read('Neutrino');
        $style              =   $cnfg["style"];
        $this->set('style', "admin/".$style);
            $sales_min_date=explode(" ",$this->Order->getSalesDates("min"));
//            $sales_max_date=explode(" ",$this->Order->getSalesDates("max"));
            $sales_max_date[0]  = date("m-d-Y");
            $this->set('dflt_mindate', $sales_min_date[0]); //Setting the max date for the calendar...
            $this->set('dflt_maxdate', $sales_max_date[0]); //Setting the max date for the calendar...

            if(isset($_POST["sales_fdate"]) &&  isset($_POST["sales_fdate"]) && $_POST["sales_tdate"]<>'' && $_POST["sales_tdate"]<>'') {
                $frmdate=$_POST["sales_fdate"];
                $todate=$_POST["sales_tdate"];
            }
            else if(isset($this->passedArgs["frmdate"]) && isset($this->passedArgs["todate"]) &&
                    $this->passedArgs["frmdate"] <> '' &&  $this->passedArgs["todate"] <> '') {
                $frmdate=$this->passedArgs["frmdate"];
                $todate= $this->passedArgs["todate"];
            }
            else {
                $frmdate=$sales_min_date[0];
                $todate=$sales_max_date[0];
            }
            //$cttbl=$this->Report->getTableName("users");
            $reportdet = array();
            if(isset($frmdate) && $frmdate <> '' && isset($todate) && $todate <> '') {

                $sdate=explode('-',$frmdate);
                $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
                $tdate=explode('-',$todate);
                $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

                //$cttb2=$this->User->getTableName("user_addresses");
                //getting table names...

                $ordtbl=$this->Order->getTableName("orders");
                $usrtbl=$this->Order->getTableName("users");
                $cpntbl=$this->Order->getTableName("coupons");
                $statustbl=$this->Order->getTableName("order_statuses");

                //getting table names...





               $this->paginate = array(
                        'conditions' => array("DATE_FORMAT(Order.date,'%Y-%m-%d')>= '".$srch_fdate."' AND
                        DATE_FORMAT(Order.date,'%Y-%m-%d') <= '".$srch_tdate."' AND Order.coupon_id <> 0"),
                        'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                        'order' => 'Order.date DESC',
                        'limit' => $this->paginate["limit"],
                        'joins' => array(
                                array(
                                        'table' => $usrtbl,
                                        'alias' => 'USR',
                                        'type' => 'INNER',
                                        'conditions'=> array('Order.user_id = USR.id')
                                ),
                                array(
                                        'table' => $cpntbl,
                                        'alias' => 'CPN',
                                        'type' => 'LEFT',
                                        'conditions'=> array('Order.coupon_id = CPN.id')
                                ),
                                array(
                                        'table' => $statustbl,
                                        'alias' => 'ORS',
                                        'type' => 'LEFT',
                                        'conditions'=> array( 'Order.order_status_id = ORS.id')
                                )
                        ),
                        'group' => '',
                        'passit' => $this->passedArgs
                );

            } 
            
            /* $this->paginate = array(
                        'conditions' => array("DATE_FORMAT(Order.date,'%Y-%m-%d')>= '".$srch_fdate."' AND
                        DATE_FORMAT(Order.date,'%Y-%m-%d') <= '".$srch_tdate."' AND Order.discount <> 0"),
                        'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                        'order' => 'Order.date DESC',
                        'limit' => $this->paginate["limit"],
                        'joins' => array(
                                array(
                                        'table' => $usrtbl,
                                        'alias' => 'USR',
                                        'type' => 'INNER',
                                        'conditions'=> array('Order.user_id = USR.id')
                                ),
                                array(
                                        'table' => $cpntbl,
                                        'alias' => 'CPN',
                                        'type' => 'LEFT',
                                        'conditions'=> array('Order.coupon_id = CPN.id')
                                ),
                                array(
                                        'table' => $statustbl,
                                        'alias' => 'ORS',
                                        'type' => 'LEFT',
                                        'conditions'=> array( 'Order.order_status_id = ORS.id')
                                )
                        ),
                        'group' => '',
                        'passit' => $this->passedArgs
                );

            }*/


            $reportdet = $this->paginate('Order');
            $this->set('reportdet',$reportdet);
            $this->set('mindate', $frmdate);
            $this->set('maxdate', $todate);
            $this->passedArgs['limit']=$this->paginate["limit"];
            $this->set('passedarg',$this->passedArgs);
            $this->layout = 'adm';
        }


        function pcodecsv() {
            //getting table names...
            $ordtbl=$this->Order->getTableName("orders");
            $usrtbl=$this->Order->getTableName("users");
            $cpntbl=$this->Order->getTableName("coupons");
            $statustbl=$this->Order->getTableName("order_statuses");
            //getting table names...

            /*
        $cttbl=$this->Report->getTableName("users");
            $sdate=explode('-',$frmdate);
            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
            $tdate=explode('-',$todate);
            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];
            */

            $qry = array(
                    'conditions' => array("Order.coupon_id <> 0"),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => '',
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $tot_cnt=count($this->Order->find('all', $qry));

            $this->paginate = array(
                    'conditions' => array("Order.coupon_id <> 0"),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => $tot_cnt,
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $data = $this->paginate('Order');
            $this->set('data', $data);
            $this->layout = 'csvexp';
        }

        function pcodexls() {
            //getting table names...
            $ordtbl=$this->Order->getTableName("orders");
            $usrtbl=$this->Order->getTableName("users");
            $cpntbl=$this->Order->getTableName("coupons");
            $statustbl=$this->Order->getTableName("order_statuses");
            //getting table names...

            /*
        $cttbl=$this->Report->getTableName("users");
            $sdate=explode('-',$frmdate);
            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
            $tdate=explode('-',$todate);
            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];
            */

            $qry = array(
                    'conditions' => array("Order.coupon_id <> 0"),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => '',
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $tot_cnt=count($this->Order->find('all', $qry));

            $this->paginate = array(
                    'conditions' => array("Order.coupon_id <> 0"),
                    'fields' => array("Order.id,Order.date,USR.uname,Order.total_price, Order.discount,CPN.code,ORS.name"),
                    'order' => 'Order.date DESC',
                    'limit' => $tot_cnt,
                    'joins' => array(
                            array(
                                    'table' => $usrtbl,
                                    'alias' => 'USR',
                                    'type' => 'INNER',
                                    'conditions'=> array('Order.user_id = USR.id')
                            ),
                            array(
                                    'table' => $cpntbl,
                                    'alias' => 'CPN',
                                    'type' => 'LEFT',
                                    'conditions'=> array('Order.coupon_id = CPN.id')
                            ),
                            array(
                                    'table' => $statustbl,
                                    'alias' => 'ORS',
                                    'type' => 'LEFT',
                                    'conditions'=> array( 'Order.order_status_id = ORS.id')
                            )
                    ),
                    'group' => '',
                    'passit' => ''
            );
            $data = $this->paginate('Order');
            $this->set('data', $data);
            $this->layout = 'xlsexp';
        }

        function placeorder() {

            $this->__validateLoginStatus();
            $cnfg               =   Configure::read('Neutrino');
            $style              =   $cnfg["style"];
            $this->set('style', "admin/".$style);

            $admsess    =   $this->Session->read('Admin');

            if($admsess["orders"] <> 1) {

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

                exit();

            }

            /*************** User Details ******************/
            //$this->User->unbindModel(array('hasMany' => array('UserAddress'))); /* This code line unbinds model related to parent model not specifically with 'hasMany' but with any relation */

            $userData = $this->User->find('all', array('order' => array('User.uname ASC')));
            
            $userAutoItem = $this->User->formatUserforAutocomplete($userData);
            
            $this->set('userAutoItem', $userAutoItem);
            /*************** User Details ******************/
            /*************** Shipping Details ******************/
            $cnfg               =   Configure::read('Neutrino');
            $i = 0;
            $shipmentmethods=array();
            if($cnfg["shipping_require_australia"]  ==  "Y") {
                $shipmentmethods[$i]    =   "Australiapost";
                $i++;
            }

            if($cnfg["shipping_require_canada"] ==  "Y") {
                $shipmentmethods[$i]    =   "Canadapost";
                $i++;
            }

            if($cnfg["shipping_require_fedex"]  ==  "Y") {
                $shipmentmethods[$i]    =   "FEDEX";
                $i++;
            }

            if($cnfg["shipping_require"]    ==  "Y") {
                $shipmentmethods[$i]    =   "UPS";
                $i++;
            }

            if($cnfg["shipping_require_usps"]   ==  "Y") {
                $shipmentmethods[$i]    =   "USPS";
                $i++;
            }

            if($cnfg["fflat_shipping_require"]  ==  "Y") {
                $shipmentmethods[$i]    =   $cnfg["flat_ship_name"];
                $i++;
            }

            if($cnfg["sflat_shipping_require"]  ==  "Y") {
                $shipmentmethods[$i]    =   $cnfg["secflat_ship_name"];
                $i++;
            }

            if($cnfg["tflat_shipping_require"]  ==  "Y") {
                $shipmentmethods[$i]    =   $cnfg["thirdflat_ship_name"];
                $i++;
            }

            if($cnfg["foflat_shipping_require"] ==  "Y") {
                $shipmentmethods[$i]    =   $cnfg["forthflat_ship_name"];
                $i++;
            }

            $this->set('shipmentMethods', $shipmentmethods);

            /*************** Shipping Details ******************/

            /*************** Shipping Flat Rate ******************/
            $flat_shipping_first = $cnfg["flat_shipping_first"];
            $this->set('flatShippingFirst', $flat_shipping_first);

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

            /*************** Shipping Flat Rate ******************/

            /*************** Currency Symbol ******************/
            global $currency;

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

            $this->set('curlogo',utf8_encode($curr["Currency"]["logo"]));
            $this->set('currencySymbol',utf8_encode($curr["Currency"]["logo"]));
            $this->set('currencyCode', $curr["Currency"]["code"]); //

            /*************** Currency Symbol ******************/
            /*************** Order Status ********************/
            $osts   =   $this->OrderStatus->find('list',array('fields'=>array('OrderStatus.id', 'OrderStatus.name')));
            $this->set('osts', $osts);
            /*************** Order Status ********************/

            /*************** Posted values ********************/



            $order = array();

            if(isset($_POST['Submit'])) {
//            echo '<pre>';
//            print_r($_POST);
//            echo '</pre>';
                // User Id
                $userId = $_POST['userId'];
                // Promo code Details
                $couponArr = array();
                $promoCode = $_POST['promoCode'];
                $totalDiscount = $_POST['totalDiscount'];
                $couponArr = $this->Coupon->getCouponDetails($promoCode);
                $couponId = NULL;
                if(!empty($couponArr)) {
                    $couponId = $couponArr[0]['c']['id'];
                }
                //

                $order["coupon_id"] = $couponId;
                $order["discount"] = $totalDiscount;
                $order["date"] = date("Y-m-d H:i:s");
                $order["user_id"] = $userId;

                // Product type of order
                $prodtype = $_POST['orderProductType'];

                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"] = $_POST['shipOptionMethod'];
                }

                $order["shipping_service"] = $_POST['shipOptionTitle'];
                $order["shipping_price"] = $_POST['shipOptionCost'];

                // The type
                $order["tax_price"] = $_POST['totalTax'];
                $order["tax_name"] = $_POST['taxOptionName'];
                $order["total_price"] = $_POST['grandTotal']; // grandTotal
                $order["order_status_id"] = $_POST['orderStatus']; // orderStatus

                // Shipping Info

                if ($prodtype <> "Digital") {

                    $order["ship_fname"] = $_POST['editship_fname'];

                    $order["ship_lname"] = $_POST['editship_lname'];

                    $order["ship_address"] = $_POST['editship_address'];

                    $order["ship_city"] = $_POST['editship_city'];

                    $order["ship_state"] = $_POST['editship_state'];

                    $order["ship_country"] = $_POST['editship_country'];

                    $order["ship_zip"] = $_POST['editship_zip'];

                    $order["ship_phone"] = $_POST['editship_phone'];

                    $order["ship_mobile"] = $_POST['editship_mobile'];

                    $order["ship_fax"] = $_POST['editship_fax'];
                }

                // Transaction Id
                $order["transaction_id"] = "-";

                $order["bill_fname"] = $_POST['editbill_fname'];

                $order["bill_lname"] = $_POST['editbill_lname'];

                $order["bill_address"] = $_POST['editbill_address'];

                $order["bill_city"] = $_POST['editbill_city'];

                $order["bill_state"] = $_POST['editbill_state'];

                $order["bill_country"] = $_POST['editbill_country'];

                $order["bill_zip"] = $_POST['editbill_zip'];

                $order["bill_phone"] = $_POST['editbill_phone'];

                $order["bill_mobile"] = $_POST['editbill_mobile'];

                $order["bill_fax"] = $_POST['editbill_fax'];

                $order["payment_method"] = "";

                if(isset($_POST['credits']) && $_POST['credits']=='Y'){
                    $order["payment_method"] = "Credits";
                    
                    //Deduct user credits
                    $this->User->updateUserCredits($userId, $_POST['grandTotal']);
                }

                $order["currency_type"] = $_POST['currencyCode'];

                // Specials /

                $specialsCount = 0;
                // extraBillCost
                $specialsArr = array();
                $specialcost = 0;

                $order["specials"] = '';
                $order["special_price"] = '';

                if(isset($_POST['extraBillDetail'])) {
                    $specialsCount = count($_POST['extraBillDetail']);
                    if($specialsCount > 0) {
                        for($i=0;$i<$specialsCount;$i++) {

                            $specialsArr[] = array('note' => $_POST['extraBillDetail'][$i],
                                    'cost' => $_POST['extraBillCost'][$i]);

                            $specialcost += $_POST['extraBillCost'][$i];
                        }

                        $order["specials"] = json_encode($specialsArr);
                        $order["special_price"] = $specialcost;
                    }
                }

                $order["order_type"] = "P";
                //

                $order["note"] = $_POST['note'];
                $order["comments"] = $_POST['comment'];

                $this->Order->save($order);

                $order_id = $this->Order->id;

                //echo '<pre>'; print_r($_POST); echo '</pre>';
                
                
                
               
                
                
                if(isset($_POST['productId'])) {
                    if(!empty($_POST['productId'])) {
                        $j = 0;
                        
                        foreach($_POST['productId'] as $item) {
                            $this->OrderDetail->create($odet = array());

                            $odet["order_id"] = $order_id;

                            $odet["product_id"] = $item;

                            $odet["product_price"] = $_POST['uPrice'][$j];

                            $odet["prodtype"] = $_POST['productType'][$j]; //

                            $odet["discount_type"] = $_POST['dType'][$j]; //

                            $odet["discount"] = $_POST['dValue'][$j]; //

                            $odet["extra_price"] = $_POST['aPrice'][$j]; //

                            $odet["quantity"] = $_POST['qty'][$j]; //

                            if(!empty($_POST['optionId'][$j])) {
                                $odet["combination_id"] = $_POST['optionId'][$j];

                                if(!is_numeric($odet["combination_id"]))
                                {
                                        $odet["combination_id"] = 0;
                                }
                            }

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

                            $odet["price_type"] = $_POST['priceType'][$j];

                            $this->OrderDetail->save($odet);

                            
                            // Update Quantity in case of combination
                            if ($_POST['optionId'][$j] > 0 ) {

                                $this->Product->updatecombnstock($item, $_POST['optionId'][$j], $_POST['qty'][$j]);

                                $prodid[] = $item;
                                

                            } else if ($_POST['optionId'][$j] == 0 || $_POST['optionId'][$j] == '') { // Update Quantity in case of product without combination

                                $this->Product->updatestock($item, $_POST['qty'][$j]);
                                
                            }

                            //check if reorder level has been breached
                            $reorder_breached = $this->Product->threshold_breached($item);
                            if($reorder_breached <> 0) {
                                $this->sendMailReorderAlert($item);
                            }

                            $j++;
                            
                        } // End Foreach
                    }
                }

                    
                $dataOrderArr = $this->Order->read();               
                          
                $this->__generateOrderNotification($dataOrderArr);

                $this->Session->setFlash('Your order has been successfully placed and an e-mail with order details has sent to uers\'s e-mail ID!!');                 

               $this->redirect(array('controller' => 'orders', 'action' => 'index'));

              
               
                //$this->redirect('/orders/');
                exit;
            } // End Post


            $this->layout = 'adm';


        } // End placeorder

        function productfill() {

            Configure::write('debug', 0);

            $this->layout = null;

            global $currency;

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

            $currencySymbol = utf8_encode($curr["Currency"]["logo"]);

            $userID = $_POST["userid"];

            $productDataArr = $this->Product->productDetails();

            $userDataArr = array();

            if(!empty($userID)) {
                $userDataArr = $this->User->findById($userID);
            }

//    echo '<pre>';
//     print_r($userDataArr);
//    echo '</pre>';


            $dataArr = array();
            if(!empty($productDataArr)) {
                foreach($productDataArr as $item) {

//            echo '<pre>';
//            print_r($item);
//            echo '</pre>';
                    $itemArr = $itemArrApnd = array();

                    $productName = $reorderLevel = $skuNo = NULL;
                    $productFile = $priceType = NULL;

                    $price = $discountPrice = $discountValue = $discountAmount = $additionalPrice = $totalPrice = 0.00;
                    $discountType = NULL;

                    $productName .= $item['p']['pname']; // Product Name
                    $reorderLevel = $item['p']['reorderlevel']; // Product reorder level
                    $skuNo = $item['p']['skuno']; // Product skuno
                    $productFile = $item['p']['pdctfile']; // Product File

                    // Product Stock
                    $stock = $item['p']['stock'];
                    $price = $item['p']['price']; // Retail price
                    $priceType = 'R';

                    if(!empty($userDataArr) && $userDataArr['User']['usertype'] == 'wholesale') { // Wholesale Price
                        $price = $item['p']['wholesale_price'];
                        $priceType = 'W';
                    } // End If

                    //Unit Price
                    $unitPrice = $price;

                    // Combination Details
                    if($item['p']['combination']=='Y') {
                        $productName .=' [';
                        $productName .= $item['cf']['custom_name'];
                        $productName .=' - ';
                        $productName .= $item['cv']['custom_value'];
                        $productName .=']';

                        //Extra Price calculation
                        $price += $item['pd']['extraprice'];
                        $additionalPrice = $item['pd']['extraprice'];
                        // Combination Stock
                        $stock = $item['pd']['stock'];
                        // Combination reorder level
                        $reorderLevel = $item['pd']['reorderlevel']; // Combination reorder level
                        // Combination skuno
                       $skuNo   = $item['pd']['skuno']; // Combination skuno
                        // Combination Product File
                        $productFile = $item['p']['pdctfile']; // Combination Product File
                    }
                    
                    if($item['p']['combination']=='Y') {
                        $item['p']['combination'] = $item['cv']['custom_value'];
                        
                         //$item['p']['skuno'] = $item['pd']['skuno'];
                    }

                    // Total Price
                    $totalPrice = $price;

                    // Discount Price
                    if($item['p']['wholesale_price'] > 0 || $item['p']['price'] > 0 ) { // price - will be considered as retail price
                        if(isset($item['p']['discount_type']) && $item['p']['discount'] > 0) {
                            $discountType = $item['p']['discount_type'];
                            $discountValue = $item['p']['discount'];
                            switch($discountType) {
                                case 'amnt':
                                    $discountAmount = $discountValue;
                                    $discountPrice = $price - $discountAmount;

                                    break;
                                case 'per':
                                    $discountAmount = ($price * ($discountValue/100));
                                    $discountPrice = $price - $discountAmount;
                                    break;
                            } // End Function
                            $totalPrice = $discountPrice;
                        }
                    } // End If

                    if(!empty($stock) && $stock > 0) {

                        $itemArr = array('id' => $item['p']['id'],
                                'value' => $productName,
                                'pname' => $productName,
                                'category_id' => $item['p']['category_id'],
                                'descr' => $item['p']['descr'],
                                'combination' => $item['p']['combination'],
                                'currencySymbol' => $currencySymbol,
                                'priceType' => $priceType,
                                'unitPrice' => $unitPrice,
                                'additionalPrice' => $this->Product->formatToPrice($additionalPrice),
                                'price' => $this->Product->formatToPrice($price),
                                'wholesale_price' => $this->Product->formatToPrice($item['p']['wholesale_price']),
                                'discount_type' => $discountType,
                                'discountValue' => $this->Product->formatToPrice($discountValue),
                                'discountAmount' => $this->Product->formatToPrice($discountAmount),
                                'discountPrice' => $this->Product->formatToPrice($discountPrice),
                                'totalPrice' => $this->Product->formatToPrice($totalPrice),
                                'stock' => $stock,
                                'reorderlevel' => $reorderLevel,
                                'skuno' =>  $item['pd']['skuno'],
                                'weight' => $item['p']['weight'],
                                'shipping_price' => $item['p']['shipping_price'],
                                'status' => $item['p']['status'],
                                'pdctfile' => $productFile,
                                'prodtype' => $item['p']['prodtype'],
                                'optionId' => $item['pd']['id'],
                                'cname' => $item['c']['cname'],
                                'imagename' => $item['pi']['imagename'],
                                'default_img' => $item['pi']['default_img'],
                                'custom_value' => $item['cv']['custom_value'],
                                'custom_name' => $item['cf']['custom_name']);

                        $itemArrApnd = array('itemArr'=> json_encode($itemArr));

                        $dataArr[]=array_merge($itemArr, $itemArrApnd);
                        // $dataArr[]=$itemArr;
                    } else {
                        continue;
                    }

                } // End Foreach
            } // End If


            echo json_encode($dataArr);
            exit();


        } // End Function

        function promocodecheck() {

            Configure::write('debug', 0);

            $this->layout = null;

            $promoCode = $_POST["code"];

            $priceTotal = $_POST["price"];

            $couponArr = $this->Coupon->getCouponDetails($promoCode);

            $flag = 0; // Invalid Coupon Code

            $errMsg = 'Invalid Promo Code';

            $discountAmount = 0;

            if(!empty($couponArr)) {

                /*
        $couponArr[0]['c']['id'];
        $couponArr[0]['c']['code'];
        $couponArr[0]['c']['type'];
        $couponArr[0]['c']['giftvalue'];
        $couponArr[0]['c']['from_date'];
        $couponArr[0]['c']['to_date'];
        $couponArr[0]['c']['status'];
        $couponArr[0]['c']['descr'];
        $couponArr[0]['c']['minamt'];
        $couponArr[0][0]['expired'];
                */

                if($couponArr[0][0]['expired']==0) {
                    if($priceTotal >= $couponArr[0]['c']['minamt']) {
                        $flag=1; // Valid coupon
                        $errMsg = '';
                        if($couponArr[0]['c']['type']== "Amt") {

                            if($couparray["Coupon"]["giftvalue"] > $priceTotal)
                                $discountAmount =   $priceTotal;
                            else
                                $discountAmount =   $couponArr[0]['c']['giftvalue'];
                        }
                        else {
                            $discountAmount =   $priceTotal * ($couponArr[0]['c']['giftvalue'] / 100);
                        }
                    } else {
                        $flag = 3; // Price Less than Min Amount
                        $errMsg = "Total Price less than Minimum applicable amount for Promocode";
                    }
                } else {
                    $flag = 2; // Expired
                    $errMsg = "Promocode Expired";
                }




            }

            $dataArr = array('flag' => $flag,
                    'discount' => $this->Product->formatToPrice($discountAmount),
                    'errorMsg' => $errMsg);

            echo json_encode($dataArr);
            exit();

        } // End Function

        function dotaxation() {

            Configure::write('debug', 0);

            $this->layout = null;

            $priceTotal = $_POST["price"];

            $shippingAmount = $_POST["shipping"];

            $userId = $_POST["user"];

            $prod_type = $_POST["prdtype"];

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

            $taxAmount = $taxPercent = 0;

            $taxName = '';


            if($cnfg["taxto"] == "gtotal") {
                $taxableAmt = $priceTotal+$shippingAmount;

            } else {
                $taxableAmt = $priceTotal;
            }

            $taxableAdd = array();

            $stateDetail = array();
           
            //Tax options
            if($cnfg["tax_option"]=="notax") {
                $taxPercent = 0;
                $taxName = "No tax is applicable";
            } else if($cnfg["tax_option"]=="fixedtax") {
                $taxPercent = $cnfg["fixedtax_rate"];
                $taxName = ucfirst($cnfg["fixedtax_name"]);
            } else {
                // Choose Taxable address
                if ($cnfg["taxable_address"] == "shipping") {
                    if (trim($prod_type) == 'Digital') {
                        $taxableAdd = $this->UserAddress->find('UserAddress.user_id = ' . $userId . ' AND UserAddress.addr_type = "Billing"');
                    } else {
                        $taxableAdd = $this->UserAddress->find('UserAddress.user_id = ' . $userId . ' AND UserAddress.addr_type = "Shipping"');
                    }
                }
                else {
                    $taxableAdd = $this->UserAddress->find('UserAddress.user_id = ' . $userId . ' AND UserAddress.addr_type = "Billing"');
                }

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

                if (isset($stateDetail["State"])) {

                    $taxPercent = $stateDetail["State"]["tax_rate"];
                    $taxName = $stateDetail["State"]["tax_name"];

                } else {

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

                    if (isset($stateDetail["State"])) {

                        $taxPercent = $stateDetail["State"]["tax_rate"];
                        $taxName = $stateDetail["State"]["tax_name"];

                    } else {

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


                        if (isset($stateDetail["State"])) {
                            $taxPercent = $stateDetail["State"]["tax_rate"];
                            $taxName = $stateDetail["State"]["tax_name"];

                        } else {
                            $taxPercent = 0;
                            $taxName = "No tax is applicable";
                        }
                    }
                }

            }

            if($taxPercent > 0) {
                $taxAmount = ($taxableAmt > 0) ? (($taxableAmt * $taxPercent) / 100) : 0;
            }

            $dataArr = array('taxPercent' => $this->Product->formatToPrice($taxPercent),
                    'taxName' => $taxName,
                    'taxAmount' => $this->Product->formatToPrice($taxAmount));



            echo json_encode($dataArr);
            exit();
        } // End Function

        function doshippingcalculation() {

            Configure::write('debug', 0);

            $this->layout = null;

            // User Id
            $user_id = $_POST['user'];
            
            $cnfg = Configure::read('Neutrino');

            // Shipment Method
            $shipmeth = NULL;

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

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

            // Shipping weight
            $shipweight = $_POST['weight'];

            // Shipping charge
            $shipchrge = $_POST['charge'];

            //Quantity
            $qty = $_POST['qty'];

            //Product Type
            $prodtype = $_POST['prodtype'];

            $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"];

            $shipchrgeadd = 0;

            $shipflag = 'yes';

            $bxno = 1; // Defaullt Box value

            $shipweight2 = $shipweight / $bxno;

            while ($shipweight2 > 149) {

                $bxno++;

                $shipweight2 = $shipweight / $bxno;
            }

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

            $shipweight2 = ($shipweight2 == 0) ? 0.1 : $shipweight2;

            $module_shipping_ups_types = '1DM, 1DML, 1DA, 1DAL, 1DAPI, 1DP, 1DPL, 2DM, 2DML, 2DA, 2DAL, 3DS, GND, STD, XPR, XPRL, XDM, XDML, XPD';
            if($cnfg["shipping_origin_city"]!=''){
                 $origin_city = $cnfg["shipping_origin_city"];
            }else{
                $origin_city = $cnfg["shipping_origin_state"];
            }   
            
            $origin_country = $cnfg["shipping_origin_country"];

            $origin_postal = $cnfg["shipping_origin_zip"];

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

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

            $prod = ($destination_country == 'CA') ? 'STD' : 'GNDRES';

            $shipoption = NULL;
            $first_item = NULL;
            $additional_item = NULL;
            $pshipchrg = NULL;
            $flatArr = array();


            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) {
                    $shipoption = $shipopt;
                    $shipflag = "yes";
                    //$this->set('shipopt', $shipopt);
                    //$this->set('shipflag', 'yes');
                } else {

                    $flatArr = $this->__setFlateRate($qty);

                    $shipoption = $flatArr['shipopt'];
                    $first_item = $flatArr['first_item'];
                    $additional_item = $flatArr['additional_item'];
                    $pshipchrg = $flatArr['pshipchrg'];
                    $shipflag = "no";
                     $shipmeth = 'Flat Rate Shipping';
                      $shipmeth = $shipoption[0]['title'];

                    //$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("20008");
                #$usps->setOrigZip("10022");

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

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

                ############# These parts has to make dynamic from dbtable###################3333
                //$Weight = $shipweight;
                //$this->Usps->setWeight($Weight , 0);

                $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) {
                    $shipoption = $MailArray;
                    $shipflag = "yes";
                    //$this->set('shipopt', $MailArray);
                    //$this->set('shipflag', 'yes');
                } else {

                    $flatArr = $this->__setFlateRate($qty);

                    $shipoption = $flatArr['shipopt'];
                    $first_item = $flatArr['first_item'];
                    $additional_item = $flatArr['additional_item'];
                    $pshipchrg = $flatArr['pshipchrg'];
                    $shipflag = "no";
                    
                     $shipmeth = 'Flat Rate Shipping';
                     
                     $shipmeth = $shipoption[0]['title'];

                    //$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) {
                    $shipoption = $auspost;
                    $shipflag = "yes";
//                $this->set('shipopt', $auspost);
//                $this->set('shipflag', 'yes');
                } else {

                    $flatArr = $this->__setFlateRate($qty);

                    $shipoption = $flatArr['shipopt'];
                    $first_item = $flatArr['first_item'];
                    $additional_item = $flatArr['additional_item'];
                    $pshipchrg = $flatArr['pshipchrg'];
                    $shipflag = "no";
                    
                     $shipmeth = 'Flat Rate Shipping';
                     $shipmeth = $shipoption[0]['title'];

//                $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) {
                    $shipoption = $capost;
                    $shipflag = "yes";
//                $this->set('shipopt', $capost);
//                $this->set('shipflag', 'yes');
                } else {

                    $flatArr = $this->__setFlateRate($qty);

                    $shipoption = $flatArr['shipopt'];
                    $first_item = $flatArr['first_item'];
                    $additional_item = $flatArr['additional_item'];
                    $pshipchrg = $flatArr['pshipchrg'];
                    $shipflag = "no";
                    //print '<pre />';print_r($shipoption);exit;
                    $shipmeth = $shipoption[0]['title'];

//                $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'; 

                
                /*

              $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';
                
                
                  $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);
            $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++;
                    }
                }
            } 
            if (isset($fed) && empty($fed) === false) {
                    $shipoption = $fed;
                    $shipflag = "yes";
       
                } else {

                    $flatArr = $this->__setFlateRate($qty);

                    $shipoption = $flatArr['shipopt'];
                    $first_item = $flatArr['first_item'];
                    $additional_item = $flatArr['additional_item'];
                    $pshipchrg = $flatArr['pshipchrg'];
                    $shipflag = "no";

//                $this->__setFlateRate($qty);
                   $shipmeth = $shipoption[0]['title'];
//                $this->set('shipflag', 'no');
                }

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

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

                $shipme = $this->Setting->findByValue($shipmeth);
                $flatArr = $this->__getFlateRate($shipmeth, $qty);
                $shipoption = $flatArr['shipopt'];
                $first_item = $flatArr['first_item'];
                $additional_item = $flatArr['additional_item'];
                $pshipchrg = $flatArr['pshipchrg'];
                $shipflag = "yes";
                //echo $shipme;exit;
                $shipmeth = $shipoption[0]['title'];;

//            $this->__getFlateRate($shipmeth, $qty);
//
//            $this->set('shipflag', 'yes');


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


            /*
                $shipoption = $flatArr['shipopt'];
                $first_item = $flatArr['first_item'];
                $additional_item = $flatArr['additional_item'];
                $pshipchrg = $flatArr['pshipchrg'];
                $shipflag = "no";
                $shipmeth;
            */

            $dataArr = array('shipoption' => $shipoption,
                    'first_item' => $first_item,
                    'additional_item' => $additional_item,
                    'pshipchrg' => $pshipchrg,
                    'shipflag' => $shipflag,
                    'shipmeth' => $shipmeth);

            //echo '<pre>'; print_r($dataArr); echo '</pre>';

//        $this->set('shippingmethod', $shipmeth);
            echo json_encode($dataArr);
            exit();
        } //End Function

        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"];
            }

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

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

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

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

            $shiph = array();

            $first_item = $additional_item = $shipopt = $pshipchrg = NULL;

            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);

                $first_item = $cnfg["flat_shipping_first"];
                $additional_item = $cnfg["flat_shipping_additional"];
                $shipopt = $shiph;
                $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);

                $first_item = $cnfg["secflat_shipping_first"];
                $additional_item = $cnfg["secflat_shipping_additional"];
                $shipopt = $shiph;
                $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);

                $first_item = $cnfg["thirdflat_shipping_first"];
                $additional_item = $cnfg["thirdflat_shipping_additional"];
                $shipopt = $shiph;
                $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);

                $first_item = $cnfg["forthflat_shipping_first"];
                $additional_item = $cnfg["forthflat_shipping_additional"];
                $shipopt = $shiph;
                $pshipchrg = $shipchrge;
            } else {

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

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

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

                //$this->set('pshipchrg', 0);

                $first_item = 0;
                $additional_item = 0;
                $shipopt = '';
                $pshipchrg = 0;
            }

            $dataArr = array('first_item'=>$first_item,
                    'additional_item'=>$additional_item,
                    'shipopt'=>$shipopt,
                    'pshipchrg' => $pshipchrg);

            return $dataArr;

        } // End Function

        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
        }

        function saveaddress() {
            $userID = $_POST["user_id"];
            $addressType = $_POST["addr_type"];

            $data = $_POST;

            if($addressType == 'Billing') {
                $this->UserAddress->deleteAll("UserAddress.user_id = ".$userID." AND UserAddress.addr_type = 'Billing'");
            } else { // Shipping
                $this->UserAddress->deleteAll("UserAddress.user_id = ".$userID." AND UserAddress.addr_type = 'Shipping'");
            }
            if($this->UserAddress->save($data)) {
                echo 'Saved';
            } else {
                echo 'Error in saving!';
            }

            Configure::write('debug', 0);
            $this->layout = null;
            exit();

        }

        function getusercredit(){
            $user_id = $_POST["user_id"];
            $creditBalance = 0;
            if(!empty($user_id)){
                $creditBalance = $this->Product->formatToPrice($this->User->getUserCredits($user_id));
            }
            echo $creditBalance;            
            Configure::write('debug', 0);
            $this->layout = null;
            exit();
            
        }

        function __generateOrderNotification($data){
                        
            $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");
            }   
            $prodtype = '';

            if($data["OrderDetail"]["combination_id"]=='')
            {
               // $data["OrderDetail"]["combination_id"] = 0;
            }
            

           
             $cmbtype_flag='no';
            if(count($data["OrderDetail"])>0) {

                //echo "<br>herre22";

                foreach($data["OrderDetail"] as $det) {
                 //print '<pre />';print_r($det["Product"]);exit;
                    if($det["OrderDetail"]["combination_id"] <> '0')
                        $cmbtype_flag='yes';
                }
            }
            for ($j = 0; $j < sizeof($data["OrderDetail"]); $j++) {

                   //echo "<br>herre33";
                $prodtype = $data["OrderDetail"][$j]["prodtype"];
                if ($data["OrderDetail"][$j]["type"] == 'P') {

                    $pdet = $this->Product->findById($data["OrderDetail"][$j]["product_id"]);

                    $data["OrderDetail"][$j]["Product"] = $pdet["Product"]["pname"];
                }
                
                $data["OrderDetail"][$j]["combinations"]= '--';
           
            if($data["OrderDetail"][$j]["type"]=='P') {
                if(data["OrderDetail"][$j]["combination_id"]!='0') {

                   // echo "<br>herre444";

                    $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
            }


          
         

            $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"];


            $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> " . $odr['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>Additional Cost</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) {

                $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 = number_format($dis_amnt, 2, '.', '');


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

                if (isset($det["discount_type"]) && $det["discount_type"] <> '' && $det["discount_type"] !='null') {
                    

                    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 ($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>

            <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>

          </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>&nbsp;</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"] > $amt)
                $discamt = number_format($amt, 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>

        </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>";

            if ($det['prodtype'] <> "Digital") {

                $content .="<tr>

                <td><strong>Shipping</strong></td>

                <td>:</td>

                <td> " . $odr['Order']['shipping_price'] . " </td>

              </tr>";
            }

            $content .="<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>Discount </strong></td>

                <td>:</td>

                <td> " . $discamt . " </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>";




            $content .="<tr>

            <td>&nbsp;</td>

          </tr>

        </table>

      </td>

       <td>&nbsp;</td>

      </tr>

    </table>";





            $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);



            //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($mailcontent);
            //$body           = eregi_replace("[\]",'',$body);
            $admin_mail->IsSMTP(); 
            $admin_mail->SMTPSecure = 'tls';
            //$mail->SMTPDebug  = 2;                    
            $admin_mail->SMTPAuth   = true;  

            $admin_mail->Host       = MAIL_HOST; 
            $admin_mail->Port       = MAIL_PORT;                 
            $admin_mail->Username   = MAIL_USERNAME; 
            $admin_mail->Password   = MAIL_PASSWORD;       
            $admin_mail->SetFrom($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($admin_email, "Administrator"); 
            $admin_mail->Send();
            /************************** MAIL TO THE ADMINISTRATOR ************************/

            /*#################################### EMAIL SEGMENT ###############################*/

            ###################################
            ################################### Sending Fax to Admin ###################################

              
            $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);
               
            }

                 

            Configure::write('debug', 0);
            $this->layout = null;
           

        } // End Function

function save_paymentmethod($id) {

        $this->__validateLoginStatus();
        
        $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");
        } 

        $admsess    =   $this->Session->read('Admin');

        if($admsess["orders"] <> 1) {

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

            exit();

        }

        $oid = $_POST["payment_method"];

        if($oid) {

            $re= $this->Order->changepaymentmethod($id,$oid);

            if(!empty($re)) {

                $this->Session->setFlash('Order Payment Status Changed Successfully.');

                $this->Order->id = $id;

                $data = $this->Order->read();

                for($j=0;$j < sizeof($data["OrderDetail"]);$j++) {

                    $pdet   =   $this->Product->findById($data["OrderDetail"][$j]["product_id"]);

                    $data["OrderDetail"][$j]["Product"] =   $pdet["Product"];

                }

                //print_r($data); exit;

                $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;

                $ship   =   $shipadd[0]["UserAddress"];

                $bill   =   $billadd[0]["UserAddress"];

                $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 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>

              </tr>

              <tr>

                <td>".

                        $odr['OrderStatus']['name']."

                </td>

                <td>";



                $dt = strtotime($odr['Order']['date']);

                $content .= date('Y-m-d',$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>

        <td><strong>Quantity</strong></td>

        <td><strong>Unit Price</strong></td>

        <td><strong>Price</strong></td>

      </tr>

      <tr>

        <td colspan='2'>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>";



                $amt=0;

               

                foreach($odr['OrderDetail'] as $det) {

                    $price = $det['product_price']*$det['quantity'];

                    $amt = $amt +($det['product_price']*$det['quantity']);

                    $content .= " <tr>

        <td colspan='2'>". $det['Product']['pname']."</td>

        <td> ".$det['quantity']." </td>

        <td> ".$det['product_price']." </td>

        <td>". $price." </td>

      </tr>

      <tr>

        <td colspan='2' height='15'>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

        <td>&nbsp;</td>

      </tr>";

                }

                $content .= "</table>

    </td>

      </tr>

      <tr>

        <td width='50%'>

        <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>

              <tr>

                <td><strong>Transaction Id</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['transaction_id']." </td>

              </tr>

            </table>

        </td></tr>

        </table>



    </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>Shipping Price</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['shipping_price']." </td>

              </tr>

               <tr>

                <td><strong>Tax Price</strong></td>

                <td>:</td>

                <td> ".$odr['Order']['tax_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><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'] .",".  $odr['Order']['ship_state']." </td>

      </tr>

      <tr>

        <td> ".$odr['Order']['ship_country']."  - ".$odr['Order']['ship_zip']." </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>

    </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']." ,".  $odr['Order']['bill_state'] ."</td>

      </tr>

      <tr>

        <td>". $odr['Order']['bill_country'] ." - ".$odr['Order']['bill_zip']." </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>

    </table> ";

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



                $subject        = "Order Status Changed 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 payment received 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>";

                $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);

                //echo $mailcontent; exit;

                //$mailcontent  =   "Hi ".$user["uname"].", <br> Thank you for registering with ".$cnfg["site_name"]."<br> Thanks and Regards, <br> Administrator";

                //$mailcontentad    =   "Hi Admin, <br> ".$user["uname"]." registered  with ".$cnfg["site_name"]."<br> Thanks and Regards, <br> ".$user["uname"];

                //$mailsent         = mail($odr['User']['email'],$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($odr['User']['email'], ""); 
                    $mail->Send();
                    /******************************* MAIL TO THE USER ****************************/ 
                /*#################################### EMAIL SEGMENT ###############################*/

            }else {

                $this->Session->setFlash('Order Payment Method Can\'t Change now .');

            }

        }

        $this->redirect(array('controller' => 'orders', 'action' => 'details/'.$id));

        exit;

    }
     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;
        if(trim($site_name) <> ""){
            $subj = 'Product stock alert at '.trim($site_name);
        }else{
            $subj = 'Product stock alert';
        }
        
        /*#################################### 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    = $subj;
            $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, ""); 
            $mail->Send();
            /******************************* MAIL TO THE USER ****************************/ 
        
        /*#################################### EMAIL SEGMENT ###############################*/
        
      // echo $mailcontent12.'subject'.'Product Stock Alert - ' . $cnfg["site_name"];exit;
        
        //mail($cnfg["admin_email"], 'Product Stock Alert - ' . $cnfg["site_name"], $mailcontent12, $headers);

        Configure::write('debug', 0);
        $this->autoRender = false;
    }
    ####### 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);
                    
            /*#################################### 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($to, ""); 
                $mail->Send();
                /******************************* MAIL TO THE USER ****************************/ 

            /*#################################### EMAIL SEGMENT ###############################*/
        }
    }

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


    }
    
?>