<?php
ini_set("memory_limit","-1");
$baseurl = "../../../";
$subDir = $_REQUEST['SubDir'];
$configdir = "../../../../../".$subDir;
require_once("../../../general/config.php");
require("../../../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 = "";
   $rset = $set;
   //$set = (int)$set == 0?"":"AND s.StartSes=".$set;
   if(isset($reportType)){
    $searchstr = isset($str)?$str:"";
    //$datefilter = ($from != "" && $to != "")?"AND (p.PayDate >= '$from' AND p.PayDate <= '$to')":"";
    $setfilter = ((int)$set > 0)?"AND s.StartSes = $set":"";
    $entrfilter = ((int)$entr > 0)?"AND s.ModeOfEntry = $entr":"";
    $genderarr = array("","AND s.Gender = 'M'","AND s.Gender = 'F'");
    $genderfilter = $genderarr[$gender];
    $mstatusarr = array("","AND s.MaritalStatus = 'S'","AND s.MaritalStatus = 'M'");
    $mstatusfilter = $mstatusarr[$mstatus];
   $reptypeName = "";
     $sesName = $rses == 0?"":SessionName($rses);

     if($reportType == "rpttypefac"){ //Summary Report
        $reptypeName = "FACULTY/SCHOOL";
        $searchcond = ($searchstr != "")?" AND (f.FacName LIKE '%$searchstr%' OR st.Name LIKE '%$searchstr%')":"";
      $query = "SELECT st.Name as STUDY, f.FacName as 'FACULTY/SCHOOL', COUNT(s.SurName) as NUMSTUD FROM fac_tb f LEFT JOIN study_tb st ON st.ID = f.StudyID LEFT JOIN dept_tb d ON f.FacID = d.FacID LEFT JOIN programme_tb p ON d.DeptID = p.DeptID LEFT JOIN studentinfo_tb s ON p.ProgID = s.ProgID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo"." WHERE 1=1 $searchcond GROUP BY f.FacID";
      //$querylim = $query." LIMIT ".$lmt;

      //$querylim = $query."$searchcond GROUP BY i.ID LIMIT ".$lmt;
     }else if($reportType == "rpttypestate"){
        $reptypeName = "STATE OF ORIGIN";
        $searchcond = ($searchstr != "")?" AND st.StateName LIKE '%".$searchstr."%'":"";
      $query = "SELECT st.StateName as 'STATE OF ORIGIN', COUNT(s.SurName) as NUMSTUD FROM state_tb st LEFT JOIN studentinfo_tb s ON st.StateID = s.StateId $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo"." WHERE 1=1 $searchcond GROUP BY st.StateID ORDER BY st.StateName";
      
      //"SELECT  p.RegNo, p.Info, p.Amt, p.PayDate,p.Bank FROM payhistory_tb p WHERE p.PayID = $itemID  AND p.Ses=$ses $datefilter $searchcond ORDER BY p.PayDate DESC,p.ID DESC"
     }else if($reportType == "studrptprog"){ //Report by Department/programme
        $reptypeName = "DEPARTMENT/PROGRAMME";
        $searchcond = ($searchstr != "")?" AND p.ProgName LIKE '%$searchstr%'":"";
     $query = "SELECT  p.ProgName as 'DEPARTMENT/PROGRAMME', COUNT(s.SurName) as NUMSTUD FROM programme_tb p LEFT JOIN  dept_tb d ON p.DeptID = d.DeptID LEFT JOIN studentinfo_tb s ON s.ProgID = p.ProgID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo WHERE d.FacID = $FacID $searchcond GROUP BY p.ProgID";
    
    }else if($reportType == "studrptlga"){// if($reportType == "paytypefac"){
        $reptypeName = "LGA";
        $searchcond = ($searchstr != "")?" AND l.LGAName LIKE '%$searchstr%'":"";
     $query = "SELECT l.LGAName as 'LOCAL GOVERNMENT AREA', COUNT(s.SurName) as NUMSTUD FROM lga_tb l LEFT JOIN studentinfo_tb s ON l.LGAID = s.LGA $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo WHERE l.StateID = $StateID $searchcond  GROUP BY l.LGAID ORDER BY l.LGAName ASC";
      //$querylim = $query."$searchcond GROUP BY pr.ProgID LIMIT ".$lmt;
    }else if($reportType == "studregtypestud"){
        $reptypeName = "DEPARTMENTAL STUDENTS";
        $searchcond = ($searchstr != "")?" AND (s.RegNo LIKE '%".$searchstr."%' OR s.JambNo LIKE '%$searchstr%' OR s.SurName LIKE '%$searchstr%' OR s.FirstName LIKE '%$searchstr%' OR s.OtherNames LIKE '%$searchstr%' OR s.Phone LIKE '%$searchstr%' OR s.Email LIKE '%$searchstr%' OR p.ProgName LIKE '%$searchstr%')":"";
      $query = "SELECT IF(s.RegNo = '',s.JambNo,s.RegNo) AS 'REG. NO', CONCAT(s.SurName,' ',s.FirstName,' ',s.OtherNames) as 'STUDENT NAME', s.Phone, s.Email,p.ProgName AS 'DEPARTMENT/PROGRAMME' FROM studentinfo_tb s, programme_tb p WHERE s.ProgID = p.ProgID AND s.ProgID = $ProgID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo $searchcond ORDER BY RegNo ASC,JambNo ASC";
    
    }else if($reportType == "studregtypelga"){
        $reptypeName = "LGA STUDENTS";
        $searchcond = ($searchstr != "")?" AND (s.RegNo LIKE '%".$searchstr."%' OR s.JambNo LIKE '%$searchstr%' OR s.SurName LIKE '%$searchstr%' OR s.FirstName LIKE '%$searchstr%' OR s.OtherNames LIKE '%$searchstr%' OR s.Phone LIKE '%$searchstr%' OR s.Email LIKE '%$searchstr%' OR p.ProgName LIKE '%$searchstr%')":"";
        $query = "SELECT IF(s.RegNo = '',s.JambNo,s.RegNo) AS 'REG. NO', CONCAT(s.SurName,' ',s.FirstName,' ',s.OtherNames) as 'STUDENT NAME', s.Phone, s.Email,p.ProgName AS 'DEPARTMENT/PROGRAMME' FROM studentinfo_tb s, programme_tb p WHERE s.ProgID = p.ProgID AND s.LGA = $LGAID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo $searchcond ORDER BY RegNo ASC,JambNo ASC";
    }else if($reportType == "studregall"){
        $reptypeName = "ADMMITTED STUDENT";
        $searchcond = ($searchstr != "")?" AND (s.RegNo LIKE '%".$searchstr."%' OR s.JambNo LIKE '%$searchstr%' OR s.SurName LIKE '%$searchstr%' OR s.FirstName LIKE '%$searchstr%' OR s.OtherNames LIKE '%$searchstr%' OR s.Phone LIKE '%$searchstr%' OR s.Email LIKE '%$searchstr%' OR p.ProgName LIKE '%$searchstr%')":"";
      $query = "SELECT IF(s.RegNo = '',s.JambNo,s.RegNo) AS 'REG. NO', CONCAT(s.SurName,' ',s.FirstName,' ',s.OtherNames) as 'STUDENT NAME', s.Phone, s.Email,p.ProgName AS 'DEPARTMENT/PROGRAMME', IF(TRIM(s.RegNo)!='',IF(s.RegNo != s.JambNo,'Registered','Unregistered'),'Unregistered') as STATUS FROM studentinfo_tb s, programme_tb p WHERE s.ProgID = p.ProgID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 $searchcond ORDER BY RegNo ASC,JambNo ASC";
    }else if($reportType == "studregreg"){
        $reptypeName = "REGISTERED STUDENT";
        $searchcond = ($searchstr != "")?" AND (s.RegNo LIKE '%".$searchstr."%' OR s.JambNo LIKE '%$searchstr%' OR s.SurName LIKE '%$searchstr%' OR s.FirstName LIKE '%$searchstr%' OR s.OtherNames LIKE '%$searchstr%' OR s.Phone LIKE '%$searchstr%' OR s.Email LIKE '%$searchstr%' OR p.ProgName LIKE '%$searchstr%')":"";
      $query = "SELECT IF(s.RegNo = '',s.JambNo,s.RegNo) AS 'REG. NO', CONCAT(s.SurName,' ',s.FirstName,' ',s.OtherNames) as 'STUDENT NAME', s.Phone, s.Email,p.ProgName AS 'DEPARTMENT/PROGRAMME' FROM studentinfo_tb s, programme_tb p WHERE s.ProgID = p.ProgID $setfilter $entrfilter $genderfilter $mstatusfilter AND s.RegLevel>=6 AND TRIM(s.RegNo) != '' AND s.RegNo != s.JambNo $searchcond ORDER BY RegNo ASC,JambNo ASC";
    }
    $sesName = (int)$rset == 0?"ALL SET":SessionName($rset);
     $Genderarr = ["MALE & FEMALE","MALE","FEMALE"];
     $Gender = $Genderarr[$gender];
     $MOE = (int)$entr == 0?"ALL ENTRY":GetMOEName(GetMOEID($entr));
     $mastatusarr = ["SINGLE & MARRIED","SINGLE","MARRIED"];
     $maStatus = $mastatusarr[$mstatus];
     $html = $query;
     $totstud = 0;
               $totamt = 0;
               $cnt =1;
               $sumary = true;
               $toregstudseen = false;
    if($query != ""){
       $qr =  $dbo->RunQuery($query);
       if(is_array($qr)){
           if($qr[1] > 0){
               $thead = "";
               $tbody = "<tbody>";
               $tfoot = "";
              $totfields = 0;
               while($rst = $qr[0]->fetch_assoc()){
                $tr = "<tr><td>$cnt</td>";
                if($totfields == 0){$totfields = count($rst);}
                
                 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];
                    }

                    if($fName == 'NUMSTUD'){
                        $toregstudseen = true;
                        $fName = "REGISTERED STUDENTS";
                        $totstud += (int)$val;
                    }
                   
                    if($cnt == 1){
                        $thead .= "<th>".strtoupper($fName)."</th>"; 
                    }
                    
                    //$val = $fName == "AMOUNT"?number_format($val,2,".",","):$val;
                    $val = str_replace(strtoupper($searchstr),'<strong>'.strtoupper($searchstr).'</strong>',strtoupper($val));
                    $tr .=  "<td style=\"text-transform:uppercase\">".$val."</td>"; 
                 }
                 $tr .= "</tr>";
                 $tbody .= $tr;
               $colspan = $totfields;
               //$totalpayshtml = $sumary?"<th style=\"text-align:left\">$totpay</th>":'';
               //$datefil = $from == ""?"":"($from to $to)";
               
              
              // $tbody .= "</tbody><tfoot><tr><th colspan=\"".$colspan."\" style=\"text-align:right\">Total</th>".$qr[1]."<th style=\"text-align:left\"></th><tr></tfoot>";
              
               $cnt++;
           }
           $expsstrdis = trim($searchstr) == ""?"":"| <i>$searchstr</i>";
           $totstud = !$toregstudseen?$cnt-1:$totstud;
           $header = isset($export)?"<tr><th colspan=\"".($totfields + 1)."\">".$sesName." ".$displaytext." ($Gender | $maStatus | $MOE $expsstrdis)</th></tr>":"";
           $thead = "<thead>".$header."<tr><th>S/N</th>".$thead."</tr></thead>";
           $tbody .= "</tbody>";
           $tfoot = "<tfoot><tr><th colspan=\"".$colspan."\" style=\"text-align:right\">Total</th><th style=\"text-align:left\">".$totstud."</th><tr></tfoot>";
           $html = "<table id=\"regallreporttb\"> $thead $tbody $tfoot</table>";
       }
    }


   }
   
}
}

if(isset($export)){
    exit($html);
}



$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","REGISTRAR")));
$pdf->Panel();
$pdf->InfoBox(1.33,"margin-left:1.5%");
    $pdf->InfoTitle("STATICTICS");
        $pdf->Info("REPORT TYPE:",$reptypeName);//$searchstr
        $pdf->Info("SEARCH:",$searchstr);
        $pdf->Info("TOTAL RECORDS:",$cnt-1);
$pdf->_InfoBox();
$pdf->InfoBox(1.33,"margin-left:1.5%");
    $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("SET:",trim($sesName));
        $pdf->Info("GENDER:",$Gender);
        $pdf->Info("MARITAL ST:",$maStatus);
        $pdf->Info("MODE OF ENTRY:",$MOE);
$pdf->_InfoBox();
$pdf->InfoBox(1.33,"margin-left:1.5%");
    $pdf->InfoTitle("DETAILS");
       // $pdf->Info("Query String:",$quryva);
        $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();

?>