<?php
session_start();
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".$_POST['SubDir'];
require_once("../../../../general/config.php");
//require("../../../../general/getinfo.php");
 //exit(json_encode(["Message"=>"#gfghgh"]));
 include("genfunc.php");
 AllowUser("Updates");
 
  $errors = [];
 function FieldIn($Field = "",$Strctu = []){
if($Field == "" || count($Strctu) < 1)return FALSE;
foreach($Strctu as $fielddet){
    if(strtolower($Field) == strtolower($fielddet['Field'])){
        return $fielddet;
    }
}
return FALSE;
 }

 //get auto-increament field
 function AIField($struc){
  foreach($struc as $fieldn => $fielddet){
    //check if field exist in local table already exist
    //check auto incr field //"Extra":"auto_increment"
       if($fielddet['Extra'] == "auto_increment")return $fieldn;
  }
  return "";
 }

//sleep(4);
function AlterFieldQuery($tbname,$newstuc){
    //ALTER TABLE `adminuser_tb`
  //MODIFY `adminId` int(11) NOT NULL AUTO_INCREMENT;

/* ALTER TABLE `content_tb` CHANGE `ContentImg` `ContentImg` TEXT CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL COMMENT \'dd\' */
$cola = is_null($newstuc['Collation'])?"":"COLLATE ".$newstuc['Collation'];
if(is_null($newstuc['Default'])){
    $def = $newstuc['Null'] == "NO"?"":"DEFAULT NULL";
}else if($newstuc['Default'] == "CURRENT_TIMESTAMP"){
    $def = "DEFAULT CURRENT_TIMESTAMP";
}else{
   $def = "DEFAULT '{$newstuc['Default']}'";
}
//$def = is_null($newstuc['Default'])?"DEFAULT NULL":$newstuc['Default'] == "CURRENT_TIMESTAMP"?"DEFAULT CURRENT_TIMESTAMP":"DEFAULT '{$newstuc['Default']}'";
$null = $newstuc['Null'] == "NO"?"NOT NULL":"NULL";
$newstuc['Comment'] = str_replace("'","\'",$newstuc['Comment']);
$autoincr = strtoupper($newstuc['Extra']);
$q = "ALTER TABLE `{$tbname}` CHANGE `{$newstuc['Field']}` `{$newstuc['Field']}` {$newstuc['Type']} {$cola} $null $def $autoincr COMMENT '{$newstuc['Comment']}'";
  return $q;
}

function AddFieldQuery($tbname,$newstuc,$afterField = ""){
//ALTER TABLE `accesscode_tb` ADD `TEST` VARCHAR(200) NOT NULL DEFAULT 'ddd' COMMENT 'dddd' AFTER `RegID`;
//$cola = is_null($newstuc['Collation'])?"":"COLLATE ".$newstuc['Collation'];
$def = is_null($newstuc['Default'])?"":""."DEFAULT '{$newstuc['Default']}'";
$null = $newstuc['Null'] == "NO"?"NOT NULL":"NULL";
$newstuc['Comment'] = str_replace("'","\'",$newstuc['Comment']);
$afterField = trim($afterField) == ""?"":"AFTER `$afterField`";
$q = "ALTER TABLE `{$tbname}` ADD `{$newstuc['Field']}` {$newstuc['Type']} $null $def COMMENT '{$newstuc['Comment']}' $afterField";
  return $q;
}

//check index if exist
function IndexExist($inddet,$localindexes){
    if(count($localindexes) > 0){
      foreach($localindexes as $localind){
        if($localind['Non_unique'] == $inddet['Non_unique'] && $localind['Key_name'] == $inddet['Key_name']  && $localind['Column_name'] == $inddet['Column_name'] && $localind['Index_type'] == $inddet['Index_type']){
          return TRUE;
        }
      }
    }
    return FALSE;
}

//function to create query to set all indexes
function SetKeys($tbname,$newindex){
    global $dbo;
    $indexq = [];
  //
  foreach($newindex as $inddet){
   $exist = IndexExist($inddet,$localindexes);
if(!$exist){
  if((int)$inddet['Non_unique'] == 0){
    $indexq[] ="ALTER TABLE `$tbname` ADD UNIQUE(`{$inddet['Column_name']}`)";
  }else{
      if($inddet['Index_type'] == "FULLTEXT"){
        $indexq[] ="ALTER TABLE `$tbname` ADD FULLTEXT(`{$inddet['Column_name']}`)";
      }else{
        $indexq[] ="ALTER TABLE `$tbname` ADD INDEX(`{$inddet['Column_name']}`)";
      }
  }
}
  }
}

function KeyQuery($tbname,$field,$newindex,$localindex){
    $indexq = [];
  //get total indexes in new indexes
  $newIndexCount = [0,0,0,0];//PRIMARY, UNIQUE, INDEX, FULLTEXT
  $localIndexCount = [0,0,0,0];//PRIMARY, UNIQUE, INDEX, FULLTEXT
 foreach($newindex as $newind){
    if(strtolower($newind['Column_name']) != strtolower($field))continue;
   if($newind['Key_name'] == "PRIMARY"){$newIndexCount[0]++;continue;}
   if((int)$newind['Non_unique'] == 0){$newIndexCount[1]++;continue;}
   if((int)$newind['Non_unique'] > 0 && $newind['Index_type'] == "FULLTEXT"){$newIndexCount[3]++;continue;}
   if((int)$newind['Non_unique'] > 0){$newIndexCount[2]++;continue;}
 }

 foreach($localindex as $localind){
    if(strtolower($localind['Column_name']) != strtolower($field))continue;
    if($localind['Key_name'] == "PRIMARY"){$localIndexCount[0]++;continue;}
    if((int)$localind['Non_unique'] == 0){$localIndexCount[1]++;continue;}
    if((int)$localind['Non_unique'] > 0 && $localind['Index_type'] == "FULLTEXT"){$localIndexCount[3]++;continue;}
    if((int)$localind['Non_unique'] > 0){$localIndexCount[2]++;continue;}
  }

if($newIndexCount[0] > 0 && $localIndexCount[0] == 0){
    //add primary key
$indexq[] = "ALTER TABLE `$tbname` ADD PRIMARY KEY(`$field`);";
}

if($newIndexCount[1] > 0 && $localIndexCount[1] == 0){
    //add unique key
    $indexq[] ="ALTER TABLE `$tbname` ADD UNIQUE(`$field`)";
}

//index
if($newIndexCount[2] > $localIndexCount[2]){
  $rem = $newIndexCount[2] - $localIndexCount[2];
 while($rem > 0){
    $indexq[] ="ALTER TABLE `$tbname` ADD INDEX(`$field`)";
    $rem--;
 }
}

//fulltext
if($newIndexCount[3] > $localIndexCount[3]){
    $remf = $newIndexCount[3] - $localIndexCount[3];
   while($remf > 0){
      $indexq[] ="ALTER TABLE `$tbname` ADD FULLTEXT(`$field`)";
      $remf--;
   }
  }

return $indexq;
}

function recurse_copy($src,$dst,$overw = true) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                recurse_copy($src . '/' . $file,$dst . '/' . $file,$overw); 
            } 
            else { 
              if($overw == false){
                //check if file already exist
                if(file_exists($dst . '/' . $file))continue;
              }
                copy($src . '/' . $file,$dst . '/' . $file);
                chmod($src . '/' . $file,$dst . '/' . $file,0644);
            } 
        } 
    } 
    closedir($dir); 
}

//function update index.php
function Uninstall($setVersion=""){
    global $protocol; global $ServerRoot; global $nowdir; global $root; //global $stt;
    $vdirstr = trim($setVersion) != ""?"/".str_replace(".","_",$setVersion):"";
    foreach(["portal","cportal"] as $ddir){
        $redstr = "<?php //EP-Redirector
        header('Location: ".$protocol.$ServerRoot ."/".$nowdir."/$ddir');
       ?>";
      // $stt .= $root.$vdirstr ."/$ddir/index.php" ." ; ";
 if(file_exists($root.$vdirstr ."/$ddir/index.php")){
    //get the content
    $indcont = file_get_contents($root.$vdirstr ."/$ddir/index.php");
    
     if(substr(trim($indcont),0,21) != "<?php //EP-Redirector"){ //if not a redirector
         //rename to base index
        copy($root.$vdirstr ."/$ddir/index.php",$root.$vdirstr ."/$ddir/index_uninstall.php");
     } 
 }
 file_put_contents($root.$vdirstr ."/$ddir/index.php",$redstr);
       }
}

 //check if setup id sent
 extract($_POST);
 
 if(!isset($id) || (int)$id < 1)exit(json_encode(["Message"=>"#Invalid Setup Selected"]));
 $setup = $dbo->SelectFirstRow("setup_tb","","ID=".$id);
 if(!is_array($setup))exit(json_encode(["Message"=>"#Setup Details Not Found"]));
 $nowversion = $setup['Version'];

 //get the running version
 $inusesetup = $dbo->SelectFirstRow("setup_tb","","Inuse=1 LIMIT 1");
 $inuseversion = is_array($inusesetup)?$inusesetup['Version']:"";
 //exit(json_encode(["Message"=>$inuseversion]));
 //setup type - upgrade or update
$setuptype = "Upgrade";

 //check if they are the same
 if(strtolower($nowversion) == strtolower($inuseversion)){
    $setuptype = "Update";
 }

 $nowversionstr = str_replace(".","_",$nowversion);
 $inuseversionstr = str_replace(".","_",$inuseversion);

 //get the root directory
 $root = $_SERVER['DOCUMENT_ROOT'];

$nowdir = $nowversionstr;

 //check if directory already exist
if(is_dir($root."/".$nowversionstr) && $setuptype == "Update"){ //if the curent dir is the runing dir, dont overwrite it 
   //change the new one tempoaryly for installation
   //$nowdir .= "_install";
}
 if($group == 1){ //copying files
 //extract the the setup 
    $epsf = file_exists("../../../../setup/".$nowversionstr."/setup_$nowversionstr.epx");
if($epsf || file_exists("../../../../setup/".$nowversionstr."/setup_$nowversionstr.zip")){
    if($epsf)rename("../../../../setup/".$nowversionstr."/setup_$nowversionstr.epx","../../../../setup/".$nowversionstr."/setup_$nowversionstr.zip");
    $zip = new ZipArchive;
    if ($zip->open("../../../../setup/".$nowversionstr."/setup_$nowversionstr.zip") === TRUE)
{
    $zip->extractTo($root."/".$nowdir);
    $zip->close();

    //rename back to epx
    rename("../../../../setup/".$nowversionstr."/setup_$nowversionstr.zip","../../../../setup/".$nowversionstr."/setup_$nowversionstr.epx");
}else{
    exit(json_encode(["Message"=>"#Reading Setup File Failed"]));
}
exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group + 1,"NextOperation"=>"Setting Up Database ..."]));
 }else{
    exit(json_encode(["Message"=>"#Setup File Not Found"]));
}
}
 

//Databse Setup
if($group == 2){

 //get the database structure file
 $dbstruc = file_get_contents($root."/".$nowdir."/db.json");
 if($dbstruc === FALSE || trim($dbstruc) == "")exit(json_encode(["Message"=>"#Reading Database Structure Failed"]));

 $dataobj = [];
  //get the database structure file
  $ddata = file_get_contents($root."/".$nowdir."/data.json");
  if($ddata !== FALSE && trim($ddata) != ""){
      $dataobj = json_decode($ddata,true);
      //foreach
  }

  

 $dbstrcarr = json_decode($dbstruc,true);

 //get all tables names
 $tbnames = array_keys($dbstrcarr);

 
 if(!file_exists($root."/".$nowdir."/rundb.json")){
  $lasttbInd = 0;
 }else{
  $lasttbInd = file_get_contents($root."/".$nowdir."/rundb.json");
  if($lasttbInd === FALSE){
    //terminate database operation/ installation
    exit(json_encode(["Message"=>"#Reading Database Setup Working File Failed"]));
  }
  $lasttbInd = (int)$lasttbInd;
  if($lasttbInd < 1){
    exit(json_encode(["Message"=>"#Installation Aborted: Infinite Database Setup Logic"]));
  }

 }


 if($lasttbInd >= count($tbnames)){ //if table not exist
  //switch to next installation module
  unlink($root."/".$nowdir."/rundb.json");
  exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group + 1,"NextOperation"=>"Copying User Files ..."]));
 }


 $tbname = $tbnames[$lasttbInd];

  //process Database
  $databQuery = ["SET SESSION sql_mode = ''"];
  $totalf = 16;
$cnt = 1;
$tt = [];

  //foreach (["classofpass_tb"=>$dbstrcarr['classofpass_tb']] as $tbname => $struc) {
   //foreach ($dbstrcarr as $tbname => $struc) {
    $struc = $dbstrcarr[$tbname];
$AIF = AIField($struc);
      /* if($cnt > $totalf)break;
      $cnt++; */
    $tbindexex = $struc['__INDEX__'];
    unset($struc['__INDEX__']);
    $createtbq = $struc['__CREATE__'];
    unset($struc['__CREATE__']);
      //check if table exist
      $localtbstrucs = $dbo->RunQuery("SHOW FULL FIELDS FROM ".$tbname);
      $localstruc = [];
      if(is_array($localtbstrucs)){ //if table exist
          if($localtbstrucs[1]>0){ //if fields found
          $localstruc = $dbo->FetchAll($localtbstrucs[0],MYSQLI_ASSOC);
         
          }

          //get the local table indexs
$localindex = $dbo->RunQuery("SHOW INDEX FROM $tbname");
$localindexes = [];
if(is_array($localindex) && $localindex[1] > 0)$localindexes = $dbo->FetchAll($localindex[0],MYSQLI_ASSOC);

//Move trough all new structure and update as required
$lstField = "";
//$txt = [];
if(count($struc) > 0){
  foreach($struc as $fieldn => $fielddet){
     //check if field exist in local table already exist
     //check auto incr field //"Extra":"auto_increment"
//if($fielddet['Extra'] == "auto_increment")$AIF=$fieldn;
//$databQuery[] = $AIF." <br/>";
     $exist = FieldIn($fieldn,$localstruc);
     //$txt[$fieldn] = FieldIn($fieldn,$localstruc);
      //if(){ //if exist, Alter Query
          if($exist !== FALSE){
              //check if the same
              if(json_encode($exist) != json_encode($fielddet)){
                  $databQuery[] = AlterFieldQuery($tbname,$fielddet);
              }
          }else{
              $databQuery[] = AddFieldQuery($tbname,$fielddet,$lstField);
          }
          //$databQuery[] = $exist !== FALSE?AlterFieldQuery($tbname,$fielddet):AddFieldQuery($tbname,$fielddet,$lstField);
          $lstField = $fieldn;
          $keyquery = KeyQuery($tbname,$fieldn,$tbindexex,$localindexes);
         // $tt[$fieldn] = $keyquery;
         if(count($keyquery) > 0)$databQuery = array_merge($databQuery,$keyquery);
  }
}
      }else{
//table not exist
//create it
$databQuery[] = $createtbq;

      }
      $databQuery[] = "ALTER TABLE $tbname AUTO_INCREMENT=1";
      //set default
if(isset($dataobj[$tbname]) && count($dataobj[$tbname]) > 0){
  $datadet = $dataobj[$tbname];
   $dataquery = [];
   $collist = [];
   if($tbname == "menu_tb"){ //always update menu_tb
      $databQuery[] = "TRUNCATE TABLE $tbname";
   }
  //form field datas
  foreach($datadet as $realdata){
$datastring = "(SELECT ";
    foreach($realdata as $dfield=>$dval){

      $dval = is_numeric($dval)?$dval:"'".$dbo->SqlSafe($dval)."'";
if($dfield == $AIF)$dval = 0;
      $datastring .= $dval." AS `".$dfield."`, ";
      if(count($collist) ==0)$collist = array_keys($realdata);
    }
    $datastring = rtrim($datastring,", ").")";
    $dataquery[] = $datastring;
  }

  $collist = (count($collist)  > 0)?"(`".implode("`,`",$collist)."`)":"";

  $databQuery[] = "INSERT INTO $tbname $collist SELECT t.* FROM (".implode("UNION",$dataquery).") t WHERE NOT EXISTS (SELECT * FROM $tbname)";
  
  /* (SELECT 1 as col1, 'kingston' as col2, 'test' as col3, true as col4) */
}
       

      
  //}
  
  $query = implode(";",$databQuery).";";
  //exit(json_encode(["Message"=>"*DBFiles - ".count($dbstrcarr),"Query"=>$query]));
  $dump = $dbo->Connection->multi_query($query);
  if(!$dump){
      exit(json_encode(["Message"=>"#Server Error: ".$dbo->Connection->error]));
  }else{
      while ($dbo->Connection->more_results()){
          $dbo->Connection->next_result();
          if(trim($dbo->Connection->error) != ""){
              exit(json_encode(["Message"=>$dbo->Connection->error]));
          }
         // echo $dbo->Connection->error;
         if ($result = $dbo->Connection->store_result()) {
                             
                              
          $result->free();
      }
     }
  }
  $lasttbInd = $lasttbInd + 1;
  //exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group + 1,"NextOperation"=>"Copying User Files ..."]));
  file_put_contents($root."/".$nowdir."/rundb.json",$lasttbInd);
  exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group,"NextOperation"=>"Setting Up Database (".$lasttbInd."/".count($dbstrcarr).")...","Rerun"=>1])); //Rerun is use in setup installer
}

//Dependables and Userfiles
if($group == 3){
//Copy Ignore Files
       //check if current version exist
       $rundir = is_dir($root."/".$inuseversionstr)?$root."/".$inuseversionstr."/":$root."/";
       //get all ignors
       //$stt = "";
       $ign = file_get_contents($root."/".$nowdir."/ignores.json");
       //$ign = FALSE;
       if($ign !== FALSE && trim($ign) != ""){
           $ignobj = json_decode($ign,true);
           $ignobj["schoool"] = "root://epconfig/UserImages/School"; //include school
           $ignobj["wallpapers"] = "root://epconfig/UserImages/wallpapers"; //include school
           if(count($ignobj) > 0){
               foreach($ignobj as $key => $ignordir){
                 if(substr(trim($ignordir),0,1) != "*"){ //if to be included
             $sr = str_replace("root://",$rundir,$ignordir);
             $dest = str_replace("root://",$root."/".$nowdir."/",$ignordir);
             if(trim($sr) == trim($dest))continue;
              if(is_dir($sr)){
                if($key == "schoool" || $key == "wallpapers"){
                  recurse_copy($sr,$dest,false); //dont overwrite
                }else{
                  recurse_copy($sr,$dest);
                }
                
              }else{
                 //looking for conf.txt file
                 $srdet = pathinfo($sr,PATHINFO_BASENAME);
        if($srdet != "conf.txt" || !isset($newconf)){
        copy($sr,$dest);
        }
                
              }
                    
                 }
               }
           }
           //foreach
       }
       exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group + 1,"NextOperation"=>"Installing Dependables ..."]));
}

//Dependables
if($group == 4){
  //Copy Dependables Files
         //check if current version exist
         $rundir = is_dir($root."/".$inuseversionstr)?$root."/".$inuseversionstr."/":$root."/";
         //get all ignors
         //$stt = "";
         //copy depend variable
         $cdp = 0; //dependables not part of the setup
         $meta = file_get_contents($root."/".$nowdir."/meta.json");
         if($meta !== FALSE && trim($meta) != ""){
          $meta = json_decode($meta,true);
          $cdp = (int)$meta['Dependables'];
         }

         //copy required
         if($cdp == 0){
          $ign = file_get_contents($root."/".$nowdir."/dp.json");
         
          //$ign = FALSE;
          if($ign !== FALSE && trim($ign) != ""){
              $ignobj = json_decode($ign,true);
              if(count($ignobj) > 0){
                  foreach($ignobj as $ignordir){
                    if(substr(trim($ignordir),0,1) != "*"){ //if to be included
                $sr = str_replace("root://",$rundir,$ignordir);
                $dest = str_replace("root://",$root."/".$nowdir."/",$ignordir);
                if(trim($sr) == trim($dest))continue;
                 if(is_dir($sr)){
                   recurse_copy($sr,$dest);
                 }else{
                    //looking for conf.txt file
                   // $srdet = pathinfo($sr,PATHINFO_BASENAME);
          // if($srdet != "conf.txt" || !isset($newconf)){
           copy($sr,$dest);
           //}
                   
                 }
                       
                    }
                  }
              }
              //foreach
          }
         }
        
         exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group + 1,"NextOperation"=>"Executing Patches ..."]));
  }

$ServerRoot = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
//$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$protocol = !empty($_SERVER['HTTPS'])?'https://' : 'http://';

//Executing Patches
if($group == 5){
  $patchfiledir = $nowdir."/patch";
  $patchdir = $root."/".$patchfiledir;
  //check temp patch file
  if(isset($Patch)){ //if individual patch execution
    if(trim($Patch) == "")exit(json_encode(["Message"=>"Invalid Patch Script"]));
    $patchfiledir = $nowdir."/patch/temp";
    $patchdir = $root."/".$patchfiledir;
    if(!file_exists($root."/".$patchfiledir."/".$Patch.".php"))exit(json_encode(["Message"=>"Patch Script Not Found"]));
  }
  //Help to hold completed and current runing patch, will be usefull when a break is done in patch script for heavy patch operation
  //check if patch working directory exist
  $runpatch = [];
  if(file_exists($root."/".$nowdir."/runpatch.json")){
    $runpatchstr = file_get_contents($root."/".$nowdir."/runpatch.json");
    if($runpatchstr && trim($runpatchstr) != ""){
      $runpatch = json_decode($runpatchstr,true);
    }
  }
 //Run Patch Scripts
 
       
      
       if(is_dir($patchdir)){
        $pdir = opendir($patchdir); 
        //@mkdir($dst); 
        while(false !== ( $pfile = readdir($pdir)) ) { 
            if (( $pfile != '.' ) && ( $pfile != '..' )) { 
                if (!is_dir($patchdir . '/' . $pfile) ) {
                  $patchpinfo = pathinfo($patchdir . '/' . $pfile);
                  //check if individual/single patch execution
                  if(isset($Patch) && $patchdir . '/' . $pfile != $patchdir . '/' . $Patch.".php")continue;
                  
                    if($patchpinfo['extension'] == "php"){
                      $patchfname = $patchpinfo['filename'];
                      if(isset($runpatch[$patchfname]) && is_null($runpatch[$patchfname]))continue;
                      $param = ["Type"=>"EP_Patcher"];
                      if(isset($PatchParam)){
                        $PatchParam = json_decode($PatchParam,true);
                        $param = array_merge($param,$PatchParam);
                        //exit(json_encode(["Message"=>json_encode($param)]));
                      }
                      if(isset($runpatch[$patchfname]) && !is_null($runpatch[$patchfname])){
                       $param['Break'] = $runpatch[$patchfname];
                      }
                      
                       $rtnval = CallScript($protocol.$ServerRoot ."/".$patchfiledir ."/". $pfile,$param);
                       $errors[] = $rtnval;
                       if(trim($rtnval) != ""){
                        //exit(json_encode(["Message"=>$rtnval]));
                        $rtnvalobj = json_decode($rtnval,true);
                        if(isset($rtnvalobj['Error'])){
                           if(isset($Patch)){unlink($root."/".$patchfiledir."/".$Patch.".php");
                            exit(json_encode(["Message"=>$rtnvalobj['Error']]));}
                          $errors[] = $rtnvalobj['Error'];
                        }
                        if(isset($rtnvalobj['Break'])){
                          $runpatch[$patchfname] = $rtnvalobj['Break'];
                          //store the run details
                          $rundet = file_put_contents($root."/".$nowdir."/runpatch.json",json_encode($runpatch));
if($rundet){
$title = isset($rtnvalobj['Info'])?$rtnvalobj['Info']:"Still Executing Patches ...";
  exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1, "NextSetup"=>(int)$group,"NextOperation"=>$title]));
}else{
  $errors[] = "Patch Scritp Break Failed: ".$patchdir . '/' . $pfile;
}

                        }
                       }else{
                        $errors[] = "Empty Responce from patch script: ".$patchdir . '/' . $pfile;
                       }  
                       $runpatch[$patchfname] = NULL;
                      
                    }else{
                        $errors[] = "Invalid Patch File: ".$patchdir . '/' . $pfile;
                    }
                    
                } 
            } 
        } 
        closedir($pdir);
       }else{
        $errors[] = "No Patch Found";
       }
       if(file_exists($root."/".$nowdir."/runpatch.json")){
        unlink($root."/".$nowdir."/runpatch.json");
       }
       if(!isset($Patch)){ //if not single file patching, meaning not from setup
//delete instalation files
unlink($root."/".$nowdir."/data.json");
unlink($root."/".$nowdir."/db.json");//ignores.json
unlink($root."/".$nowdir."/ignores.json");
unlink($root."/".$nowdir."/dp.json");
unlink($root."/".$nowdir."/meta.json");
       }else{
        unlink($root."/".$patchfiledir."/".$Patch.".php");
       }
       exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1]));
}
       

//Uninstalling and Finishing     
if($group == 6){
 //$stt = "";
       //Uninstall index pages
       //get all setups and update the index where neccessary
       $setups = $dbo->Select("setup_tb","","Version != '$nowversion'");
       if(is_array($setups) && $setups[1] > 0){
           while($indsetup = $setups[0]->fetch_assoc()){
               $setVersion = $indsetup['Version'];
               //check if index.php exist
               
               Uninstall($setVersion);
           }
       }

       //Uninstall in root
       Uninstall();

       

       //update the current running
      $updrun = $dbo->RunQuery("UPDATE setup_tb SET Inuse = IF(Version='$nowversion',1,0), InstallDate = IF(Version='$nowversion','".date('Y-m-d H:i:s')."',InstallDate) ");
      exit(json_encode(["Message"=>"*Insatllation Complete","Done"=>1,"Finish"=>1]));
}
      


        


       //$root."/".$inuseversionstr
       
       
    
    //run the query
    
    //look for the inuse install directory
    



 




?>