<?php
//get all application R004
function GetApplications($Param)
{
    global $dbo;
    $cnd = "";
   
    //check ApplyGID is sent
    if (isset($Param['ApplyGID']) && trim($Param['ApplyGID']) != "") {
        $appgidarr = explode("_", $Param['ApplyGID']);
        if (count($appgidarr) > 0) {
            $cnd = " AND (ID=" . implode(" OR ID=", $appgidarr) . ") AND Enable=1";
        }
        //$cnd = (int)$Param['ApplyGID'] > 0?" AND ID=".$Param['ApplyGID']:"";
    }
    //Error(4," - ".$Param['ApplyGID']);
    //check Scope is sent
    if (isset($Param['Scope']) && trim($Param['Scope']) != "") {
        $cnd .= " AND (Scope = '{$Param['Scope']}' OR Scope = 'ALL')";
    }

    $studenable = true;
    if(isset($Param['LoginName'])){
        //get the student status
        $studEnableDb = $dbo->SelectFirstRow("studentinfo_tb", "Enable", "RegNo='{$dbo->SqlSafe($Param['LoginName'])}' OR JambNo='{$dbo->SqlSafe($Param['LoginName'])}'");
        if(is_array($studEnableDb) && (int)$studEnableDb['Enable'] != 1)$studenable = false;
    }

    //get all the group
    $appGroup = $dbo->Select("new_apply_group_tb", "*, IF(Enable=1,'Enabled','Disabled') as Status", "ID >= 1" . $cnd . " ORDER BY MenuOrder");
    if (!is_array($appGroup)) Error(4, ": Reading Application Failed.");
    if ($appGroup[1] < 1) Error(9, " : Application Not Available or Disabled");
    $applygrparr = [];
    $JointID = "";
    $firstLogo = "";
    while ($ind = $appGroup[0]->fetch_assoc()) {
        $applygrpid = $ind["ID"];
        if(!$studenable)$ind["ID"]=0;
        $JointID .= "_" . $applygrpid;
        if ($firstLogo == "") $firstLogo = trim($ind["Logo"]);
        //get the apply sub group
        $appSub = $dbo->Select("new_apply_group_sub_tb", "ID as AID, Name as AppName, Descr as AppDescr, Logo as AppLogo, Color as AppColor,  Placeholder", "Enable=1 AND GroupID=" . $applygrpid . " ORDER BY MenuOrder");
        $ind["Applications"] = [];
        if (is_array($appSub)) {
            if ($appSub[1] > 0) {
                while ($appSubInd = $appSub[0]->fetch_assoc()) {
                    $GSubID = $appSubInd['AID'];


                    //get all apply details
                    $app = $dbo->Select("new_apply_tb", "ID as ARID, Name as AppRName, Descr as AppRDescr, Logo as AppRLogo, Color as AppRColor,  Placeholder", "Enable=1 AND GroupSubID=" . $GSubID . " ORDER BY MenuOrder");
                    if (!is_array($app)) {
                        $ind["Applications"][] = InternalError(4);
                        //$ind["Applications"] = InternalError(4);
                    } else {

                        if ($app[1] > 0) {
                            $appSubInd["Menus"] =  $dbo->FetchAll($app[0], MYSQLI_ASSOC);
                            $appSubInd['SubMenuJson'] = json_encode($appSubInd["Menus"]);
                        }
                        $ind["Applications"][] = $appSubInd;
                        //$ind["Applications"] = $dbo->FetchAll($app[0],MYSQLI_ASSOC);

                    }
                }
            }
        }

        $applygrparr[] = $ind;

        // $schooldet["Wallpapers"] = $dbo->FetchAll($schwp[0],MYSQLI_ASSOC);

    }
    return ["AppGroup" => $applygrparr, "PAGEID" => ltrim($JointID, "_"), "Logo" => $firstLogo];
}

//function to get all Page element by Application ID and The Page Number - R005
function GetPageElements($Param)
{
    session_start();

    //return $Param;
    global $dbo;
    global $Request;
    global $Scripts;
    if (!isset($Param['ApplyID']) || (int)$Param['ApplyID'] == 0) Error(10);
    //get application details
    $ApplyDet = $dbo->SelectFirstRow("new_apply_tb", '', "ID=" . $dbo->SqlSafe($Param['ApplyID']), MYSQLI_ASSOC);
    if (!is_array($ApplyDet)) Error(10);
    if ($ApplyDet['Status'] == "CLOSED") Error(22, " for " . $ApplyDet['Name']);
    //Check if payment must be made
    $PayID = (int)$ApplyDet['PayID'];
    if ($PayID > 0) { //if payment must be made befor access is given
        //get the payment details

        if (!isset($Param['LoginName'])) Error(8, " : This Features requires payment, kindly login and try again");
        $paydet = $dbo->SelectFirstRow("item_tb", "ItemName", "ID=$PayID");
        if (!is_array($paydet)) Error(14, ": Report this Error to the Tech Unit");
        $bases = (int)$ApplyDet['PayBases'];
        $stdlvlsemdet = GetStudentCurrentLevelSemester($Param);
        $studlvl = $stdlvlsemdet['LevelID'];
        $studsem = $stdlvlsemdet['SemID'];
        //get the student programme id
        $studProg = $dbo->SelectFirstRow("studentinfo_tb", "ProgID", "RegNo='" . $dbo->SqlSafe($Param['LoginName']) . "' OR JambNo='" . $dbo->SqlSafe($Param['LoginName']) . "'");
        if (!is_array($studProg)) Error(8, " : This Features requires payment, kindly login and try again");
        $StudProgID = $studProg['ProgID'];
        $basescond = "AND Lvl=$studlvl AND Sem=$studsem";
        if ($bases == 2) { //level bases
            $basescond = "AND Lvl=$studlvl";
        } else if ($bases > 2) { //entire academic programme bases
            $basescond = "";
        }
        //confirm if payment made
        $paymaderst = $dbo->SelectFirstRow("payhistory_tb", "ProgID", "RegNo='" . $dbo->SqlSafe($Param['LoginName']) . "' $basescond AND ProgID=$StudProgID ORDER BY SemPart DESC LIMIT 1");
        if (!is_array($paymaderst)) Error(13, " (" . $paydet['ItemName'] . ")");
    }
    $Pages =  (!is_null($ApplyDet['Pages']) && trim($ApplyDet['Pages']) != "") ? json_decode($ApplyDet['Pages'], true) : [];
    $isext = "";
    if (is_null($Pages)) { //assuming it is a url
        //check if it is a valid url
        if (filter_var($ApplyDet['Pages'], FILTER_VALIDATE_URL)) {
            $ApplyDet['Dir'] = "General/External";
            $isext = trim($ApplyDet['Pages']);
        } else {
            $Pages = [];
            //Error(16,": Is Not Url - ".$ApplyDet['Pages']);
        }
    }
    $PageControl =  !is_null($ApplyDet['PageControl']) ? json_decode($ApplyDet['PageControl'], true) : [];

    $ApplyDetRetn = ["ApplyName" => $ApplyDet['Name'], "ApplyDescr" => $ApplyDet['Descr'], "ApplyLogo" => $ApplyDet["Logo"], "ApplyGroupID" => $ApplyDet["GroupID"], "ApplyColor" => $ApplyDet["Color"], "Dir" => $ApplyDet['Dir']];



    //get the global data set
    $GlobalData = [];
    if (!is_null($ApplyDet["GlobalData"])) $GlobalData = json_decode($ApplyDet["GlobalData"], true);
    if (is_null($GlobalData)) $GlobalData = [];
    if (trim($isext) != "") {
        $GlobalData['ExtUrl'] = $isext;
    }
    $cond = "";

    if (isset($Param['PageNum']) && (int)$Param['PageNum'] > 0) {
        $PageNumDir = (int)$Param['PageNum'];
        $NextPageNumDir = $PageNumDir + 1;
        if (count($Pages) > 0) { //if pages set
            //check if the supplied page not exist
            $pagekey = array_search($Param['PageNum'], $Pages);
            if ($pagekey === FALSE) {
                $PrePageNum = (int)$Param['PageNum'];
                do {
                    $PrePageNum = $PrePageNum - 1;
                    //if($PrePageNum > 0){
                    $prepagekey = array_search($PrePageNum, $Pages);
                    //}  
                } while ($prepagekey === FALSE && $PrePageNum > 0);
                if ($prepagekey === FALSE) {
                    $PageNumDir = $Pages[0];
                    $NextPageNumDir = $Pages[1];
                } else {
                    $PageNumDir = $Pages[$prepagekey];
                    $NextPageNumDir = isset($Pages[$prepagekey + 1]) ? $Pages[$prepagekey + 1] : $Pages[0];
                }
            } else {
                //get the next page from the pages array, if no more next use the first(return to the first)
                $NextPageNumDir = isset($Pages[$pagekey + 1]) ? $Pages[$pagekey + 1] : $Pages[0];
            }
        }
        $cond = "AND PageNumber = " . $dbo->SqlSafe($PageNumDir);
    } else if (count($Pages) > 0) {
        $PageNumDir = $Pages[0];
        $NextPageNumDir = $Pages[1];
    } else {
        $PageNumDir = 1; //default pagenum value for dir page type
        $NextPageNumDir = 2;
    }

    $Param['PageNum'] = $PageNumDir;
    //Error(0," - ".$PageNumDir);

    //process page control settings
    if (isset($PageControl[$PageNumDir])) {
        foreach ($PageControl[$PageNumDir] as $PCID => $status) {
            $PageControl[$PageNumDir][$PCID] = $status ? [1] : [];
        }
    }

    $pageDet = ["ApplyID" => $Param['ApplyID'], "ApplyGroupID" => $ApplyDet["GroupID"]];
    //check if file type
    if (!is_null($ApplyDet['Dir']) && trim($ApplyDet['Dir']) != "") {
        //
        //get the PageDetails
        //check if file exixt
        //first check in school directory incase general page is overwritten
        $lookup = __DIR__."/../../Pages/";
        if (file_exists(__DIR__."/../../../../" . $dbo->Config["SubDir"] . "Pages/" . $ApplyDet['Dir'] . "/" . $PageNumDir . ".json")) {

            $lookup = __DIR__."/../../../../" . $dbo->Config["SubDir"] . "Pages/";
        }

       


        if (file_exists($lookup . $ApplyDet['Dir'] . "/" . $PageNumDir . ".json")) {
           
    
            $locate = $lookup . $ApplyDet['Dir'] . "/" . $PageNumDir . ".json";
            $locatekey = str_replace(array("/", ".",'\\',':'), "_", $locate);
           
            //check if cached
            if (isset($_SESSION[$locatekey]) && trim($_SESSION[$locatekey]) != "") {
                
                $pagejsondet = $_SESSION[$locatekey];
            } else {
                $pagejsondet = file_get_contents($locate);
               
            }

            // Error(0,": ".$pagejsondet);
            if ($pagejsondet !== FALSE && trim($pagejsondet) != "") {
                $jsonobj = json_decode($pagejsondet, true);
                
                if (!is_null($jsonobj)) { //if valid
                    $page = $jsonobj[0];
                    //form page det
                    $pageDet['Name'] = isset($page['name']) ? $page['name'] : "";
                    $pageDet['Logo'] = isset($page['logo']) ? $page['logo'] : "";
                    $pageDet['Descr'] = isset($page['data']) ? $page['data'] : "";
                    $pageDet['PageMarkup'] = $pagejsondet;
                    $pageDet['PreRID'] = isset($page['request']) && isset($page['request']['pre']) ? $page['request']['pre'] : "";
                    $pageDet['SubmitRID'] = isset($page['request']) && isset($page['request']['post']) ? $page['request']['post'] : "";
                    $pageDet['PreRequestData'] = isset($page['request']) && isset($page['request']['data']) ? json_encode($page['request']['data']) : "";
                    
                }
            }
        }
    } else {
        Error(16, "<br />Directory not Setup</br/>Report this error to the technical team");
    }

    // if(count($pageDet) < 1){
    if (!isset($pageDet['PageMarkup'])) {
       
        $pageDet = $dbo->SelectFirstRow("new_apply_page_tb", '', "ApplyID=" . $dbo->SqlSafe($Param['ApplyID']) . " " . $cond, MYSQLI_ASSOC);
        if (!is_array($pageDet)) Error(16);
    }



    // $AllRst['R005'] = $pageDet;
    //get the pre request ID
    $preRID = $pageDet['PreRID'];
    $preRdata = $pageDet['PreRequestData'];
    //$preRdata['NextPageNum'] = $NextPageNumDir;
    $pageDet['NextPageNum'] = $NextPageNumDir;
    $pageDet['NowPageNum'] = $PageNumDir;
  
    if (trim($preRID) != "") {

        $preRdata = trim($preRdata) != "" ? json_decode($preRdata, true) : [];
        if (isset($PageControl[$PageNumDir])) $preRdata = array_merge($preRdata, $PageControl[$PageNumDir]);
        $preRdata['NextPageNum'] = $NextPageNumDir;
        $preRdata['NowPageNum'] = $PageNumDir;
        $preRdata = array_merge($preRdata, $Param, $GlobalData);
        $RIds = explode(",", $preRID);
        //$preRdata = array_merge($preRdata,$Param);
        /* $RIds = explode(",",$preRID);
         $preRdata = array_merge($preRdata,$Param,$RIds,$GlobalData); */
        /* $RIds = explode(",",$preRID);
         $preRdata = array_merge($preRdata,$Param); */

        foreach ($RIds as $IndRid) {
          
            //check if function exist
            if (!function_exists($Request[$IndRid][0])) {
                
                //include all the required 
                /*    try{
                   require_once "script"
                 }catch (Exception $e) {
     //exit('Require failed! Error: '.$e);
     // Or handle $e some other way instead of `exit`-ing, if you wish.
 } */
                if (!in_array($Request[$IndRid][1], $Scripts)) {
                    require_once $Request[$IndRid][1] . ".php";
                } else {
                    Error(3, " : -" . $Request[$IndRid][0]);
                }
            }
            
            //call the script
            $rst = call_user_func($Request[$IndRid][0], $preRdata);
            //var_dump($rst);
            //exit;
            //check if PagNum is changed from pre script
            if (isset($rst['PageNum']) && (int)$rst['PageNum'] != (int)$PageNumDir) {

                return GetPageElements(array_merge($Param, $rst));
            }

            $preRdata = array_merge($preRdata, $rst);
            //Error(10,': '.$rst);
            //get notification out to main array root
            if (isset($rst['__Notify__'])) $pageDet['__Notify__'] = $rst['__Notify__'];
            $pageDet = array_merge($pageDet, [$IndRid => $rst]);
        }

        //check if current PageNum has changed

    }

    $pageDet = array_merge($pageDet, $_SESSION);
    //Error(10,': '.json_encode($PageControl[$PageNumDir]));
    if (isset($PageControl[$PageNumDir])) $pageDet = array_merge($pageDet, $PageControl[$PageNumDir]);
    //
    //Error(16,json_encode($GlobalData)); 
    return array_merge($pageDet, $Param, $ApplyDetRetn, $GlobalData);
}

//R024
function GetAllApplications($Param)
{
    global $dbo;
    $cnd = "";
    //get all the group
    $appGroup = $dbo->Select("new_apply_group_tb", "", "Enable=1" . $cnd);
    if (!is_array($appGroup)) Error(4, ": Reading Application Failed.");
    if ($appGroup[1] < 1) Error(9, " : Application Not Exist or Disabled");
    $applygrparr = [];
    $JointID = "";
    while ($ind = $appGroup[0]->fetch_assoc()) {
        $applygrpid = $ind["ID"];
        $JointID .= "_" . $applygrpid;
        //get all apply details
        $app = $dbo->Select("new_apply_tb", "ID as AID, Name as AppName, Descr as AppDescr, Logo as AppLogo", "Enable=1 AND GroupID=" . $applygrpid . " ORDER BY MenuOrder");
        if (!is_array($app)) {
            $ind["Applications"] = InternalError(4);
        } else {
            $ind["Applications"] = $dbo->FetchAll($app[0], MYSQLI_ASSOC);
        }
        $applygrparr[] = $ind;
        // $schooldet["Wallpapers"] = $dbo->FetchAll($schwp[0],MYSQLI_ASSOC);

    }
    return ["AppGroup" => $applygrparr, "PAGEID" => ltrim($JointID, "_")];
}

//Get Application Links
function MenuLinkDetails($Param = [])
{
    global $dbo;
    $portaldet = $dbo->SelectFirstRow("portal_tb");
    $setmlinks = [];
    if (is_array($portaldet) && isset($portaldet['MenuLink']) && !is_null($portaldet['MenuLink'])) {
        $setmlinks = json_decode($portaldet['MenuLink'], true);
    }
    $q = [];
    if (count($setmlinks) > 0) {
        foreach ($setmlinks as $mid => $det) {
            $q[] = "SELECT a.ID,a.Name,a.Descr,a.GroupID,a.Logo,a.Color,a.Placeholder,ag.Logo as GroupLogo,'$mid' as MID FROM new_apply_tb a, new_apply_group_tb ag WHERE ag.ID= {$det[1]} AND a.ID={$det[2]} AND a.GroupID=ag.ID LIMIT 1";
        }
    }
    $query = "(" . implode(") UNION (", $q) . ")";
    $menus = $dbo->RunQuery($query);
    $rtnarr = [];
    if (is_array($menus) && $menus[1] > 0) {
        while ($indmen = $menus[0]->fetch_assoc()) {
            $rtnarr[$indmen['MID']] = $indmen;
        }
    }
    $dump = [
        "enrol" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "pay" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "wallet" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "course" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "restult" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "assignmet" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "elearn" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""],
        "notify" => ["ID" => 0, "Name" => "", "Descr" => "", "GroupID" => 0, "Logo" => "", "Color" => "", "Placeholder" => "textbox", "GroupLogo" => ""]
    ];
    if (!is_array($rtnarr)) $rtnarr = $dump;
    return $rtnarr;
}
