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

$errstr = "";
function Logg($Stud,$Error=""){
    global $ErrorArr;
    global $errstr;
    if(isset($ErrorArr[$Stud])){
        $ErrorArr[$Stud][] = $Error;
    }else{
        $ErrorArr[$Stud] = [$Error];
    }
    $errstr .= __FlatTRecord("class=ep-animate-opacity,style=text-align:unset");
    $errstr .= __FlatTData(count($ErrorArr),"size=5");
    $errstr .= __FlatTData($Stud,"size=40");
    $errstr .= __FlatTData($Error,"size=55");
    $errstr .= ___FlatTRecord();
}

function InsertData($tb,$columnInd=[],$rownum,$fieldsValeus=[]){
    return QueryData($tb,$columnInd,"",$rownum,$fieldsValeus,true);
}

function QueryData($tb,$columnInd=[],$cond="",$rownum,$fieldsValeus=[],$insert=false){
    global $dbo;
    $fieldarr = [1=>"id","RegNo","JambNo","SurName","FirstName","OtherNames","Gender","StateId","LGA","Phone","Addrs","AccessCode"];
    $qy = $insert? "INSERT INTO {$tb} SET ": "UPDATE {$tb} SET ";
    foreach($columnInd as $colid){
        if(!isset($fieldarr[$colid]))continue;
        $field = $fieldarr[$colid];
        $value = isset($_POST[$rownum.'_'.$colid])?$_POST[$rownum.'_'.$colid]:"";
        $sep = (is_string($value)  || (empty($value) && !is_null($value)))?"'":"";
        $value = is_null($value)?'NULL':$dbo->SqlSafe($value);
       $qy .= "`".$field ."` = ". $sep . $value . $sep . ", "; 
    }
    if(count($fieldsValeus) > 0){
        foreach($fieldsValeus as $field => $value){
            $sep = (is_string($value)  || (empty($value) && !is_null($value)))?"'":"";
            $value = is_null($value)?'NULL':$dbo->SqlSafe($value);
           $qy .= "`".$field ."` = ". $sep . $value . $sep . ", "; 
        }
    }
    $qy = trim($qy,", ");
    if($cond != ""){
        $qy .= " WHERE ". $cond ; 
     }
     $qy .= ";";
     return $qy;
}

if(!isset($_POST['preloadstudy']) || (int)$_POST['preloadstudy'] < 1 || !isset($_POST['preloadprog']) || (int)$_POST['preloadprog'] < 1 || !isset($_POST['preloadstartses']) || (int)$_POST['preloadstartses'] < 1 ){
    Error("INVALID PARAMETER","Select required academic details");
    exit;
}

$preloadstudy = (int)$_POST['preloadstudy'];
$preloadprog = (int)$_POST['preloadprog'];
$preloadstartses = (int)$_POST['preloadstartses'];
$preloadclass = (!isset($_POST['preloadclass']) || (int)$_POST['preloadclass'] < 1) ?0:(int)$_POST['preloadclass'];
$preloadmoe = (!isset($_POST['preloadmoe']) || (int)$_POST['preloadmoe'] < 1) ?1:(int)$_POST['preloadmoe'];

//exit(json_encode(["Study:"=>$preloadstudy,"Prog:"=>$preloadprog,"StartSes:"=>$preloadstartses,"Class:"=>$preloadclass,"MOE:"=>$preloadmoe]))

//get the total entered rechords
$TotalRec = (int)$_POST['MaxDataRow'];
//exit("".$TotalRec);
$ErrorArr = [];

$query = "";

$studSet = StudentSettings();
$formdet = STUDREG();

if($TotalRec > 0){
    for($i=1;$i<=$TotalRec;$i++){
        //get the student db id
        $StudID = 0;
        $ACID = 0;
        //get the old and new regnos
        $NewRegNo = isset($_POST[$i.'_2'])?$_POST[$i.'_2']:"";
        $NewJambNo = isset($_POST[$i.'_3'])?$_POST[$i.'_3']:"";
        $OldRegNo = isset($_POST[$i.'_13'])?$_POST[$i.'_13']:"";
        $OldJambNo = isset($_POST[$i.'_14'])?$_POST[$i.'_14']:"";
        $ACID = isset($_POST[$i.'_15'])?(int)$_POST[$i.'_15']:0;
        $ErrorRegNo = trim($OldRegNo != "")?$OldRegNo:(trim($OldJambNo != "")?$OldJambNo:"Row $i");
        //check if student record is deleted
        if(isset($_POST[$i.'_deleted']) && trim(strtolower($_POST[$i.'_deleted'])) == "true"){
            Logg($ErrorRegNo,"Student Update Ignored: Delete operation not allowed in Class List Module");
            continue;
        }

        $requiredset = true;
        foreach ([4,5,7,8,9] as $colmnNum) {
            $rcell = $i.'_'.$colmnNum;
            if(!isset($_POST[$rcell]) || trim($_POST[$rcell]) == ""){
                $requiredset = false;
               break;
            }
        }
        
        if(!isset($_POST[$i.'_10']) || trim($_POST[$i.'_10']) == ""){ //make sure phone is empty string
            $_POST[$i.'_10'] = "";
        }

        //set default accesscode
        if(!isset($_POST[$i.'_12']) || trim($_POST[$i.'_12']) == ""){ 
            // $_POST[$i.'_12'] = FormAC();
            $_POST[$i.'_12'] = "myschool";
        }

        //check requied fields
        if($requiredset == false){
            Logg($ErrorRegNo,"Student Update Ignored: Invalid Data - Surname, Firstname, Gender, State, LGA, Phone Number and Access Code are required");
            continue;
        }

        

        $allowaccesscodeupdate = true;
        if(isset($_POST[$i.'_12']) && trim($_POST[$i.'_12']) != ""){
            $payreg = trim($OldRegNo) == ""?$OldJambNo:$OldRegNo;
            if($studSet['AdminVerifyPay'] == 'TRUE'){ //if admin payment verification is enabled
                $payacc = HasPaid($payreg,$formdet['PayID'],1,3,3,1,-1);
                    if($payacc[0] != 1){
                        Logg($ErrorRegNo,"Student Update Ignored: Student Accesscode can only be assigned when required payment is made - ".json_encode($payacc));
                        $allowaccesscodeupdate = false;
                        continue;
                    }else{
                        //if paid

                    }
                }
        }else{
            $allowaccesscodeupdate = false;
        }


         
        if(isset($_POST[$i.'_1']) && (int)$_POST[$i.'_1'] > 0){ //if it is an already student
            //If no RegNo Found
        if(trim($NewRegNo) == "" && trim($OldRegNo) == "" && trim($OldJambNo) == ""){
            Logg($ErrorRegNo,"Student Update Ignored: No Valid Registration Number Found");
            continue;
        }
            $StudID = (int)$_POST[$i.'_1'];
           //if no regno change done
           if(strtolower(trim($OldRegNo)) == strtolower(trim($NewRegNo))){
               $query .= QueryData("studentinfo_tb",[4,5,6,7,8,9,10,11],"id=".$dbo->SqlSafe($StudID),$i,["RegLevel"=>6]);
               if($allowaccesscodeupdate){
                   if($ACID > 0){ //if already have acesscode record
                    $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i);
                   }else{
                       $UseRegNo = trim($OldRegNo) == ""?$OldJambNo:$OldRegNo;
                       $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$UseRegNo]);
                   }
               }
           }else{ //if changes done
            //if new RegNo is empty - meaning Rgnomber cleard
            if(trim($NewRegNo) == ""){
                $OtherField = ["RegNo"=>"","AutoGenReg"=>"FALSE","RegLevel"=>6];
                $globalupd = true;
                $UpdOldReg = $OldRegNo;
                $UpdNewReg = $OldJambNo;
                if(trim($OldJambNo) == ""){ //if no jambno set before
                  //use the old regno
                  $OtherField["JambNo"] = $OldRegNo;
                  $globalupd = false; //no need for global update
                  $UpdNewReg = $OldRegNo;
                }
                $query .= QueryData("studentinfo_tb",[4,5,6,7,8,9,10,11],"id=".$dbo->SqlSafe($StudID),$i,$OtherField);
                if($globalupd){//if global update is to be done
                    foreach(["coursereg_tb","order_tb","payhistory_tb","result_tb","wallet_tb"] as $tb){
                        $query .= QueryData($tb,[],"RegNo='".$dbo->SqlSafe($UpdOldReg)."'",$i,["RegNo"=>$UpdNewReg]);
                    }
                }
                if($allowaccesscodeupdate){
                    if($ACID > 0){ //if already have acesscode record
                     $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i,["JambNo"=>$UpdNewReg]);
                    }else{
                        $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$UpdNewReg]);
                    }
                }
            }else{ //if new RegNo set
                $chk = $dbo->SelectFirstRow("studentinfo_tb","id","RegNo='".$dbo->SqlSafe($NewRegNo)."' OR JambNo='".$dbo->SqlSafe($NewRegNo)."'");
             if(is_array($chk)){
                Logg($ErrorRegNo,"Student Update Ignored: New Registration Number Already Exist");
                continue;
              }
                $OtherField = ["RegNo"=>$NewRegNo,"AutoGenReg"=>"TRUE","RegLevel"=>6];
                $query .= QueryData("studentinfo_tb",[4,5,6,7,8,9,10,11],"id=".$dbo->SqlSafe($StudID),$i,$OtherField);
                if(trim($OldRegNo) != ""){ //if oldregno exist, update occurence of OldRegNo to New RegNo globally
                    $UpdOldReg = $OldRegNo;
                    $UpdNewReg = $NewRegNo;
                    foreach(["coursereg_tb","order_tb","payhistory_tb","result_tb","wallet_tb"] as $tb){
                        $query .= QueryData($tb,[],"RegNo='".$dbo->SqlSafe($UpdOldReg)."'",$i,["RegNo"=>$UpdNewReg]);
                    }
                    if($allowaccesscodeupdate){
                        if($ACID > 0){ //if already have acesscode record
                         $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i,["JambNo"=>$UpdNewReg]);
                        }else{
                            $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$UpdNewReg]);
                        }
                    }
                }else if(trim($OldJambNo) != ""){
                    $UpdOldReg = $OldJambNo;
                    $UpdNewReg = $NewRegNo;
                    foreach(["coursereg_tb","order_tb","payhistory_tb","result_tb","wallet_tb"] as $tb){
                        $query .= QueryData($tb,[],"RegNo='".$dbo->SqlSafe($UpdOldReg)."'",$i,["RegNo"=>$UpdNewReg]);
                    }
                    if($allowaccesscodeupdate){
                        if($ACID > 0){ //if already have acesscode record
                         $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i,["JambNo"=>$UpdNewReg]);
                        }else{
                            $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$UpdNewReg]);
                        }
                    }
                }
            }
           }
        }else{ //if new entring
            $Phone = $_POST[$i.'_10'];
            //Use Random number instead of phone number
            /* do{
                //generate a random number
                $Phone = strtoupper(substr($_POST[$i.'_4'],0,2)).mt_rand(100000,999999);
                $chk = $dbo->SelectFirstRow("studentinfo_tb","id","RegNo='".$dbo->SqlSafe($Phone)."' OR JambNo='".$dbo->SqlSafe($Phone)."'");
            }while(is_array($chk)); */
            $Phone = AutoGenRegNoRand(strtoupper(substr($_POST[$i.'_4'],0,2)));
            $accdet = ["StudyID"=>$preloadstudy,"ProgID"=>$preloadprog,"StartSes"=>$preloadstartses,"ClassID"=>$preloadclass,"ModeOfEntry"=>$preloadmoe,"RegLevel"=>6,"AdmSes"=>$preloadstartses,"RegDate"=>date('Y-m-d'),"Accept"=>1];
            //["Study:"=>$preloadstudy,"Prog:"=>$preloadprog,"StartSes:"=>$preloadstartses,"Class:"=>$preloadclass,"MOE:"=>$preloadmoe]
            if(trim($NewRegNo) == ""){//if no regno specified
              //get the phone number,
              
              //check if phone already exist as JambNo
              /* $chk = $dbo->SelectFirstRow("studentinfo_tb","id","RegNo='".$dbo->SqlSafe($Phone)."' OR JambNo='".$dbo->SqlSafe($Phone)."'");
              if(is_array($chk)){
                Logg($ErrorRegNo,"Student Inclusion Ignored: Invalid RegNo. and phone number - $Phone already use by another student as RegNo");
                continue;
              } */

              $query .=  InsertData("studentinfo_tb",[4,5,6,7,8,9,10,11],$i,array_merge($accdet,["RegNo"=>"","JambNo"=>$Phone]));
              if($allowaccesscodeupdate){
                if($ACID > 0){ //if already have acesscode record
                 $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i,["JambNo"=>$Phone]);
                }else{
                    $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$Phone]);
                }
            }

            }else{ //if RegNo set
             //check if already exist as JambNo
             $chk = $dbo->SelectFirstRow("studentinfo_tb","id","RegNo='".$dbo->SqlSafe($NewRegNo)."' OR JambNo='".$dbo->SqlSafe($NewRegNo)."'");
             if(is_array($chk)){
                Logg($ErrorRegNo,"Student Inclusion Ignored: Student Aready Exist");
                continue;
              }
              $query .=  InsertData("studentinfo_tb",[4,5,6,7,8,9,10,11],$i,array_merge($accdet,["RegNo"=>$NewRegNo,"JambNo"=>$Phone]));
            if($allowaccesscodeupdate){
                if($ACID > 0){ //if already have acesscode record
                 $query .= QueryData("accesscode_tb",[12],"ID=".$dbo->SqlSafe($ACID),$i,["JambNo"=>$NewRegNo]);
                }else{
                    $query .=  InsertData("accesscode_tb",[12],$i,["RegNo"=>"","JambNo"=>$NewRegNo]);
                }
            }
            }
            
        }
    }
}
//exit($query);
//Logg("Query",$query);
//Logg("Post",$dbo->DataString($_POST));
if(trim($query) != ""){
    $dump = $dbo->Connection->multi_query($query);
	 if(!$dump){
        exit(json_encode(["Success"=>"FALSE","Errors"=>$errstr,"Message"=>"#Server Error: ".$dbo->Connection->error]));
	 }else{
			 do {
					 /* store first result set */
													 if ($result = $dbo->Connection->store_result()) {
															 /*while ($row = $result->fetch_row()) {
																	 printf("%s\n", $row[0]);
															 }*/
															 $result->free();
													 }
													 /* print divider */
													 if ($dbo->Connection->more_results()) {
															 //printf("-----------------\n");
													 }
											 } while ($dbo->Connection->next_result());
                                             exit(json_encode(["Success"=>"TRUE","Errors"=>$errstr,"Message"=>"*Class List Saved"]));
									 }
    
}else{
    exit(json_encode(["Success"=>"FALSE","Errors"=>$errstr,"Message"=>"#No Update Found"])); 
}



?>