<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
require("../../../../general/getinfo.php");
AllowUser("Troubleshoot"); 

function MoveOrder($order,$issue = "Unknown",$delete=true){
    global $dbo;
$ordermove = $order;
unset($ordermove['ID'],$ordermove['RequestDate'],$ordermove['RequestDate'],$ordermove['ReceiptDate']);//
$ordermove['Issue'] = $issue;
$move = $dbo->Insert("order_ex_tb",$ordermove);
// exit('{"Error":"'.$move.'","Ref":"'.$order['TransNum'].'"}');
if($delete){
  //delete the order 
$del = $dbo->Delete("order_tb","ID=".$order['ID']); 
return 0;
}else{
$del = $dbo->Update("order_tb",["ExpiredRef"=>$order['ExpiredRef'].":".$order['TransNum'].":","Amt"=>$order['Amt']],"ID=".$order['ID']);
return (int)$order['ID'];
}
}
//get the school details
    $schdet = GetSchool();
//require("../../../../epconfig/GenScript/PHP/getinfo.php");
//check if to get valid student only
if(isset($_POST['GetRegNos'])){
    $RegNos = trim($_POST['GetRegNos']);
    if($RegNos == "")exit("#"); //no valid reg no supplid
    //convert to object
    $RegNos = json_decode($RegNos,true);
    //check if it is to be loaded
    if(isset($RegNos['StudyID'])){
        $field = "GROUP_CONCAT((IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo)) SEPARATOR ',') as RegNos";
        $fields = "s.id,s.RegNo";
        $tbs = "studentinfo_tb s";
        //{"SesID":0,"StudyID":0,"FacID":0,"DeptID":0,"ProgID":0,"LvlID":0}
        $studq = ((int)$RegNos['StudyID'] > 0)? "IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != '' AND s.StudyID = ".$RegNos['StudyID']:"IF(TRIM(s.RegNo) = '',s.JambNo,s.RegNo) != ''";
        
        if((int)$RegNos['ProgID'] > 0){
            $studq .= " AND s.ProgID = ".$RegNos['ProgID'];
        }else{
             if((int)$RegNos['DeptID'] > 0){
                    $studq .= " AND s.ProgID = p.ProgID AND d.DeptID = p.DeptID AND d.DeptID = ".$RegNos['DeptID'];
                    $tbs .= ",programme_tb p, dept_tb d";
                }else if((int)$RegNos['FacID'] > 0){
                    $studq .= " AND s.ProgID = p.ProgID AND d.DeptID = p.DeptID AND d.FacID = f.FacID AND f.FacID = ".$RegNos['FacID'];
                    $tbs .= ",programme_tb p, dept_tb d, fac_tb f";
                }
               // $facq = ((int)$RegNos['FacID'] > 0)? "StudyID = ".$RegNos['StudyID']:"StudyID != 0";
        }
        if((int)$RegNos['LvlID'] > 0){
            
            $CurSes = CurrentSes();
            $CurSes = $CurSes['SesID'];
            $studq .= " AND ($CurSes - s.StartSes + IF(TRIM(s.ModeOfEntry) = '',1,IF(s.ModeOfEntry = 'UTME',1,IF(s.ModeOfEntry = 'Direct-Entry',2,(0+s.ModeOfEntry)))))  = ".(int)$RegNos['LvlID'];
            //calculate the startses
        }
        //get the total number character of all student regno + number of regno (to takecare of the commas)
        $extimatedchars = $dbo->SelectFirstRow("studentinfo_tb","(sum(CHAR_LENGTH(if(trim(RegNo)='',JambNo,RegNo)))+count(id)) as len");
         $totalch = !is_array($extimatedchars)?5353674748:$extimatedchars['len'];
        $setmax = $dbo->RunQuery("SET SESSION group_concat_max_len=$totalch;");

        $query = "SELECT $field FROM $tbs WHERE s.RegLevel=6 AND $studq";
        $runquery = $dbo->RunQuery($query);
        if(!is_array($runquery)){
            exit("##"); //Internal Error
        }
$queryrst = $runquery[0]->fetch_assoc();
if(!is_null($queryrst['RegNos'])){
$RegNo = $queryrst['RegNos'];
$RegNoarr = explode(",",$RegNo);
$rtn = array("Total"=>count($RegNoarr),"RegNos"=>$RegNoarr,"TotalBad"=>0,"BadRegNos"=>array(),"Q"=>$query);
}else{
    $rtn = array("Total"=>0,"RegNos"=>array(),"TotalBad"=>0,"BadRegNos"=>array(),"Q"=>$query);  
}

//exit(json_encode($rtn));
      //exit($query);
    }else{
        //get valid students
        
      if(count($RegNos) < 1)exit("#");
      $GoodStud = array(); $BadStud = array();
      $RegNos = array_unique($RegNos);
     // sort($RegNos);
      foreach($RegNos as $RegNo){
          if(trim($RegNo) == "")continue;
          $sRegNo = $dbo->SqlSafe($RegNo);
          //check if exist
          //$chkreg = $dbo->SelectFirstRow("studentinfo_tb st, order_tb od","st.id","(st.RegNo=od.RegNo OR st.JambNo OR (TRIM(st.RegNo)='' && st.JambNo='$RegNo') OR LIMIT 1");
          $q="
          SELECT DISTINCT(od.RegNo) FROM studentinfo_tb st, order_tb od WHERE (st.RegNo=od.RegNo OR st.JambNo=od.RegNo) AND (st.RegNo = '$sRegNo' OR st.JambNo = '$sRegNo' OR st.SurName LIKE '%$sRegNo%' OR st.FirstName LIKE '%$sRegNo%' OR st.OtherNames LIKE '%$sRegNo%') AND (st.ProgID=od.ProgID OR od.ProgID=0) UNION SELECT DISTINCT(od.RegNo) FROM pstudentinfo_tb st, order_tb od WHERE (st.RegNo=od.RegNo OR st.JambNo=od.RegNo) AND (st.RegNo = '$sRegNo' OR st.JambNo = '$sRegNo' OR st.SurName LIKE '%$sRegNo%' OR st.FirstName LIKE '%$sRegNo%' OR st.OtherNames LIKE '%$sRegNo%')
          ";
          $chkreg = $dbo->RunQuery($q);
         // exit($q);
          if(is_array($chkreg) && $chkreg[1] > 0){
              while($sturtn = $chkreg[0]->fetch_array()){
                if(!in_array($sturtn[0],$GoodStud))$GoodStud[] = $sturtn[0];
              }
          }else{
              //check if 
            $BadStud[] = $RegNo;
          }
      }
      $rtn = array("Total"=>count($GoodStud),"RegNos"=>$GoodStud,"TotalBad"=>count($BadStud),"BadRegNos"=>$BadStud,"Q"=>$q);
      
    }
exit(json_encode($rtn));
}

//function to convert an array to datastring without escaping the values
function DataString2($darr){
$rst = "";
    foreach($darr as $k=>$v){
$rst .= $k."=".$v."&";
    }
    return rtrim($rst,"&");
}


$res = "";
//$_POST['RegNo'] ='AK16/NAS/MTH/019';
$dump = '';
$errs = 0; $fix =0; $note = 0;$rsthtml='';$paids=0;$unpaids = 0;$updated = 0;$disnote = "";
//function to write response
function Push($txt,$err = ''){
    global $dump; global $errs; global $fix; global $note; global $fixnow;
    $cnt = "";
    $logo = "terminal";
    if($err == "err"){
        $errs++;
      $cnt = "<strong>(".$errs.")</strong>";
      $logo = "ban";
    }else if($err == "ok"){
        $fix++;
      $cnt = "<strong>(".$fix.")</strong>";
      $logo = $fixnow?"check":"exclamation-triangle";
    }else if($err == "note"){
        $note++;
        $cnt = "<strong>(".$note.")</strong>";
        $logo = "list-alt";
    }
    $dump .= '<div class="'.$err.'"><i style="opacity:0.5" class="fa fa-'.$logo.'"></i>&nbsp;&nbsp;&nbsp;'.$txt.' '.$cnt.'</div>';
}
Push("STARTING...");
//Get the student regno
if(!isset($_POST['RegNo']) || trim($_POST['RegNo']) == "")exit ('<div class="err">Invalid RegNo</div>');
$RegNo = $_POST['RegNo'];
$num = $_POST['Num'];//regno counter
$tot = $_POST['Tot'];
//$fixnow = (int)$_POST['Type'] == 1?true:false; //indicate if fix is to be done
$query = ""; //the fix query
//get the student details
//$studDet = $dbo->SelectFirstRow("studentinfo_tb","","RegNo='".$RegNo."' OR JambNo='".$RegNo."'");
$studDet = GetBasicInfo($RegNo,"","a");
$cnt = 0;
$studName = "Unknown";
if(!is_array($studDet)){
    Push('<div class="err">Invalid Student - Could not read Student Data</div>','note');
    $disnote = "Invalid Student - Could not read Student Data";
    //exit();
}else{
    $studName = $studDet['Name'];
//get student payment orders

$allrst = $dbo->Select("order_tb o LEFT JOIN programme_tb p ON o.ProgID = p.ProgID LEFT JOIN payhistory_tb pay ON pay.TransID = o.TransNum","o.*,COALESCE(p.ProgName,'UNKNOWN') as ProgName,IF(o.ProgID=".$studDet['ProgID'].",1,0) as ValidProg, pay.ProgID as PayProgID","o.RegNo='".$RegNo."' ORDER BY RegDate");
// $allrst = $dbo->Select("order_tb o LEFT JOIN programme_tb p ON o.ProgID = p.ProgID LEFT JOIN payhistory_tb pay ON pay.TransID = o.TransNum","o.*,COALESCE(p.ProgName,'UNKNOWN') as ProgName,IF(o.ProgID=".$studDet['ProgID'].",1,0) as ValidProg, pay.ProgID as PayProgID","o.RegNo='".$RegNo."' AND (o.ProgID=".$studDet['ProgID']." OR o.ProgID=0) ORDER BY RegDate");
if(is_array($allrst) && $allrst[1] > 0){
    $NumRst = $allrst[1];
 Push("$RegNo => ".$allrst[1]." Payment Order(s) Found","note");
 //proccess each result
 Push("Verfying $RegNo Payment Orders ..");
 $rsthtml .= '
     <div>
     <div><strong>'.$RegNo.' - '.$studName.' Payment History</strong></div>';
     $rsthtml .= __Table("rowselect=true,style=width:100%;font-size:0.8em;margin:auto;text-align:left;margin-top:10px,id={$RegNo}_verpays,multiselect=false,data-type=table");
     $rsthtml .= __THeader(array("Ref. No.","Item","Amt","Level",$schdet['SemLabel'],"Policy","Date","Status","For","Remark"),"style=text-align:left");
 
 while($studrst = $allrst[0]->fetch_assoc()){
     $cnt++;
     $oID = $studrst['ID'];
     $Ref = $studrst['TransNum'];
     $Lvl = $studrst['Lvl'];
     $lvlnm = LevelName($Lvl, $studDet['StudyID']);
     $Sem = $studrst['Sem'];
     $SemName = SemesterName($Sem);
     $Sempararr = [1=>"Part","Complete","Full"];
     $SemPart = $studrst['SemPart'];
     $SempartNm = $Sempararr[$SemPart];
     $Amt = $studrst['Amt'];
     $PDate = new DateTime($studrst['RegDate']);
     $dtn = $PDate->format('d/m/Y');
     $PStatus = (int)$studrst['Paid'];
     $pst = $PStatus < 1?"NOT PAID":"PAID";
     $ProgName =  ((int)$studrst['ValidProg'] == 1 && (int)$studrst['PayProgID'] == (int)$studDet['ProgID'])?$studrst['ProgName']:$studrst['ProgName']._LogoButton('onclick=Payment.Troubleshoot.UpdateProg(\''.$studrst['TransNum'].'\');return false;,style=color:#fff;background-color:red;font-size:0.8em;border-radius:50%;width:15px; height:15px;vertical-align:middle;margin-left:3px;padding:0px,logo=exclamation-triangle,title=Update to Current,id=ord_'.$studrst['TransNum']);
     $Rmk = "";
     Push("$RegNo => Proccessing Order: ".$studrst['ID'].", Ref: ".$studrst['TransNum'].", Level: ".$lvlnm.", {$schdet['SemLabel']}: ".$SemName.", Policy: ".$SempartNm.", Date: ".$dtn.", Status: ".$pst);
     Push("**********************************************");
     if($PStatus < 1){ //if not paid
        //if($schdet['PayVerifyType'] == 'DEEP'){
          Push("$RegNo / {$studrst['TransNum']} => Querying Payment Status ....");
         $hpaid = HasPaidRef($studrst['TransNum'],$studrst);   
       // }else{
        //    $hpaid = [0] 
        //}
        //
//echo json_encode($hpaid);
$deleted = false;
$cls = "";
if($hpaid[0] == 1){
    $PStatus = 1;
    Push("$RegNo / {$studrst['TransNum']} => Payment Already Made and Updated");
    $Rmk = "Updated From Gateway";
    $cls = ",class=ok";
    $paids++;
    $updated++;
}else{
    $unpaids++;
    Push("$RegNo / {$studrst['TransNum']} => Payment Not Made - ".$hpaid[5]);
    //checking if order has expired
    Push("$RegNo / {$studrst['TransNum']} => Checking order validity ....");
   
   // $valditydays = $schdet['OrderValidity'];
    $OrderDate = date_create($studrst['RegDate']);
    $Now=date_create(date("Y-m-d"));
    $diff=date_diff($OrderDate,$Now);
    $days = (int)$diff->format('%R%a');
    //get the validity days
    if($days > (int)$schdet['OrderValidity']){ //if not valid
        Push("$RegNo / {$studrst['TransNum']} => Order has expired","err");  
      //delete the order 
      MoveOrder($studrst,"Expired by Admin");
      //$del = $dbo->Delete("order_tb","ID=".$oID);
      Push("$RegNo / {$studrst['TransNum']} => Order Delete"); 
      $Rmk = "Order Deleted (Expired)";
      $deleted = true;
      //exit('{"Error":"Order Expired and Deleted"}');
}else{
    Push("$RegNo / {$studrst['TransNum']} => Order is Valid","ok"); 
    $Rmk = "Valid";
}
        //try to query payment
     }

    }else{ //if paid
      $paids++;
    }
    if($PStatus < 1){// if not paid
        $pst = "NOT PAID";
        $cls = ",class=err";
    }else{//if paid confirm in payhisory
        Push("$RegNo / {$studrst['TransNum']} => Getting Payment Details ....");
       $paydet = $dbo->SelectFirstRow("payhistory_tb","","TransID='".$studrst['TransNum']."'");
       if(!is_array($paydet)){ //if not found 
          //update the order back to not paid
          Push("$RegNo / {$studrst['TransNum']} => Payment Detais Not Found","err");
          $upd = $dbo->Update("order_tb",["paid"=>0],"ID=".$studrst['ID']);
          $paids--;
         // $unpaids++;
          Push("$RegNo / {$studrst['TransNum']} => Order Status Reversed","ok");
          $pst = "NOT PAID";
          $cls = ",class=err";
       }else{
        Push("$RegNo / {$studrst['TransNum']} => Payment Details Found","ok");
        $ndt = new DateTime($paydet['PayDate']);
        $dtn = $ndt->format('d/m/Y');
        $pst = "PAID";
        $cls = "";
       }
        
    }
     
     //add to the payment tables
 //,"Item","Amt","Level","Semester","Policy","Date","Status","Remark"
     //5$curunregcourses = $curunregcoursesArr[1];
     $rsthtml .= __TRecord(array($studrst['TransNum'],$studrst['ItemName'],number_format((float)$studrst['Amt'],2),$lvlnm,$SemName,$SempartNm,$dtn,$pst,$ProgName,$Rmk),"");
     
     
   
     Push("**********************************************");

     
    }
    $disnote = $allrst[1]." Order(s) Proccesed";
    Push($disnote,"note");
    $rsthtml .=___Table();
$rsthtml .= '</div>';
}else{ //if no order found

    $disnote = "No Payment Order Found";
    Push($disnote,"note");
}
}



//echo '<div id="'.$RegNo.'">&nbsp;</div>';
$distray = (int)$tot > 1?"none":"block";
if((int)$num < 1){
Box("class=ep-animate-opacity");
    echo $rsthtml;
    echo '
        <div style="padding:6px">
    <div style="float:left;width:70%"><strong class="err">'.$errs.' Issues</strong> | <strong class="ok">'.$fix.' Fixes</strong>  | <strong class="">'.$note.' Notes</strong></div>
    <div style="float:right;width:30%">';
    LogoButton('onclick=_(\''.$RegNo.'_vtray\').ToggleShowHide();return false;,style=display:block;float:right;color:#fff,class=altBgColor2,logo=list-alt,text=Process Tray');
    echo '<div style="clear:both"></div></div><div style="clear:both"></div>
    <div style="margin:auto;padding:6px;margin-top:5px;background-color:#fff;border:#ccc 1px solid;min-height:100px;max-height:200px;display:'.$distray.';overflow:auto" id="'.$RegNo.'_vtray">
    '.$dump.'
    </div>
    </div>
    
    ';
    _Box();
}else{
    FlatTRecord("class=ep-animate-opacity");
    FlatTData($num,"size=5");
    FlatTData("$RegNo - $studName","size=40");
    FlatTData($paids,"size=10");
    FlatTData($unpaids,"size=10,style=font-weight:bold,class=altColor");
    FlatTData($updated,"size=10,style=font-weight:bold,class=ok");
    FlatTData($disnote,"size=20");
    FlatTData('<i class="fa fa-ellipsis-h"></i>',"size=5,style=text-align:left;cursor:pointer,onclick=_('".$RegNo."_vdet').ToggleShowHide(),class=altColor2Hover,title=View Details");
   /* echo '
          <div style="clear:both"></div>

          <div class="subbx" style="display:none" id="'.$RegNo.'_det">'; */
FlatTDataSub("id={$RegNo}_vdet,style=display:$distray");
            echo $rsthtml;
         echo '
        <div style="padding:6px">
    <div style="float:left;width:70%"><strong class="err">'.$errs.' Issues</strong> | <strong class="ok">'.$fix.' Fixes</strong>  | <strong class="">'.$note.' Notes</strong></div>
    <div style="float:right;width:30%">';
    LogoButton('onclick=_(\''.$RegNo.'_vtray\').ToggleShowHide();return false;,style=display:block;float:right;color:#fff,class=altBgColor2,logo=list-alt,text=Process Tray');
    /* echo '<button onclick="_(\''.$RegNo.'_tray\').ToggleShowHide()" style="display:block;float:right"  class="altBgColor2 bbtn"><i class="fa fa-list-alt"></i> Process Tray</botton>'; */
    echo'<div style="clear:both"></div></div><div style="clear:both"></div>
    <div style="margin:auto;padding:6px;margin-top:5px;background-color:#fff;border:#ccc 1px solid;min-height:100px;max-height:200px;display:none;overflow:auto" id="'.$RegNo.'_vtray">
    '.$dump.'
    </div>
    </div>';
        //echo '</div>';
        _FlatTDataSub();
          _FlatTRecord();
}

         // echo '<div id="'.$RegNo.'_scroll" style=""></div>';
?>