<?php
    if (!defined('BASEPATH')) exit('No direct script access allowed');
    class Inventory extends MY_Controller {
        function __construct() {
            parent::__construct();
            $this->load->model('settings/reports_model');
            $this->load->library('Formatslist');
        }

        function index() {
            $data['reportlist'] = $this->reports_model->getlines();
            $data['template'] = 'reports/reports_inventory_view';
            $this->load->view('template', $data);
        }

        function reportcreation($id = '') {
            $data["reportid"] = $id;
            $data['reportdet'] = $this->reports_model->reportInfo($id);
            if(!$data['reportdet'])
                redirect('info/accessdenied');
            $content = str_replace('=">', '="GR', $data['reportdet'][0]->CONTENT);
            $content = str_replace('="<', '="LT', $content);
            $xml = simplexml_load_string($content);
            $querycheck =   trim(strtoupper(substr(trim($xml->script), 0, 7)));
            if($querycheck=='SELECT') {
                $j = 0;
                if ($xml->columns->column) {
                    foreach ($xml->columns->column as $item) {
                        $datatableVar["title"][$j]  =   $item->attributes()->title;
                        $datatableVar["field"][$j]  =   $item->attributes()->field;
                        $datatableVar["width"][$j]  =   $item->attributes()->width;
                        $datatableVar["align"][$j]  =   $item->attributes()->align;
                        $datatableVar["type"][$j]   =   $item->attributes()->type;
                        $datatableVar["sum"][$j]    =   $item->attributes()->sum;
                        $datatableVar["subtotal"][$j]    =   $item->attributes()->subtotal;
                        $j++;
                    }
                    $data["datatableVar"] = $datatableVar;
                }
                $where = "";
                $i = 0;
                foreach ($xml->filters->filter as $item1) {
                    $name = $item1->attributes()->name;
                    if (isset($_POST["$name"]) && $_POST["$name"] != '') {
                        $searchval = $_POST["$name"];
                        if ($item1->attributes()->type == 'date') {
                            if($item1->attributes()->operator == 'GR=' || $item1->attributes()->operator == 'GR'){
                                $searchval = date('Y-m-d H:i:s', strtotime($searchval." 00:00"));}
                            else if($item1->attributes()->operator == 'LT=' || $item1->attributes()->operator == 'LT'){
                                $searchval = date('Y-m-d H:i:s', strtotime($searchval." 23:59:59"));}
                            else{
                                $searchval = date('Y-m-d', strtotime($searchval));}
                        }
                        if ($item1->attributes()->type == 'datetime') {
                            $searchval = date('Y-m-d H:i', strtotime($searchval));
                        }
                        if ($item1->attributes()->operator == 'like') 
                            $where .= " AND " . $item1->attributes()->field . " " . $item1->attributes()->operator . "'%" . str_replace("'","",trim($searchval)) . "%'";
                        else if ($item1->attributes()->operator == 'GR=') {
                            $where .= " AND " . $item1->attributes()->field . ">='" . trim($searchval) . "'";
                        } else if ($item1->attributes()->operator == 'GR') {
                            $where .= " AND " . $item1->attributes()->field . ">'" . trim($searchval) . "'";
                        } else if ($item1->attributes()->operator == 'LT=') {
                            $where .= " AND " . $item1->attributes()->field . "<='" . trim($searchval) . "'";
                        } else if ($item1->attributes()->operator == 'LT') {
                            $where .= " AND " . $item1->attributes()->field . "<'" . trim($searchval) . "'";
                        } else 
                            $where .= " AND " . $item1->attributes()->field . $item1->attributes()->operator . "'" . str_replace("'","",trim($searchval)) . "'";
                    }else {
                        $searchval = "";
                    }
                    if ($item1->attributes()->type == 'text') {
                        $searchfields[$i] = "<div class='col-lg-2 col-md-12 col-sm-12 col-xs-12' style='text-align: left;padding-top: 12px;'>" . strtoupper($item1->attributes()->title) . "</div><div class='col-md-3 searchfieldslist'><input type='text' name='" . $name . "' id='" .$name. "' value='" . $searchval . "' placeholder='ENTER " . strtoupper($item1->attributes()->title) . "' class='form-control' /></div>";
                    } else if ($item1->attributes()->type == 'list') {
                        if ($item1->attributes()->value) {
                            $query = substr($item1->attributes()->value, 1, -1);
                        }
                        $reclist = $this->common->customquery($query);
                        if ($reclist) {
                            $select = "<div class='col-lg-2 col-md-12 col-sm-12 col-xs-12' style='text-align: left;padding-top: 12px;'>" . strtoupper($item1->attributes()->title) . "</div><div class='col-md-3 searchfieldslist'><select name='" . $name . "' id='" . $name . "' class='form-control'>";
                            $select .= "<option value=''>SELECT " . strtoupper($item1->attributes()->title) . "</option>";
                            foreach ($reclist as $list) {
                                $namelist = $item1->attributes()->name;
                                if (isset($_POST["$namelist"]) && ($list->ID == $_POST["$namelist"]))
                                    $selected = "selected";
                                else 
                                    $selected = "";
                                $select .= "<option value='" . $list->ID . "' " . $selected . ">" . $list->NAME . "</option>";
                            }
                            $select .= "</select></div>";
                        } else {
                            $select = "<div class='col-lg-2 col-md-12 col-sm-12 col-xs-12' style='text-align: left;padding-top: 12px;'>" . strtoupper($item1->attributes()->title) . "</div><div class='col-md-3 searchfieldslist'><select name='" . $name . "' id='" . $name . "' class='form-control'>";
                            $select .= "<option value=''>SELECT " . strtoupper($item1->attributes()->title) . "</option>";
                            $select .= "</select></div>";
                        }
                        $searchfields[$i] = $select;
                    } else if ($item1->attributes()->type == 'date') {
                        if ($item1->attributes()->value) {
                            $query = substr($item1->attributes()->value, 1, -1);
                        }
                        if(isset($query) && $query){
                            $reclist = $this->common->customquery($query);
                            if ($searchval)
                                $datepickerVal = date("d-m-Y",strtotime($searchval));
                            else
                                $datepickerVal = date("d-m-Y",strtotime($reclist[0]->DATE));
                        }else{
                            if ($searchval)
                                $datepickerVal = date("d-m-Y",strtotime($searchval));
                            else
                                $datepickerVal = '';
                        }
                        $searchfields[$i] = "<div class='col-lg-2 col-md-12 col-sm-12 col-xs-12' style='text-align: left;padding-top: 12px;'>" . strtoupper($item1->attributes()->title) . "</div><div class='col-md-2 searchfieldslist'><input type='text' name='" . $name . "' id='" . $name . "' value='" . $datepickerVal . "' readonly placeholder='ENTER " . strtoupper($item1->attributes()->title) . "' class='form-control date-picker' /></div>";
                    } else if ($item1->attributes()->type == 'datetime') {
                        if ($item1->attributes()->value) {
                            $query = substr($item1->attributes()->value, 1, -1);
                        }
                        if(isset($query) && $query){
                            $reclist = $this->common->customquery($query);
                            if ($searchval)
                                $datepickerVal = date("Y-m-d H:i:s",strtotime($searchval));
                            else
                                $datepickerVal = date("Y-m-d H:i:s",strtotime($reclist[0]->DATE));
                        }else{
                            if ($searchval)
                                $datepickerVal = $searchval;
                            else
                                $datepickerVal = '';
                        }
                        $searchfields[$i] = "<div class='col-lg-2 col-md-12 col-sm-12 col-xs-12' style='text-align: left;padding-top: 12px;'>" . strtoupper($item1->attributes()->title) . "</div><div class='col-md-3 searchfieldslist'><div class='form-group' style='margin-bottom: 0px;'><div class='input-group date form_datetime col-md-12' data-date-format='yyyy-mm-dd hh:ii'><input class='form-control' name='".$name."' size='16' type='text' readonly value='".$datepickerVal."' placeholder='ENTER " . strtoupper($item1->attributes()->title) . "' /><span class='input-group-addon'><span class='glyphicon glyphicon-th'></span></span></div></div><script type='text/javascript'> $('.form_datetime').datetimepicker({ autoclose: 1, });</script></div>";
                    }
                    $i++;
                }
                $limittext = '';
                $limitvalue =   '';
                if($xml->limit) {
                    
                    if(isset($xml->limit->attributes()->value)) {
                        if(isset($_POST["LIMITVAL"])) {
                            if($_POST["LIMITVAL"]) {
                                $limitvalue =   $_POST["LIMITVAL"];
                            }
                        } else {
                            $limitvalue =   $xml->limit->attributes()->value;
                        }
                    }
                    $limittext = '<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"><div class="col-lg-2 col-md-12 col-sm-12 col-xs-12" style="text-align: left;padding-top: 12px;">LIMIT</div><div class="col-md-3 searchfieldslist"><input type="text" class="form-control" name="LIMITVAL" id="LIMITVAL" value="'.$limitvalue.'" placeholder="Enter Limit" /></div></div>';
                }
                
                if ($_POST) {
                    if ($where) {
                        $data["wherecond"] = $where;
                        $xmlscript = str_replace("?", "1" . $where, $xml->script);
        //                $data["sqlquery"] = $xmlscript;
                    } else {
                        $where = "1";
                        $data["wherecond"] = $where;
                        $xmlscript = str_replace("?", $where, $xml->script);
        //                $data["sqlquery"] = $xmlscript;
                    }
                    if ($xml->groups->group) {
                        $orgrp  =   0;
                        foreach ($xml->groups->group as $group) {
                            $groupArr[$orgrp] =   (string)$group->attributes()->field;
                            $orgrp++;
                        }
                        $data["groupArray"]         =   $groupArr;
                        $data["groupArrayCount"]    =   count($groupArr);

                        $groupfields =   implode(",",$groupArr);
                        // Append fields to select values section
                        $xmlscript= strtoupper($xmlscript);
                        $slqsplit   =   explode("FROM",$xmlscript);
                        $sqlupdated =   $slqsplit[0]." FROM ".$slqsplit[1];
                        $sqltemp =   $sqlupdated;
                        // split limit potion of the sql if exists
                        if(substr_count($sqlupdated,"LIMIT")>0) {
                            $sqlArrLimit =   explode("LIMIT",$sqlupdated);
                            $sqlupdated  =   $sqlArrLimit[0];
                        }
                        //Append fields to group by and order by
                        $flagorderby    =   0;
                        if(substr_count($sqlupdated,"ORDER BY")>0){
                            $flagorderby    =   1;
                        }
                        if($flagorderby==1) {
                            $groupbyArr     =   explode("ORDER BY",$sqlupdated);
                            $sqlupdated     =   $groupbyArr[0]." ORDER BY ".$groupfields.",".$groupbyArr[1];
                        } else {
                            $sqlupdated     =   $sqlupdated." ORDER BY ".$groupfields;
                        }
//                        if(substr_count($sqltemp,"LIMIT")>0) {
//                            $sqlupdated  =   $sqlupdated." LIMIT ".$sqlArrLimit[1];
//                        }
                        if(substr_count($sqltemp,"LIMIT")>0) {
                            $sqlupdated  =   $sqlupdated." LIMIT ".$sqlArrLimit[1];
                        } else {
                            if(isset($_POST["LIMITVAL"])) {
                                if($_POST["LIMITVAL"]) {
                                    $sqlupdated  =   $sqlupdated." LIMIT ".$_POST["LIMITVAL"];
                                }
                            }
                        }
                        $data["sqlquery"] = str_replace('"',"'" , $sqlupdated);
                    } else {
                        if(substr_count($xmlscript,"LIMIT")>0) {
                            $xmlscript  =   $xmlscript." LIMIT ".$sqlArrLimit[1];
                        } else {
                            if(isset($_POST["LIMITVAL"])) {
                                if($_POST["LIMITVAL"]) {
                                    $xmlscript  =   $xmlscript." LIMIT ".$_POST["LIMITVAL"];
                                }
                            }
                        }
                        $data["sqlquery"] = str_replace('"',"'" , $xmlscript);
                        $sqlupdated = $data["sqlquery"];
                    }
                    
    //                 echo $sqlupdated;exit;
                    $data["dataresult"] = $this->common->customquery($sqlupdated);
                } else {
                    $data["groupArray"] =  '';
                    $data["wherecond"] = '';
                    $data["dataresult"] = '';
                }
            } else {
                redirect(base_url().'info/wrongsql');
            }
    //        echo $sqlupdated;exit;
            $data['reporttitle'] = $xml->title;
            if (isset($searchfields) && $searchfields) $data['searchfields'] = $searchfields;
            $data['limittext'] = $limittext;
            $data['template'] = 'reports/report_tempate';
            $this->load->view('template', $data);
        }

        function exportexceldata() {
            if (isset($_POST)) {
                $id = $_POST["reportid"];
                $data['reportdet'] = $this->reports_model->reportInfo($id);
                if (isset($_POST["excelexport"])) {
                    $file = $data['reportdet'][0]->REPORTNAME."001.xls";
                    header("Content-type: application/vnd.ms-excel");
                    header("Content-Disposition: attachment; filename=$file");
                }
                $content = str_replace('=">', '="GR',$data['reportdet'][0]->CONTENT);
                $content = str_replace('="<','="LT',$content);
                $xml = simplexml_load_string($content);
                $j = 0;
                if ($xml->columns->column) {
                    foreach ($xml->columns->column as $item) {
                        $datatableVar["title"][$j] = $item->attributes()->title;
                        $datatableVar["field"][$j] = $item->attributes()->field;
                        $datatableVar["width"][$j] = $item->attributes()->width;
                        $datatableVar["align"][$j] = $item->attributes()->align;
                        $datatableVar["type"][$j] = $item->attributes()->type;
                        $datatableVar["sum"][$j] = $item->attributes()->sum;
                        $datatableVar["subtotal"][$j]    =   $item->attributes()->subtotal;
                        $j++;
                    }
                }
                if ($xml->groups->group) {
                    $orgrp  =   0;
                    foreach ($xml->groups->group as $group) {
                        $groupArr[$orgrp] =   (string)$group->attributes()->field;
                        $orgrp++;
                    }
                    $groupArray         =   $groupArr;
                    $groupArrayCount    =   count($groupArr);
                }

                $dataresult = $this->common->customquery($_POST["hiddenqueryvalue"]);
                if(isset($_POST["hiddensumqueryvalue"]) && $_POST["hiddensumqueryvalue"])
                    $qry = $_POST["hiddensumqueryvalue"];
                $tabledata= '<table style="font-size:11px;font-weight:bold; text-align:left;border-collapse:collapse;border:1px solid #c8c8c8;padding: 5 5 5 5;width:100%;"><tr>';
                if ($datatableVar["title"]) {
                    $k = 0;
                    $sumArray = array();
                    foreach ($datatableVar["title"] as $title) {
                        $tabledata .= '<td align="'.$datatableVar["align"][$k].'" class="headertd" style="font-size:12px;background-color: #d8d8d8;">' . $title;
                        if ($datatableVar["sum"][$k] == 'true') {
                            array_push($sumArray, 'sum(' . $datatableVar["field"][$k] . ') as ' . $datatableVar["field"][$k]);
                        }
                        $tabledata .= '</td>';
                        $k++;
                    }
                    $totalcols  =   $k;
                }
                $tabledata .= '</tr>';
                if (isset($qry) && $qry) {
                    $footerdata = '<tr>';
                    $sumdataresult = $this->common->customquery($qry);
                    
                    if ($datatableVar["title"]) {
                        $k = 0;
                        foreach ($datatableVar["title"] as $title) {
                            $footerdata .= '<td style="text-align:'.$datatableVar["align"][$k].';font-weight:bold;">';
                            if (trim($datatableVar["sum"][$k]) == 'true') {
                                $fieldname = $datatableVar["field"][$k];
                                if (trim($datatableVar["type"][$k]) == 'currency') {
                                    $footerdata .= $this->formatslist->formatCurrencywithHash($sumdataresult[0]->$fieldname);
                                } else {
                                    $footerdata .= $sumdataresult[0]->$fieldname;
                                }
                            }
                            $footerdata .= '';
                            $k++;
                            $footerdata .= '</td>';
                        }
                    }
                    $footerdata .= '</tr>';
                }else{
                    $footerdata = '';
                }
                if (isset($dataresult) && $dataresult) {
                    $prevFlddata[]   =   '';
                    $datcount        =   0;
                    $flagexist      =   0;
                    $arrFinal       =   array();
                        if(isset($groupArray) && $groupArray) {
                            foreach($dataresult as $datarow) {
                                foreach($groupArray as $groupArrData) {
                                    $key = array_search($groupArrData, $groupArray);
                                    if(!isset($prevFlddata["$groupArrData"]))
                                        $prevFlddata["$groupArrData"][] =   "";
                                    if(!in_array($datarow->$groupArrData,$prevFlddata["$groupArrData"])) {
                                        $subcount  =   0;
                                        $prevFlddata["$groupArrData"][$datcount]   =   $datarow->$groupArrData;
                                        $arrFinal["GROUPCATEGORY"][$datcount]  =   $datarow->$groupArrData;
                                        $datcount++;
                                        $prevFlddata["$groupArrData"][$key]   =   $datarow->$groupArrData;
                                        if(isset($groupArrayCount)) {
                                            for($q=$key+1;$q<$groupArrayCount;$q++) {
                                                if(isset($prevFlddata["$groupArray[$q]"])) {
                                                    unset($prevFlddata["$groupArray[$q]"]);
                                                }
                                            }
                                        }
                                    }
                                }

                                if($datatableVar["title"]) {
                                    $k=0;
                                    $tabdata    =   '';
                                    $subtotalflag   =   0;
                                    foreach($datatableVar["title"] as $title){
                                        $fieldname  =   $datatableVar["field"][$k];
                                        $arrFinal["SUBDATA"][$datcount][$k]["txtalign"]     =   $datatableVar["align"][$k];
                                        $arrFinal["SUBDATA"][$datcount][$k]["width"]        =   $datatableVar["width"][$k];
                                        $arrFinal["SUBDATA"][$datcount][$k]["type"]         =   $datatableVar["type"][$k];
                                        $arrFinal["SUBDATA"][$datcount][$k]["value"]        =   $datarow->$fieldname;
                                        if($datatableVar["subtotal"][$k]=="true")
                                            $subtotalflag   =   1;
                                        $arrFinal["SUBDATA"][$datcount][$k]["subtotal"]     =   $datatableVar["subtotal"][$k];
                                        if(isset($datatableVar["subtotal"][$k])) {
                                            if($datatableVar["subtotal"][$k]=='true')
                                                $arrSumkey[] =   $k;
                                        }
                                        $k++;
                                    }
                                }
                                $datcount++;
                            }

                            if($arrFinal) {
                                if(isset($arrSumkey)) {
                                    $arrSumkey  =   array_unique($arrSumkey);
                                    if($arrSumkey) {
                                        $totsumtmp["SUMTOTAL"]  =   array();
                                        foreach($arrSumkey as $arrSumrec) {
                                            $totsumtmp["SUM"]   =   array();
                                            $sum    =   0;
                                            for($k=0;$k<$datcount;$k++) {
                                                if(isset($arrFinal["GROUPCATEGORY"][$k])) {
                                                    $k++;
                                                    $totsumtmp["SUM"][]    =   $sum;
                                                    $sum    =   0;
                                                }
                                                if(isset($arrFinal["SUBDATA"][$k])) {
                                                    $sum    =   $sum+$arrFinal["SUBDATA"][$k][$arrSumrec]["value"];
                                                }
                                            }
                                            $totsumtmp["SUM"][] =   $sum;
                                            $tmtsumarr            =   $totsumtmp["SUM"];
                                            $totsumtmp["SUMTOTAL"][]    =   $tmtsumarr;
                                        }
                                    }
                                }
                            }

                            if($arrFinal) {
                                $subdataflag=0;
                                $totlflag=1;
    //                            $countrows   =   count($arrFinal['SUBDATA']);
                                for($a=0;$a<$datcount;$a++) {
                                    if(isset($arrFinal['SUBDATA'][$a])) {
                                        $tabledata.='<tr>';
                                        if($arrFinal['SUBDATA'][$a]) {
                                            $k=0;
                                            foreach($arrFinal['SUBDATA'][$a] as $title){
                                                $tabledata.='<td style="text-align:'.$title["txtalign"].';width:'.$title["width"].';">';
                                                if($title["type"]=='currency') {
                                                    $tabledata.=$this->formatslist->formatCurrencywithHash($title["value"]);
                                                } else if($title["type"]=='double') {
                                                    $tabledata.=$this->formatslist->formatDoubleNumber($title["value"]);
                                                } else if($title["type"]=='number') {
                                                    $tabledata.=$this->formatslist->formatIntegerNumber($title["value"]);
                                                } else if($title["type"]=='date') {
                                                    if($title["value"])
                                                        $tabledata.=$this->formatslist->dateFormat($title["value"]);
                                                } else if($title["type"]=='datetime') {
                                                    if($title["value"])
                                                        $tabledata.=$this->formatslist->datetimeFormat($title["value"]);
                                                } else
                                                    $tabledata.=$title["value"];
                                                $tabledata.='</td>';
                                                $k++;
                                            }
                                        }
                                        $tabledata.='</tr>';
                                        $subdataflag    =   1;
                                    }

                                    if(isset($arrFinal['GROUPCATEGORY'][$a]) && $subdataflag==1) {
                                        $subdataflag    =   0;
                                        if(isset($datatableVar["subtotal"])) {
                                            if($subtotalflag==1)
                                                $tabledata.=    '<tr>';
                                            $sfalg      =   0;
                                            foreach($datatableVar["subtotal"] as $chksumtitle) {
                                                if($chksumtitle=='true') {
                                                    if(isset($totsumtmp["SUMTOTAL"][$sfalg][$totlflag])) {
                                                        $tabledata.='<td style="text-align:right;font-weight:bold;">'.
                                                            $this->formatslist->formatCurrencywithHash($totsumtmp["SUMTOTAL"][$sfalg][$totlflag]).'</td>';
                                                    }
                                                    $sfalg++;
                                                } else {
                                                    if($subtotalflag==1)
                                                        $tabledata.='<td>&nbsp;</td>';
                                                }
                                            }
                                            if($subtotalflag==1)
                                                $tabledata.='</tr>';
                                            $totlflag++;
                                        }
                                    }

                                    if(isset($arrFinal['GROUPCATEGORY'][$a])) {
                                        $tabledata.='<tr>';
                                        $tabledata.='<td colspan="'.$totalcols.'" style="font-weight:bold;">'
                                            .$arrFinal['GROUPCATEGORY'][$a].'</td>';
                                        $tabledata.='</tr>';
                                    }

                                }
                                
                                if(isset($datatableVar["subtotal"])) {
                                    if($subtotalflag==1)
                                        $tabledata.='<tr>';
                                    $sfalg  =   0;
                                    foreach($datatableVar["subtotal"] as $chksumtitle) {
                                        if($chksumtitle=='true') {
                                            if(isset($totsumtmp["SUMTOTAL"][$sfalg][$totlflag])) {
                                                $tabledata.='<td style="text-align:right;font-weight:bold;">'.
                                                    $this->formatslist->formatCurrencywithHash($totsumtmp["SUMTOTAL"][$sfalg][$totlflag]).'</td>';
                                            }
                                            $sfalg++;
                                        } else {
                                            if($subtotalflag==1)
                                                $tabledata.='<td>&nbsp;</td>';
                                        }
                                    }
                                    if($subtotalflag==1)
                                        $tabledata.='</tr>';
                                    $totlflag++;
                                }

    //                            $tabledata.='<td style="text-align:right;font-weight:bold;">'.
    //                                                        $totsumtmp["SUMTOTAL"][$sfalg][$totlflag].'</td>';
                            }

                        } else {
                            foreach($dataresult as $datarow) {
                                $tabledata.='<tr>';
                                if($datatableVar["title"]) {
                                    $k=0;
                                    foreach($datatableVar["title"] as $title){
                                        $fieldname  =   $datatableVar["field"][$k];
                                        $tabledata.='<td style="text-align:'.$datatableVar["align"][$k].';">';
                                        if($datatableVar["type"][$k]=='currency'){
                                            $tabledata.=$this->formatslist->formatCurrencywithHash($datarow->$fieldname);
                                        }else if($datatableVar["type"][$k]=='double'){
                                            $tabledata.=$this->formatslist->formatDoubleNumber($datarow->$fieldname);
                                        }else if($datatableVar["type"][$k]=='number'){
                                            $tabledata.=$this->formatslist->formatIntegerNumber($datarow->$fieldname);
                                        }else if($datatableVar["type"][$k]=='date'){
                                            if($datarow->$fieldname)
                                                $tabledata.=$this->formatslist->dateFormat($datarow->$fieldname);
                                        }else if($datatableVar["type"][$k]=='datetime'){
                                            if($datarow->$fieldname)
                                                $tabledata.=$this->formatslist->datetimeFormat($datarow->$fieldname);
                                        }else
                                            $tabledata.=$datarow->$fieldname;
                                        $tabledata.='</td>';
                                    $k++;
                                    }
                                }
                                $tabledata.='</tr>';
                                $datcount++;
                            }
                    }

    //                $datcount        =   0;
    //                foreach ($dataresult as $datarow) {
    //                    if(isset($groupArray) && $groupArray){
    //                        foreach($groupArray as $groupArrData){
    //                            $key = array_search($groupArrData, $groupArray);
    //                            if(!isset($prevFlddata["$groupArrData"]))
    //                                $prevFlddata["$groupArrData"][] =   "";
    //                            if(!in_array($datarow->$groupArrData,$prevFlddata["$groupArrData"])) {
    //                                $prevFlddata["$groupArrData"][$datcount]   =   $datarow->$groupArrData;
    //                                $tabledata.='<tr>';
    //                                $tabledata.='<td colspan="'.$totalcols.'" style="font-weight:bold;">'.$datarow->$groupArrData.'</td>';
    //                                $tabledata.='</tr>';
    //                                $prevFlddata["$groupArrData"][$key]   =   $datarow->$groupArrData;
    //                                if(isset($groupArrayCount)) {
    //                                    for($q=$key+1;$q<$groupArrayCount;$q++){
    //                                        if(isset($prevFlddata["$groupArray[$q]"]))
    //                                            unset($prevFlddata["$groupArray[$q]"]);
    //                                    }
    //                                }
    //                            }
    //                        }
    //                    }
    //                    $tabledata .= '<tr>';
    //                    if ($datatableVar["title"]) {
    //                        $k = 0;
    //                        foreach ($datatableVar["title"] as $title) {
    //                            $fieldname = $datatableVar["field"][$k];
    //                            $tabledata .= '<td style="padding:15px;border:1px solid #ddd;">';
    //                            if($datatableVar["type"][$k]=='currency'){
    //                                $tabledata.=$this->formatslist->formatCurrencywithHash($datarow->$fieldname);
    //                            }else if($datatableVar["type"][$k]=='date'){
    //                                if($datarow->$fieldname)
    //                                    $tabledata.=$this->formatslist->dateFormat($datarow->$fieldname);
    //                            }else if($datatableVar["type"][$k]=='datetime'){
    //                                if($datarow->$fieldname)
    //                                    $tabledata.=$this->formatslist->datetimeFormat($datarow->$fieldname);
    //                            }else
    //                                $tabledata.=$datarow->$fieldname;
    //                            $tabledata .= '</td>';
    //                            $k++;
    //                        }
    //                    }
    //                    $tabledata .= '</tr>';
    //                    $datcount++;
    //                }
                }
                $tabledata .= $footerdata;
                $tabledata .= '</table>';
                $data["tabledata"] =   $tabledata;

                if (isset($_POST["excelexport"])) {
                    echo $tabledata;
                } else if (isset($_POST["pdfxport"])) {
                    $this->load->model('settings/companyinfo_model');
                    $data['companyinfo'] = $this->companyinfo_model->getcompanyinfo('0');
                    $tabledata = $this->load->view('reports/report_print', $data, true);
                    $this->load->library('Pdf');
                    $pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
                    $pdf->SetMargins(10, 10, 10, true);
                    $pdf->SetCreator('Saleculator');
                    $pdf->SetAuthor('John Mathew');
                    $pdf->SetTitle($xml->title);
                    $pdf->SetSubject($xml->title);
                    //$pdf->SetKeywords('Posics, PDF, example, test, guide');
                    //define(K_BLANK_IMAGE,base_url()."assets/img/company/".$data['companyinfo']->DISPLAYLOGO);
                    $pdf->SetHeaderData(K_BLANK_IMAGE, PDF_HEADER_LOGO_WIDTH, $data['companyinfo']->COMPANYNAME."#".$xml->title, $data['companyinfo']->ADDRESS1."\nPhone: ".$data['companyinfo']->PHONE1."\n".$data['companyinfo']->EMAIL.', '.$data['companyinfo']->WEBSITE."\nTax Id: ".$data['companyinfo']->TAXID);
                    // var_dump($pdf);
                    // set header and footer fonts
                    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
                    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
                    // set default monospaced font
                    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
                    //set margins
                    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
                    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
                    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
                    //set auto page breaks
                    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
                    //set image scale factor
                    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
                    // ---------------------------------------------------------
                    // set font
                    $pdf->SetFont('helvetica', 'B', 11);
                    // add a page
                    //$pdf->AddPage();
                    $pdf->AddPage();
                    $pdf->writeHTML($tabledata, true, false, true, false, '');
                    // var_dump($html);exit;
                    // echo $html;exit;
                    // Print some HTML Cells
                    // reset pointer to the last page
                    $pdf->lastPage();
                    // ---------------------------------------------------------
                    //Close and output PDF document
                    $pdf->Output($data['reportdet'][0]->REPORTNAME.'001.pdf', 'D');
                }
            }
        }
    }