<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
//$mysqli = new mysqli()
function MessageBack($str,$exitt = true){
    $str = EscapeString($str);
Box("style=color:red;width:100%;text-align:center; margin-top:20px;");
    Box("style=font-size:2em");Icon("exclamation-triangle");_Box();
    Text("text=$str,style=color:inherit;text-transform:uppercase;font-size:1.0em");
_Box();
if($exitt){ 
    exit();
}
} 

//check priv
//AllowUser("RPayment");
 
/* function ToMySQLDate($date){
    $montharr = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
    $dtarr = explode("-",$date);
    if(count($dtarr) == 3){ //if valid
      $dtarr[1] = (int)array_search(strtolower($dtarr[1]),$montharr)+1;
      return $dtarr[2]."-".$dtarr[1]."-".$dtarr[0];
    }
    return "";
} */

function ToMySQLDate($date){
    //$montharr = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
    $dtarr = explode("/",$date);
    if(count($dtarr) == 3){ //if valid
      //$dtarr[1] = (int)array_search(strtolower($dtarr[1]),$montharr)+1;
      return $dtarr[2]."-".$dtarr[1]."-".$dtarr[0];
    }
    return "";
}

//get the school structure
$sch = GetSchool('SchStrucContr');
$schStruc = json_decode($sch['SchStrucContr'],true);

extract($_POST);
//pagenation
//Set data for print operation
Box("id=rptprintdata,style=display:none;visibility:hidden");
  echo json_encode($_POST);
_Box();
if(isset($reportType)){
   
    $from = isset($fr)?ToMySQLDate($fr):"";
    $to = isset($to)?ToMySQLDate($to):"";
    $searchstr = isset($str)?$dbo->SqlSafe($str):"";
    //remove serach string from post
    unset($_POST['str']);
    $DPOST = $_POST;
    /*if(!isset($pg)){
    $LastDis = $_POST['LastDis'];
    unset($_POST['LastDis']);
    $BackPOST = $_POST;
    $BackPOST['displaytext'] = $LastDis;
    }*/

    //pagenation
    $lastpgindex = 0;
  $recpg = 50;
   //set limit
   if(isset($pg)){
      $pg = (int)$pg;
      if($pg < 2){
        $lmt = $recpg;
      }else{
          $lastpgindex = (($pg - 1) * $recpg);
        $lmt = $lastpgindex.",$recpg";
      }
   }else{
     $pg = 1;
     $lmt = $recpg;
   }
    $datefilter = ($from != "" && $to != "")?"AND (p.PayDate >= '$from' AND p.PayDate <= '$to')":"";
    $query = "";
    $dump = array();
    $rses = $ses;
    //if all session
    $ses = (int)$ses == 0?"":"AND p.Ses=$ses";
    //Genearl Condition
    //Online Payments
    if((int)$offline == 0){
        $datefilter .= " AND LCASE(p.Bank) != 'manual pay' ";
    }

    //Offline Payment
    if((int)$online == 0){
        $datefilter .= " AND LCASE(p.Bank) = 'manual pay' ";
    }
    
    //Get the query
      include "Reports/".$reportType.".php";
      list($query,$querylim) = ReportQuery();
      //echo $reportType." => ".$querylim;
     // exit;
      //$querylim = $query." LIMIT ".$lmt;
   
    $CurPost = $_POST;
    unset($_POST['str']);
    $curdatastr = $dbo->DataString($CurPost);
    $totstat = 0;$totamt=0;$totpays=0;$totAmts=0;$overall=0;
    if($query != ""){
       
       //Run the query
        $rst = $dbo->RunQuery($query);
        
         $rpt = $dbo->RunQuery($querylim);
        //get the overall number of record and total expected page
        $rsttot = $dbo->RunQuery("SELECT FOUND_ROWS()");
        $rtot = $rsttot[0]->fetch_array();
        $alltot = (int)$rtot[0];
        $totpg = $alltot / $recpg; //get the total expexted page
        $totpg = $totpg < 1?1:ceil($totpg);
        
       // $BackPOST['displaytext'] = $_POST['displaytext'];
        if(is_array($rpt)){
            
            if($rpt[1] > 0){
               // MessageBack($rst);
               //echo $rst;
                $rstrec = $rst[0]->fetch_array();
                $totpays = $rstrec['Payments'];
                $totAmts = $rstrec['Sums'];
                //loop thru all records
                while($rec = $rpt[0]->fetch_array()){
                    $overall += 1;
                    //process the report and add to spreate sheet data
                   $dump[] = FormRecord();
                }
            }
        }
    }
    //form
    $totamtf = number_format($totamt, 2, '.', ',');
    /* if($totamt > 0){
        if($reportType == "paytypeitem"){
            $recarr = array('','PAGE TOTAL',$totamtf,'','','','');
            if((int)$offline == 1 && (int)$online == 1){
               $recarr[] = '';
             }
             $recarr['disable'] = 'true';
             $dump[] = $recarr;
        }
    } */
    $totAmts = number_format($totAmts, 2, '.', ',');
    
    $chaneldis = "";
if((int)$offline == 1 && (int)$online == 1){
    $chaneldis = "ONLINE &amp; OFFLINE";
}else if((int)$offline == 1){
    $chaneldis = "OFFLINE";
}else{
    $chaneldis = "ONLINE"; 
}
         
    Box("style=width:100%;overflow:auto");
     Table("style=width:calc(100% - 0px);font-size:0.8em;margin:10px auto;text-align:left,id=totalrpt,multiselect=false,data-type=table");
      //form the sumary table data
     list($arrhed,$arrRec) = Summary();
     //array_unshift($arrhed,"SUMMARY:");
     /* $arrhed = ($from != "" && $to != "")?array("SUMMARY:","REPORT SESSION","CHANNEL","DATE FILTER","TOTAL PAYMENT","OVERALL AMOUNT"):array("SUMMARY:","REPORT SESSION","CHANNEL","TOTAL PAYMENT","OVERALL AMOUNT");
     $fromarr = explode("-",$from);
     $toarr = explode("-",$to);
     $sesName = (int)$rses == 0?"ANY":SessionName($rses); */
     
        THeader($arrhed,"style=text-align:center");
       /*  $arrRec = ($from != "" && $to != "")?array("<strong>".$sesName."</strong>",$chaneldis,date("j-M-Y",mktime(0,0,0,$fromarr[1],$fromarr[2],$fromarr[0]))." "._Icon("arrow-right")." ".date("j-M-Y",mktime(0,0,0,$toarr[1],$toarr[2],$toarr[0])),"<strong>".$totpays."</strong>","<strong>".$totAmts."</strong>"):array("<strong>".$sesName."</strong>",$chaneldis,"<strong>".$totpays."</strong>","<strong>N ".$totAmts."</strong>"); */
        TRecord($arrRec,"data-id=paytypesum,style=font-weight:bolder");

       _Table();
       _Box();
       echo "<div style=\"width:100%; height:1px;margin:10px 0px\" class=\"altBgColor2\" > </div>";
       
       $dif = 80;
       /*if(isset($BackPOST['back'])){
           
           $backdatastr = $dbo->DataString($BackPOST);
        Box("style=width:50px;display:inline-block;margin:0px 10px;vertical-align:top");
       $backdatastr = str_replace("=","\=",$backdatastr);
       SmallButton("id=payrptbkbtn,logo=chevron-left,style=margin:0px,title=Back,onclick=Payment.PaymentReport.Search('$backdatastr')"); _Box();
       $dif = 160;
       }*/
      /* Box("style=width:100%;display:inline-block;vertical-align:top;margin-bottom:5px");
      TextBox("title=Search Report,style=width:100%,onchange=,id=payrptsearch,logo=search,info=Inteligent Search: Search by any information you have on the Report,onkeypress=Payment.PaymentReport.SearchPress(event),text=".str_replace(array("=",","),array("\=","\,"),$searchstr)); 
      _Box(); 
       Box("style=width:50px;display:inline-block;margin:0px 10px;vertical-align:top");
       $refreshpostdatastr = str_replace("=","\=",$curdatastr);
       SmallButton("id=payrptsearchbtn,logo=refresh,style=margin:0px,title=Search,onclick=Payment.PaymentReport.Search('$refreshpostdatastr')"); _Box();
       Box("style=clear:both");_Box(); */

       Box("style=width:100%;display:inline-block;vertical-align:top;margin-bottom:5px"); 
    TextBoxGroup("width:calc(100% - 0px);font-size:0.8em;margin:auto");
   // $hist  = 1;
$bkstyle = $hist > 0?"style=width:50px":"";
    TextBoxGroupItem($bkstyle);
    if($hist > 0){
    Box("style=width:50px;display:inline-block;margin:0px 10px;vertical-align:top");
    //$refreshpostdatastr = str_replace("=","\=",$curdatastr);
    SmallButton("id=studrptbackbtn,logo=chevron-left,style=margin:0px,title=Back,onclick=Payment.PaymentReport.Back()"); _Box();
    TextBoxGroupItemMore("style=width:calc(100% - 50px)");
    }
    
    TextBox("title=Search Report,style=width:100%,onchange=,id=payrptsearch,logo=search,info=Inteligent Search: Search by any information you have on the Report,onkeypress=Payment.PaymentReport.SearchPress(event),text=".str_replace(array("=",","),array("\=","\,"),$searchstr)); 
    _TextBoxGroupItem();
    _TextBoxGroup();
    _Box();
    Box('id=payrpt_curdatastr,style=display:none');
echo $curdatastr;
_Box();
       
       //Get the Spraed sheet headers
       $header=Fileds();
      
      $Readonly = "";
       foreach($header as $k=>$v){
        $Readonly .= ltrim($k,"*").";";
       }
       //echo $Readonly;
       $Readonly = rtrim($Readonly,";");
       Box("style=width:100%;overflow:auto");
           SpreadSheet("rowselect=false,style=width:calc(100% - 0px);margin:auto;margin-top:10px;margin-bottom:6px,id=payrptsumm,multiselect=false,cellfocus=,cellblur=,cellkeypress=,dynamiccolumn=false,dynamicrow=false,minrow=-1,readonly=$Readonly,trimtext=<strong class\=\"altColor\">;</strong>;<strong class\=\"altcolor\">;<strong class\=\"Labels successse\">;<strong class\=\"Labels dangerre\">;<b>;</b>,rownumstart=".($lastpgindex + 1),$header,$dump);
           //trimtext=<strong class\=\"Labels successse\">;</strong>;<strong class\=\"Labels dangerre\">;<b>;</b>
           _Box();
           Box();
           if($pg > 1){
               $DPOST['pg'] = $pg - 1;
               $datastr = $dbo->DataString($DPOST);
           SmallButton("id=prevBtn,logo=arrow-circle-left,style=margin:10px;margin-top:3px;margin-bottom:3px;float:left,title=Previous,onclick=Payment.PaymentReport.PerformLoad('".str_replace(array('=',','),array('\=','\,'),$datastr)."')");
           }
           if($pg != $totpg){
            echo '<div style="width:calc(100% - 125px);text-align:center;float:left;font-size:1.2em;font-weight:bold;margin-top:10px" class="altColor2">'.$pg."/".$totpg."</div>";
           }
           if($pg < $totpg){
               $DPOST['pg'] = $pg + 1;
               $datastr = $dbo->DataString($DPOST);
           SmallButton("id=nextbtn,logo=arrow-circle-right,style=margin:10px;margin-top:3px;margin-bottom:3px;float:right,title=Next,onclick=Payment.PaymentReport.PerformLoad('".str_replace(array('=',','),array('\=','\,'),$datastr)."')");
           }
           ClearFloat();
           _Box();
           
       
}

?>