<?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');
class OrderDetailsController extends AppController {
    var $name = "OrderDetail";
    var $helpers = array('Html', 'Form','Pagination','Javascript','Csv','xls');
    var $components = array ('Pagination','Catmenu'); // Added
    var $uses = array('OrderDetail','Order','Product', 'Category','Giftcard','Cart','Currency');
    var $paginate = array('limit' => 25,'order' => array('id' => 'desc'));

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

        $sitefolder         =   $cnfg["sitebasefolder"];
        $this->set('sitebasefolder', $sitefolder);
        
        $ordr_min_date=explode(" ",$this->OrderDetail->getDates("min"));
//        $ordr_max_date=explode(" ",$this->OrderDetail->getDates("max"));
        $ordr_max_date[0]  = date("m-d-Y");

        $this->set('dflt_mindate', $ordr_min_date[0]); //Setting the max date for the calendar...
        $this->set('dflt_maxdate', $ordr_max_date[0]); //Setting the max date for the calendar...

        if(isset($_POST["ordr_fdate"]) &&  isset($_POST["ordr_fdate"]) && $_POST["ordr_tdate"]<>'' && $_POST["ordr_tdate"]<>'') {
            $frmdate=$_POST["ordr_fdate"];
            $todate=$_POST["ordr_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=$ordr_min_date[0];
            $todate=$ordr_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];

            //getting table names...
            $orddtlstbl=$this->OrderDetail->getTableName("order_details");
            $ordtbl=$this->OrderDetail->getTableName("orders");
            //getting table names...


            $this->paginate = array(
                    'conditions' => array("DATE_FORMAT(ORD.date,'%Y-%m-%d')>='".$srch_fdate."' AND  DATE_FORMAT(ORD.date,'%Y-%m-%d') <='".$srch_tdate."'"),
                    'fields' => array("OrderDetail.product_id,  SUM( OrderDetail.product_price ) ,  SUM( OrderDetail.extra_price ) , OrderDetail.combination_id, OrderDetail.type, SUM( OrderDetail.quantity ) as tot_qty,SUM((OrderDetail.product_price + OrderDetail.extra_price ) * OrderDetail.quantity ) AS tot_price"),
                    'order' => '',
                    'limit' => $this->paginate["limit"],
                    'joins' => array(
                            array(
                                    'table' => $ordtbl,
                                    'alias' => 'ORD',
                                    'type' => 'INNER',
                                    'conditions'=> array('order_id = ORD.id')
                            )
                    ),
                    'group' => 'OrderDetail.product_id,OrderDetail.type',
                    'passit' => $this->passedArgs
            );
            $reportdet = $this->paginate('OrderDetail');
        }

        for($j=0;$j < sizeof($reportdet);$j++) {
            if($reportdet[$j]["OrderDetail"]["type"]=='P') {
                $pdet	=	$this->Product->findById($reportdet[$j]["OrderDetail"]["product_id"]);
                $reportdet[$j]["Product"]	=	$pdet["Product"]["pname"];
                $reportdet[$j]["Avail_stock"]	=	$pdet["Product"]["stock"];
            }

            else if($reportdet[$j]["OrderDetail"]["type"]=='G') {
                $gdet	=	$this->Giftcard->findById($reportdet[$j]["OrderDetail"]["product_id"]);
                $reportdet[$j]["Product"]	=	$gdet["Giftcard"]["gift_code"].'(Gift Card)';
                $reportdet[$j]["Avail_stock"]	=	$gdet["Giftcard"]["stock"];
            }
        }
        

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

        $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 productcsv() {
        //getting table names...
        $orddtlstbl=$this->OrderDetail->getTableName("order_details");
        $ordtbl=$this->OrderDetail->getTableName("orders");
        //getting table names...

            $searchArr = '';
       
       if(isset($_REQUEST["start"]) &&  isset($_REQUEST["end"]) && $_REQUEST["start"]<>'' && $_REQUEST["end"]<>'') {
            $frmdate=$_REQUEST["start"];
            $todate=$_REQUEST["end"];
            $sdate=explode('-',$frmdate);
            $srch_fdate=$sdate[2].'-'.$sdate[0].'-'.$sdate[1];
            $tdate=explode('-',$todate);
            $srch_tdate=$tdate[2].'-'.$tdate[0].'-'.$tdate[1];

            $searchArr = "DATE_FORMAT(ORD.date,'%Y-%m-%d')>='".$srch_fdate."' AND  DATE_FORMAT(ORD.date,'%Y-%m-%d') <='".$srch_tdate."'" ;
        }



        $qry = array(
                'conditions' => array($searchArr),
                'fields' => array("OrderDetail.product_id,  SUM( OrderDetail.product_price ) ,  SUM( OrderDetail.extra_price ) , OrderDetail.combination_id, OrderDetail.type, SUM( OrderDetail.quantity ) as tot_qty,SUM((OrderDetail.product_price + OrderDetail.extra_price ) * OrderDetail.quantity ) AS tot_price"),
                'order' => '',
                'limit' => '',
                'joins' => array(
                        array(
                                'table' => $ordtbl,
                                'alias' => 'ORD',
                                'type' => 'INNER',
                                'conditions'=> array('order_id = ORD.id')
                        )
                ),
                'group' => 'OrderDetail.product_id,OrderDetail.type',
                'passit' => ''
        );
        $tot_cnt=count($this->OrderDetail->find('all', $qry));


        $this->paginate = array(
                'conditions' => array($searchArr),
                'fields' => array("OrderDetail.product_id,  SUM( OrderDetail.product_price ) ,  SUM( OrderDetail.extra_price ) , OrderDetail.combination_id, OrderDetail.type, SUM( OrderDetail.quantity ) as tot_qty,SUM((OrderDetail.product_price + OrderDetail.extra_price ) * OrderDetail.quantity ) AS tot_price"),
                'order' => '',
                'limit' => $tot_cnt,
                'joins' => array(
                        array(
                                'table' => $ordtbl,
                                'alias' => 'ORD',
                                'type' => 'INNER',
                                'conditions'=> array('order_id = ORD.id')
                        )
                ),
                'group' => 'OrderDetail.product_id,OrderDetail.type',
                'passit' => ''
        );
        $data = $this->paginate('OrderDetail');



        for($j=0;$j < sizeof($data);$j++) {
            if($data[$j]["OrderDetail"]["type"]=='P') {
                $pdet	=	$this->Product->findById($data[$j]["OrderDetail"]["product_id"]);
                $data[$j]["Product"]	=	$pdet["Product"]["pname"];
                $data[$j]["Avail_stock"]	=	$pdet["Product"]["stock"];
            }

            else if($data[$j]["OrderDetail"]["type"]=='G') {
                $gdet	=	$this->Giftcard->findById($data[$j]["OrderDetail"]["product_id"]);
                $data[$j]["Product"]	=	$gdet["Giftcard"]["gift_code"].'(Gift Card)';
                $data[$j]["Avail_stock"]	=	$gdet["Giftcard"]["stock"];
            }
        }

        $this->set('data', $data);
        $this->layout = 'csvexp';
    }


    function productxls($fromdate,$todate) {
        //getting table names...
        $orddtlstbl=$this->OrderDetail->getTableName("order_details");
        $ordtbl=$this->OrderDetail->getTableName("orders");
        //getting table names...

        $searchArr = '';
       
       if(isset($_REQUEST["start"]) &&  isset($_REQUEST["end"]) && $_REQUEST["start"]<>'' && $_REQUEST["end"]<>'') {
            $frmdate=$_REQUEST["start"];
            $todate=$_REQUEST["end"];

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

            $searchArr = "DATE_FORMAT(ORD.date,'%Y-%m-%d')>='".$srch_fdate."' AND  DATE_FORMAT(ORD.date,'%Y-%m-%d') <='".$srch_tdate."'" ;
        }
       
        $qry = array(
                'conditions' => array($searchArr),
                'fields' => array("OrderDetail.product_id,  SUM( OrderDetail.product_price ) ,  SUM( OrderDetail.extra_price ) , OrderDetail.combination_id, OrderDetail.type, SUM( OrderDetail.quantity ) as tot_qty,SUM((OrderDetail.product_price + OrderDetail.extra_price ) * OrderDetail.quantity ) AS tot_price"),
                'order' => '',
                'limit' => '',
                'joins' => array(
                        array(
                                'table' => $ordtbl,
                                'alias' => 'ORD',
                                'type' => 'INNER',
                                'conditions'=> array('order_id = ORD.id')
                        )
                ),
                'group' => 'OrderDetail.product_id,OrderDetail.type',
                'passit' => ''
        );
        $tot_cnt=count($this->OrderDetail->find('all', $qry));

        $this->paginate = array(
                'conditions' => array($searchArr),
                'fields' => array("OrderDetail.product_id,  SUM( OrderDetail.product_price ) ,  SUM( OrderDetail.extra_price ) , OrderDetail.combination_id, OrderDetail.type, SUM( OrderDetail.quantity ) as tot_qty,SUM((OrderDetail.product_price + OrderDetail.extra_price ) * OrderDetail.quantity ) AS tot_price"),
                'order' => '',
                'limit' => $tot_cnt,
                'joins' => array(
                        array(
                                'table' => $ordtbl,
                                'alias' => 'ORD',
                                'type' => 'INNER',
                                'conditions'=> array('order_id = ORD.id')
                        )
                ),
                'group' => 'OrderDetail.product_id,OrderDetail.type',
                'passit' => ''
        );
        $data = $this->paginate('OrderDetail');


        for($j=0;$j < sizeof($data);$j++) {
            if($data[$j]["OrderDetail"]["type"]=='P') {
                $pdet	=	$this->Product->findById($data[$j]["OrderDetail"]["product_id"]);
                $data[$j]["Product"]	=	$pdet["Product"]["pname"];
                $data[$j]["Avail_stock"]	=	$pdet["Product"]["stock"];
            }

            else if($data[$j]["OrderDetail"]["type"]=='G') {
                $gdet	=	$this->Giftcard->findById($data[$j]["OrderDetail"]["product_id"]);
                $data[$j]["Product"]	=	$gdet["Giftcard"]["gift_code"].'(Gift Card)';
                $data[$j]["Avail_stock"]	=	$gdet["Giftcard"]["stock"];
            }
        }

        $this->set('data', $data);
        $this->layout = 'xlsexp';
    }


    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"];
        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.
        $this->set('sitefolder', $sitefolder);
        $httpHost	=	$_SERVER['HTTP_HOST'];
        $this->set('sitebase','http://'.$httpHost);
        //get cart count
        $sus = $this->Session->read();
        if ($this->Session->check('Userlog') === true) {
            $userid = $sus["Userlog"]["id"];
            $cartCount = $this->Cart->getCartCount($userid,'user');
        }else {
            $sessid = $this->Session->id();
            $cartCount = $this->Cart->getCartCount($sessid,'G');
        }
        $this->set('cartcount',$cartCount);
    }

    function beforeRender() {
    }

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