<?php
//This script setup db and also test db con
require_once("../../../epconfig/TaquaLB/Ajax/CGI/PHP/phplb.php");
//sleep(5);
function FormConfig($constr){
    global $phpf;
    $encr = $phpf -> __($constr);
          //$decr = $phpf -> _($encr);
                    $myfile = fopen("../../../epconfig/conf.txt", "w") or die("#Setup Failed: Unable to Open file!");
                    fwrite($myfile, $encr);
                    fclose($myfile);
                     echo "*"; //database configured sussessfully
}
if(isset($_POST['tid']) && trim($_POST['tid']) != ""){
   //$tid = $dbo->SqlSafe($_POST['tid']);
    $phpf = new RphpFunctions;
  // if(!isset($_POST['txt'])){ //setup
     
   //echo $_POST['tid'];
   
   $datastrconfig = str_replace(";","&",$_POST['tid']);
   $newdb = trim(@$_POST['newdb']) == "true"?true:false ;
     // echo $datastrconfig;
        $datasrr = $phpf->DataArray($datastrconfig);
       
        //$dbo = new DbFunctions($datasrr["server"],$datasrr["user"],$datasrr["pw"],$datasrr["db"]);
       // print_r($datastrconfig);exit;
       
       // $con = DbFunctions::$con; //get the connection opbject created
       //$convar = mysql_connect($datasrr["server"],$datasrr["user"],$datasrr["pw"]);
       $convar = new mysqli($datasrr["server"], $datasrr["user"], $datasrr["pw"]);
		if ($convar ->connect_errno > 0) {
            echo "#";
            //cannot connect to Server 
        //if($dbo->ConnectStatus != ""){


            /*if($dbo->ConnectStatusID == 1){ //if database not exist
               //echo "#Database not Exist";
               //create the Database

               echo "#".$dbo->ConnectStatus;
               exit;
            }else{
                echo "#Connection Failed";
                exit;
            }*/
            
       
       
        }else{
            
            $dbsel = $convar->select_db($datasrr["db"]);
            if(!$dbsel){
                if($newdb){
                   //create the database
                 $q1 = $convar->query("CREATE DATABASE IF NOT EXISTS `".$datasrr["db"]."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci");
                 $q2 = $convar->query("USE `".$datasrr["db"]."`");
                 if(!$q1){echo "#Internal Error: Cannot Create Database";exit;}
                 if(!$q2){echo "#Internal Error: Cannot Select Database";exit;}
                }else{
                 echo "##";
                 exit;
                }
                
               
            }//else{
             
            $usertb = $convar->query("show tables");
            if(!$usertb){
              echo "**";
              //exit;
            }else{
                //test tables
               // echo $usertb->num_rows; exit;
                $testTb = array("accesscode_tb","coursecontrol_tb","thirdparty_tb","wallpapers_tb");
              if($usertb->num_rows < 1){
                  //import database 
                  $databaseTbs = file_get_contents("../../../epconfig/Database/db.sql");
                  if(!$databaseTbs){ //if cannot read db file
                     echo "#Internal Error: Cannot open Database dump File";
                     $convar->close();
                     exit;
                  }
                   //load default datas
                      $defaultTbs = file_get_contents("../../../epconfig/Database/default.sql");
                      if(!$defaultTbs){
                         echo "#Internal Error: Cannot open Database default File";
                          $convar->close();
                         exit;
                      }
                      //merge query
                    $databaseTbs .= $defaultTbs;  
                  //clean db query 
                  $databaseTbs = str_replace(array("CREATE DATABASE","USE `"),array("-- CREATE DATABASE","-- USE `"),$databaseTbs);
                  $dump = $convar->multi_query($databaseTbs);
                  if(!$dump){
                    echo "#".$convar->error;
                  }else{
                     
                      //$dumpDefault = $convar->multi_query($defaultTbs);
                      //$_POST['tid']
                   // echo "*database dumped";
                   do {
        /* store first result set */
                        if ($result = $convar->store_result()) {
                            /*while ($row = $result->fetch_row()) {
                                printf("%s\n", $row[0]);
                            }*/
                            $result->free();
                        }
                        /* print divider */
                        if ($convar->more_results()) {
                            //printf("-----------------\n");
                        }
                    } while ($convar->next_result());
                   //write config details in file
                      FormConfig($_POST['tid']);
                  }
                   $convar->close();
                  exit;
              }else{
                  $seen = 0;
                  while($rst = $usertb->fetch_array()){ //move trough all rows (table names) to confirm if test tables are found
                      $tb = $rst[0];
                      if(in_array($tb,$testTb)){
                       $seen++;
                      }
                      if($seen == 4)break; //if all test table found (ie valid eduporta database)
                  }
                  if($seen == 4){ //if valid eduporta database
                       //write config details in file
                      FormConfig($_POST['tid']);
                  }else{
                     echo "**"; //invalid eduporta database
                  }
              }
               $convar->close();
               
             
            }
            
            //}
        }
    
   
  
}


?>