<?php
ini_set("memory_limit","-1");
$baseurl = "../../../";
$configdir = "../../../../../".urldecode($_REQUEST['SubDir']);
require_once($baseurl."general/config.php");
require($baseurl."general/getinfo.php");
require_once "../../../general/TaquaLB/Elements/Elements.php";
require_once $configdir.$dbo->Config['Require']."PDF/mpdf60/mpdf.php";
require_once "../../../general/TaquaLB/Elements/Script/pdf.php";

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 "";
}
if(!isset($_REQUEST['data'])){
    $html = "INVALID PARAMETER";
}else{
    $dataobj = json_decode($_REQUEST['data'],true);
    extract($dataobj);
    //get user details
    $UserDet = $dbo->SelectFirstRow("user_tb","","UserID=".$UID);
    $PrintDate = date("d/M/Y");
   $PrintTime = date("h:i A");
   $totalrst = 0;
   $html = "NO RECORD FOUND";
   $query = "";
   $rses = $ses;
   $ses = (int)$ses == 0?"":"AND p.Ses=".$ses;
   if(isset($reportType)){
    $from = isset($fr)?ToMySQLDate($fr):"";
    $to = isset($to)?ToMySQLDate($to):"";
    $searchstr = isset($str)?$str:"";
    $datefilter = ($from != "" && $to != "")?"AND (p.PayDate >= '$from' AND p.PayDate <= '$to')":"";
    //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' ";
    }

$chnfcond = ""; 
    //include the channel field
    if((int)$offline == 1 && (int)$online == 1){
        $chnfcond =", IF(LCASE(p.Bank) = 'manual pay','OFFLINE','ONLINE') as CHANNEL";
    }
    //AKSCOE **************************
   // $datefilter .= " AND CHAR_LENGTH(p.TransID) = 12 AND p.Bank = '' ";
    //AKSCOE *****************************
    //reformat date filter
    $fromarr = explode("-",$from);
     $toarr = explode("-",$to);
    //$from = $from != ""?date("j/M/Y",mktime(0,0,0,$fromarr[2],$fromarr[1],$fromarr[0])):"";
//$to = $to != ""?date("j-M-Y",mktime(0,0,0,$toarr[2],$toarr[1],$toarr[0])):""; 

     $sesName = $rses == 0?"":SessionName($rses);
     include "../../Pages/Scripts/Payment/Reports/".$reportType.".php";
      list($query,$querylim) = ReportQuery();
      //$html = $querylim;
     /* $order = "s.id";
      if(isset($OrderBy) && trim($OrderBy) != ""){
        $orderarr = ["ordregno"=>"s.RegNo, s.JambNo","ordpaid"=>"p.Amt","orddate"=>"p.PayDate"];
        if(isset($orderarr[$OrderBy])){
          $order = $orderarr[$OrderBy];
        }
      }

     $query =  "SELECT IF(s.RegNo = '', s.JambNo,s.RegNo) as SRegNo, CONCAT(s.SurName,'', s.FirstName,' ', s.OtherNames) as StudName,p.Info,p.Amt, p.TransID, p.Amt, DATE_FORMAT(p.PayDate,'%c/%m/%Y') as PayDate, p.itemNum, p.PayID, p.CollectBank, IF(LCASE(p.Bank) = 'manual pay','OFFLINE','ONLINE') as Channel, p.PayBrkDn FROM studentinfo_tb s LEFT JOIN payhistory_tb p ON (s.RegNo = p.RegNo OR s.JambNo = p.RegNo)  AND p.PayID = $PayID  AND p.Lvl=".$dbo->SqlSafe($Lvl)." AND p.Sem=".$dbo->SqlSafe($Sem)." $ses  WHERE s.ProgID = ".$dbo->SqlSafe($ProgID)." AND s.StartSes = ".$dbo->SqlSafe($StartSes)." AND s.ClassID = ".$dbo->SqlSafe($ClassID)." AND s.ModeOfEntry = ".$dbo->SqlSafe($MOE)." $searchcond ORDER BY $order "; */



     /* $query = "SELECT  p.RegNo as 'REG ID', p.Info as '_Name' , p.PayDate as 'DATE', p.Info as '_DeptName', p.Info as '_FacName', p.Info as '_FacID', p.PayID, p.CollectBank as 'RECIEVING BANK' $chnfcond , p.Amt AS AMOUNT FROM payhistory_tb p WHERE p.Info LIKE '%\"ProgID\":\"$progID\"%' $ses $datefilter ORDER BY p.PayDate DESC,p.ID DESC"; */
    
    }
     $html = "";
     $totpay = 0;
               $totstat = 0;$totamt=0;$totpays=0;$totAmts=0;$overall=0;
               $cnt =1;
               $sumary = true;
    if($query != ""){
        $thead = "";
        //form the headers
        $headers = Fileds();
        if(count($headers) > 0){ 
         $thead = '<thead><tr><th>S/N</th>';
          foreach($headers as $head){
            $thead .= "<th>".strtoupper($head)."</th>";
          }
          $thead .= '<th>REMARK</th></tr></thead>';
          
        }
        //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];
        $tbody = "";
        $cnt = 0;
        if(is_array($rpt)){
            
            if($rpt[1] > 0){
               // MessageBack($rst);
               //echo $rst;
                $rstrec = $rst[0]->fetch_array();
                $totpays = $rstrec['Payments'];
                $totAmts = $rstrec['Sums'];
                $tbody = "<tbody>";
                //loop thru all records
                 while($rec = $rpt[0]->fetch_array()){
                    $cnt++;

                   // $overall += 1;
                    //process the report and add to spreate sheet data
                   $recs = FormRecord();
                   //ogo":"*print","info":"Print","Action":"Payment.PaymentReport.PrintRc('4461842803')
                   if(isset($recs['disable']))unset($recs['disable']);
                   if(isset($recs['logo']))unset($recs['logo']);
                   if(isset($recs['info']))unset($recs['info']);
                   if(isset($recs['Action']))unset($recs['Action']);
                   $tbody .= '<tr><td>'.$cnt.'</td><td style="text-transform:uppercase" >'.implode('</td><td style="text-transform:uppercase" >',$recs)."</td><td>&nbsp;</td></tr>";
                   //$html .= "<br/>".json_encode($recs);
                }
                $tbody .= "</tbody>"; 
            }
        }
        $html .= "<table id=\"allreporttb\"> $thead $tbody </table>";
        //$html .= "hfhfh";
       /*if(is_array($qr)){
           if($qr[1] > 0){
                $thead = "";
               $tbody = "<tbody>";
               $tfoot = "";
              $totfields = 0;
              //payitem details
              $paitem = $dbo->SelectFirstRow("item_tb","PayBrkDn","ID=".$PayID);
              if(is_array($paitem)){
                  //1. get the class pay items ["payID"=>"Pay Title"]
                  $PayBrkDn = $paitem['PayBrkDn'];
                  $payitemsall = NULL;
              
              


             // $cntfileds = 0;
               while($rst = $qr[0]->fetch_assoc()){
                   if(is_null($payitemsall)){ //if default items not already loaded
                    //use the fir   st student in the class to get the possible payment breakdown
                    
                   }
                $tr = "<tr><td>$cnt</td>";
                //if($totfields == 0){$totfields = count($rst);}

                //2. Get the student pay breakdown

                //3. Loop through the items

                //3.1. to form the new dump record

                //3.2 incase of none existence item in the class pay item array - add to the others column

                //form the tds;

                //Note: Others column will contain the item name and amount

 
                
                 foreach($rst as $fName=>$val){
                     $fnameinit = substr($fName,0,1);
                     
                     $fName = $fnameinit == "_"?ltrim($fName,'_'):$fName;
                     if($fnameinit == "_"){ //if from json string (Info)
                        $val = json_decode($val,true);
                        $val = $val[$fName];
                    }
                    
                     //AKSCOE RECIEVING BANK
                     //***********************************************
                     if($fName == 'PayID' || $fName == 'FacID'){
                        continue;
                    }
                     
                     //***********************************************
                    if($cnt == 1){
                        $thead .= "<th>".strtoupper($fName)."</th>"; 
                        $totfields++;
                    }
                    
                    $val = $fName == "AMOUNT"?number_format($val,2,".",","):$val;
                    
                    $tr .=  "<td style=\"text-transform:uppercase\">".$val."</td>"; 
                 }
                 //calculate total payment
                if(isset($rst['PAYMENT'])){
                    $totpay += (int)$rst['PAYMENT'];
                    $sumary = true;
                }else{
                    $totpay = $cnt;
                    $sumary = false;
                }
                //calculate total amount
                $totamt += (float)$rst['AMOUNT'];
                 if($cnt == 0){
                   $thead .= "</tr></thead>";
                 }
                 $tbody .= $tr."</tr>";
                 $cnt++;
               }
              }else{

              }
              
               $colspan = $totfields-1;
               //$totalpayshtml = $sumary?"<th style=\"text-align:left\">$totpay</th>":'<th></th>';
               $totalpayshtml = "<th style=\"text-align:left\">$totpay</th>";
               $datefil = $from == ""?"":"($from to $to)";
               $header = isset($export)?"<tr><th colspan=\"".($totfields + 1)."\">".$sesName." ".$displaytext." $datefil</th></tr>":"";
               $thead = "<thead>$header<tr><th>S/N</th>".$thead;
               $tbody .= "</tbody><tfoot><tr><th colspan=\"".$colspan."\" style=\"text-align:right\">Total</th>".$totalpayshtml."<th style=\"text-align:left\">".number_format($totamt,2,".",",")."</th><tr></tfoot>"; 
               $html = "<table id=\"allreporttb\"> $thead $tbody </table>";
           }
       }*/
    }

$totAmts = number_format((float)$totAmts, 2, '.', ',');
    
    $chaneldis = "";
if((int)$offline == 1 && (int)$online == 1){
    $chaneldis = "ONLINE &amp; OFFLINE";
}else if((int)$offline == 1){
    $chaneldis = "OFFLINE";
}else{
    $chaneldis = "ONLINE"; 
}
   }
   
   
/* [
      "DateFilter"=>($from != "" && $to != "")?date("j-M-Y",mktime(0,0,0,$fromarr[1],$fromarr[2],$fromarr[0]))." "._Icon("arrow-right altColor2")." ".date("j-M-Y",mktime(0,0,0,$toarr[1],$toarr[2],$toarr[0])):"",
      "Channel"=>$chaneldis,
      "Session"=>$sesName,
      "PaymentType"=>$payname,
      "Level"=>$PayLevel,
      "Semester"=>$PaySem,
      "TotalPayment"=>$_POST['TotalPaidStud'],
      "ExpectedPayment"=>$totpays,
      "TotalAmount"=>$totAmts,
      "Class"=>$lvlname." ".$classname,
      "ClassTitle"=>$classdis,
      "Study"=>$studyName,
      "StudyTitle"=>$studyTitle,
      "Prog"=>$progName,
      "ProgTitle"=>$progTitle
    ] */
$ReportDetails = Summary();
//$html .= json_encode($ReportDetails);
$ReportDetails = $ReportDetails[2];
if(isset($export)){
    exit($html);
}


/* "DateFilter"=>($from != "" && $to != "")?date("j-M-Y",mktime(0,0,0,$fromarr[1],$fromarr[2],$fromarr[0]))." "._Icon("arrow-right altColor2")." ".date("j-M-Y",mktime(0,0,0,$toarr[1],$toarr[2],$toarr[0])):"",
        "Channel"=>$chaneldis,
        "Session"=>$sesName,
        "Semester"=>$PaySem,
        "TotalPayment"=>$TNumPay,
        "TotalAmount"=>"$approstr ".number_format($TAmt,2),
        "SemLabel"=>$sch['SemLabel'],
        "ItemName"=>$itemName */


$pdf = new PDFPrinter();
$pdf->SetBasePath($configdir."Files/");
//$pdf->WaterMarkText("AKSU",0.1);
$pdf->Banner($displaytext,array("LogoSize"=>"80*80","WaterMark"=>"Abbr"));
$pdf->FooterNote($displaytext,$pdf->Signataries(array("STAFF","BURSAR")));
$pdf->Panel();
$pdf->InfoBox(1,"margin-left:7px");
    $pdf->InfoTitle("REPORT");
    $pdf->Info("SESSION:",$ReportDetails["Session"]);
        $pdf->Info(strtoupper($ReportDetails['SemLabel']).":",$ReportDetails['Semester']);
        $pdf->Info("PAYMENT ITEM",$ReportDetails['ItemName']);
        // $pdf->Info("&nbsp;","&nbsp;");
/* 
        $studtitle = "SCHOOL";
        $studn = "";
        //form study programme
        if(trim($ReportDetails['Study']) != ""){
            $studtitle = $ReportDetails['StudyTitle'];
            $studn = $ReportDetails['Study'];
        }

        if(trim($ReportDetails['Prog']) != ""){
            // $studtitle .= trim($ReportDetails['Study']) != ""?" / ".$ReportDetails['ProgTitle']:$ReportDetails['ProgTitle'];
            $studn .= trim($ReportDetails['Study']) != ""?" / ".$ReportDetails['Prog']:$ReportDetails['Prog'];
        }
        
        $pdf->Info(strtoupper($studtitle).":",$studn);
        $pdf->Info("CLASS HEAD:",$ReportDetails['ClassHead']); */
$pdf->_InfoBox();
$pdf->InfoBox(1,"margin-left:7px");
    $pdf->InfoTitle("STATICTICS");
        $pdf->Info("PAYMENT:",$ReportDetails['TotalPayment']);
        $pdf->Info("AMOUNT:","<strong>".$ReportDetails['TotalAmount']."</strong>");
        $pdf->Info("RECORD:",$cnt);
        // $pdf->Info("&nbsp;","&nbsp;");
$pdf->_InfoBox();
$pdf->InfoBox(1,"margin-left:7px");
    $pdf->InfoTitle("FILTER");
    
    // $arrRec = ($from != "" && $to != "")?date("j-M-Y",mktime(0,0,0,$fromarr[1],$fromarr[2],$fromarr[0]))." - ".date("j-M-Y",mktime(0,0,0,$toarr[1],$toarr
   // [2],$toarr[0])):"";

       // $pdf->Info("Query String:",$quryva);
        
        $pdf->Info("SEARCH:",htmlspecialchars($searchstr));
        $pdf->Info("PERIOD:",$ReportDetails["DateFilter"]);
        $pdf->Info("CHANNEL:",$ReportDetails["Channel"]);
$pdf->_InfoBox();
$pdf->InfoBox(1,"margin-left:7px");
    $pdf->InfoTitle("DETAILS");
       
        $pdf->Info("REPORT BY:",$UserDet['UserName']);
        $pdf->Info("DATE:",date("d-M-Y"));
        $pdf->Info("TIME:",date("h:i:s A"));
$pdf->_InfoBox();
$pdf->_Panel();
$pdf->Dump($html);
$pdf->HTML();
/*echo '
<div style="width:95%; margin:auto;margin-top:100px;">
<div style="width:200px;float:left;border-top:#000 solid thin;padding-top:5px;text-align:center;font-style:italic;font-size:1.1em">HOD</div>
<div style="width:200px;float:right;border-top:#000 solid thin;padding-top:5px;text-align:center;font-style:italic;font-size:1.1em">Staff/User</div>
</div>';*/

$pdf->_HTML();
$pdf->Finish();











?>