<?php

//header('Location: /newstorex/controllers/generalSearch.php?do=all');
//header('Location: '.$newURL);
//the global file operation
include("../public/impOpreation.php");
// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");

include_once("dailyentryfun.php");

//Newdbname
require_once('../models/dao/NewdbnameDAO.class.php');
require_once('../models/dto/Newdbname.class.php');
require_once('../models/mysql/NewdbnameMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbnameMySqlExtDAO.class.php');
//User
require_once('../models/dao/UserDAO.class.php');
require_once('../models/dto/User.class.php');
require_once('../models/mysql/UserMySqlDAO.class.php');
require_once('../models/mysql/ext/UserMySqlExtDAO.class.php');
//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');

require_once('../models/dao/NewdbbackupDAO.class.php');
require_once('../models/dto/Newdbbackup.class.php');
require_once('../models/mysql/NewdbbackupMySqlDAO.class.php');
require_once('../models/mysql/ext/NewdbbackupMySqlExtDAO.class.php');

//Usergroup
require_once('../models/dao/UsergroupDAO.class.php');
require_once('../models/dto/Usergroup.class.php');
require_once('../models/mysql/UsergroupMySqlDAO.class.php');
require_once('../models/mysql/ext/UsergroupMySqlExtDAO.class.php');

//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

/* ======================

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */

//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
//Newdbname
$newDbName = new Newdbname();
$newDbNameDAO = new NewdbnameMySqlDAO();
$newDbNameExt = new NewdbnameMySqlExtDAO();
//Usergroup
$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$userGroupExt = new UsergroupMySqlExtDAO();
//User
$user = new User();
$userDAO = new UserMySqlDAO();
$userExt = new UserMySqlExtDAO();
//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();
//
$myUserGroupRecord = new UsergroupMySqlDAO();

$dbhostc = ConnectionProperty::getHost();
$dbuserc = ConnectionProperty::getUser();
$dbpasswordc = ConnectionProperty::getPassword();
$dbnamec = ConnectionProperty::getDatabase();

#######  prepare sql file to send it to offline programs
$pSetting = $ProgramsettingDAO->load(1);
if ($pSetting->updatefiledate != date('Y-m-d')) {
    prepareSqlFile($dbhostc, $dbuserc, $dbpasswordc, $dbnamec);
    $pSetting->updatefiledate = date('Y-m-d');
    $ProgramsettingDAO->update($pSetting);
}








//Newdbbackup
$myNewdbbackup = new Newdbbackup();
$myNewdbbackupRecord = new NewdbbackupMySqlDAO();
$file = "../public/libs/plugins/fileget.nrd";
$alreadynumber = file($file);
$alreadynumber = explode("-", $alreadynumber[0]);
$alreadynumber1 = $alreadynumber[0];
$alreadynumber = $alreadynumber[1];

if (base64_decode($alreadynumber) > 0) {
    $newnumber = base64_decode($alreadynumber) - 1;
    $newnumber = base64_encode($newnumber);
    $filenew = fopen($file, "w+");
    fwrite($filenew, $alreadynumber1 . "-" . $newnumber);
    fclose($filenew);
    // echo base64_decode($alreadynumber);
} elseif (base64_decode($alreadynumber) == "-1") {

} else {
    header("location:../exper.html");
}
//check and use the condetion that suite this action
if (empty($do)) {
    //check if showPreviousPrice column exists in programsettings tbl
    $generalSettings = $ProgramsettingDAO->load(1);
    try {
        $programData = $ProgramsettingEX->getPreviousPriceStatus();
    } catch (Exception $e) {
        if (count($programData) == 0) {
            //truncate table
            $ProgramsettingEX->truncateTable();

            //add column
            $ProgramsettingEX->alterTable();

            //insert old data
            $Programsetting->address = $generalSettings->address;
            $Programsetting->companyname = $generalSettings->companyname;
            $Programsetting->deptprinting = $generalSettings->deptprinting;
            $Programsetting->email = $generalSettings->email;
            $Programsetting->faxnumber = $generalSettings->faxnumber;
            $Programsetting->logo = $generalSettings->image;
            $Programsetting->phone = $generalSettings->phone;
            $Programsetting->printingpapersize = $generalSettings->printingpapersize;
            $Programsetting->roundnumbers = $generalSettings->roundnumbers;
            $Programsetting->saveprinting = $generalSettings->saveprinting;
            $Programsetting->specializtion = $generalSettings->specializtion;
            $Programsetting->website = $generalSettings->website;
            $Programsetting->userid = $generalSettings->userid;
            $Programsetting->showPreviousPrice = 1;
            $Programsetting->programsettingsid = 1;

            $ProgramsettingEX->insertExt($Programsetting);
        }
    }

    firstlogin();

    //check if there is database name in dbNames.txt
    $file_path = "../views/default/archiveview/dbNames.txt";
    if (filesize($file_path) == 0) {

        // file is empty
        //put new database name into file
        file_put_contents("../views/default/archiveview/dbNames.txt", "storesdb", FILE_APPEND | LOCK_EX);

        //insert into newdbname table
        $newDbName->dbname = "storesdb";
        $newDbNameDAO->insert($newDbName);
    }

    if (isset($_SESSION['userid']) && $_SESSION['userid'] != "") {
        $sessionUserId = $_SESSION['userid'];
        $sessionUsergroupId = $_SESSION['usergroupid'];

        $userGroupData = $myUserGroupRecord->load($sessionUsergroupId);
        $startPage = $userGroupData->startpage;

        //echo $startPage;
        //send the user to the start page
        if ($startPage != 'index.php') {
            header("location:" . $startPage . "");
        }

        /* $myURL=curPageURL();
          $myURL=explode("controllers",$myURL);

          echo '<script type="text/javascript">
          window.location = $myURL[0].'controllers/'.$startPage;
          </script>'; */
    } else {
        header("location:login.php");
    }
}
##########################################################################################################################################################
//here the global templates
$smarty->assign('accessscriptindex', 1);
$smarty->display("footer.html");

////****************************  Functions  ********************///
##########################################################  prepare sql file to send it to offline programs###############################################
function prepareSqlFile($host, $user, $pass, $name) {
    $tables = array("client", 'insurancecompanies', 'paymentnetworks', 'store', 'user', 'product', 'productcat', 'unit', 'doctorkashf',
        'storedetail', 'usergroup', 'clientarea', 'kashf');

    EXPORT_TABLES($host, $user, $pass, $name, $tables);
}

function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false) {
    $mysqli = new mysqli($host, $user, $pass, $name);

    $mysqli->select_db($name);

    $mysqli->query("SET NAMES 'utf8'");
    $queryTables = $mysqli->query('SHOW TABLES');
    while ($row = $queryTables->fetch_row()) {
        $target_tables[] = $row[0];
    } if ($tables !== false) {
        $target_tables = array_intersect($target_tables, $tables);
    }

    foreach ($target_tables as $table) {
        $result = $mysqli->query('SELECT * FROM ' . $table);
        $fields_amount = $result->field_count;
        $rows_num = $mysqli->affected_rows;
        $res = $mysqli->query('SHOW CREATE TABLE ' . $table);
        $TableMLine = $res->fetch_row();

        //   $content = (!isset($content) ? '' : $content) . "\n\n DROP TABLE " . $table . " ;\n\n" . $TableMLine[1] . ";\n\n";
        $content = (!isset($content) ? '' : $content) . "\n\n";
        for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) {
            while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
                if ($st_counter % 100 == 0 || $st_counter == 0) {
                    $content .= "\nREPLACE INTO " . $table . " VALUES";
                }
                $content .= "\n(";
                for ($j = 0; $j < $fields_amount; $j++) {
                    $row[$j] = str_replace("\n", "\\n", addslashes($row[$j]));
                    if (isset($row[$j])) {
                        $content .= '"' . $row[$j] . '"';
                    } else {
                        $content .= '""';
                    } if ($j < ($fields_amount - 1)) {
                        $content.= ',';
                    }
                }
                $content .=")";
                //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num) {
                    $content .= ";";
                } else {
                    $content .= ",";
                } $st_counter = $st_counter + 1;
            }
        }
        $content .="\n\n\n";
        $content .="#########delimiter########";
        $content .="\n";
    }

    #######################################################################
    #############################   save file
    $handle = fopen('backup/tables_updates.sql', 'w+');
    fwrite($handle, $content);
    fclose($handle);

    echo '<div class="row">'
    . '<div class="container">'
    . '<div class="mainindex well well-sm">'
    . 'update file created '
    . '</div></div>'
    . '</div>';

    updateOffline();

    #######################################################################
//    $backup_name = $backup_name ? $backup_name : $name . "_tables_updates.sql";
//    header('Content-Type: application/octet-stream');
//    header("Content-Transfer-Encoding: Binary");
//    header("Content-disposition: attachment; filename=\"" . $backup_name . "\"");
//    echo $content;
//    exit;
}

function updateOffline() {
    $jsScript = '';
    $jsScript .= '$.post("http://localhost/erp2016_offline/controllers/billsajax.php?do=updatedbfromonline",  function (rsltC1) {';
    //$jsScript .= 'alert(222222);';
    $jsScript .= 'if (Number(rsltC1) == 111){';
    $jsScript .= 'console.log(rsltC1);';
    $jsScript .= '} else {';
    $jsScript .= 'console.log(rsltC1);';
    $jsScript .= '}';
    $jsScript .= '});';


    print_r('<script>');
    print_r($jsScript);
    print_r('</script>');
}

#######################################################################################################################################################################################################
## mda network daily entry
/*
  function yesterdayNetworkDailyEntry($generalSettings) {
  global $ProgramsettingDAO;
  global $billsEX;
  ################################################################################################
  if (empty($generalSettings->dailyentrydate)) {
  $generalSettings->dailyentrydate = date('Y-m-d', strtotime("-1 days"));
  $ProgramsettingDAO->update($generalSettings);
  }
  ################################################################################################
  if (date('Y-m-d', strtotime("-1 days")) > $generalSettings->dailyentrydate) {
  $lastDailyEntryDate = new DateTime($generalSettings->dailyentrydate);
  $yesterday = new DateTime(date('Y-m-d', strtotime("-1 days")));

  $interval = $yesterday->diff($lastDailyEntryDate);




  for ($i = 1; $i <= $interval->days; $i++) {
  $cardValue = 0;
  $date = date('Y-m-d', strtotime($generalSettings->dailyentrydate . '+ ' . $i . 'day'));
  $bills = $billsEX->queryByBilldateAndNetwork($date, 4);     ## mda network
  if (count($bills) > 0) {
  foreach ($bills as $bill) {
  $cardValue = $cardValue + $bill->cardvalue;
  }
  saveDailyEntry(4, $cardValue, $date);
  }
  }
  }
  ################################################################################################
  else {
  $generalSettings->dailyentrydate = date('Y-m-d', strtotime("-1 days"));
  $ProgramsettingDAO->update($generalSettings);
  }
  ################################################################################################
  }

  function saveDailyEntry($networkId, $cardValue, $date) {
  global $dailyEntry;      ## Dailyentry
  global $accountsTreeDAO;
  global $paymentNetworksDAO;
  global $ProgramsettingEX;

  $mytransactions = new Transaction();

  $dailyEntryDebtorArray = array();
  $dailyEntryCreditorArray = array();

  $dailyEntry->dDateTime = date('Y-m-d h:i:s', strtotime($date));
  $dailyEntry->entryComment = '';

  $entryValue = calcEntryValue($cardValue);

  #############################################  من خصومات الشبكة الى حساب الشبكة    ############################################
  #############################################  Debtor  ############################################
  $paymentNetworks = $paymentNetworksDAO->load($networkId);
  $accountsTree = $accountsTreeDAO->queryByName('رسوم ' . $paymentNetworks->name);

  if (count($accountsTree) > 0) {
  $treeId = $accountsTree[0]->id;
  } else {
  $treeId = addTreeElement('رسوم ' . $paymentNetworks->name, 37, 0, 0, 1, '', 0, 0);
  }

  $dailyEntryDebtor->value = $entryValue;
  $dailyEntryDebtor->accountstreeid = $treeId;
  array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

  #############################################  Creditor  ############################################
  $accountsTree2 = $accountsTreeDAO->queryByName($paymentNetworks->name);
  if (count($accountsTree2) > 0) {
  $treeId2 = $accountsTree2[0]->id;
  } else {
  $treeId2 = addTreeElement($paymentNetworks->name, 41, 3, 0, 1, '', 0, 0);
  }
  $dailyEntryCreditor->value = $entryValue;
  $dailyEntryCreditor->accountstreeid = $treeId2;
  array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

  #############################################  save daily entry  ############################################

  try {
  $data = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
  //        $dailyEntryId = $data[1];
  //
  //        $bills->dailyentryid = $dailyEntryId;
  //        $billsDAO->update($bills);
  ## save last date of recording daily entry in setting table
  $ProgramsettingEX->updateObj('programsettings', 'dailyentrydate', $date, 'programsettingsid', 1);

  $mytransactions->commit();

  $message = 'تمت العملية بنجاح';
  } catch (Exception $ex) {
  $mytransactions->rollback();
  $message = 'عفوا لقد حدث خطأ';
  }
  }

  function calcEntryValue($cardValue) {
  $entryValue = 0;
  $discount = 0;


  ## discount =  .7%  of total card value
  if ($cardValue < 5000) {
  $discount = (7 * $cardValue ) / 1000;
  $entryValue = $cardValue - $discount;
  }

  ## discount = 40 Rs
  else {
  $discount = 40;
  $entryValue = $cardValue - $discount;
  }

  return $entryValue;
  }
 */
####################################################################################################################################################################################

function firstlogin() {
    //"firstbackup_".date('Y-m-d')
    global $dbhostc;
    global $dbuserc;
    global $dbpasswordc;
    global $dbnamec;


    $CHECKdata = CHECKdatabase($dbhostc, $dbuserc, $dbpasswordc);
    if ($CHECKdata == 1) {
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . 'Check databsae done '
        . '</div></div>'
        . '</div>';
    } else {
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . 'check error '
        . '</div></div>'
        . '</div>';
    }

    $repardata = repardatabase($dbhostc, $dbuserc, $dbpasswordc);
    if ($repardata == 1) {
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . 'Repair  databsae  done  '
        . '</div></div>'
        . '</div>';
    } else {
        echo '<div class="row">'
        . '<div class="container">'
        . '<div class="mainindex well well-sm">'
        . 'Repair error '
        . '</div></div>'
        . '</div>';
    }
    $newdbname = "firstbackup_" . date('Y-m-d');
    $filename = '../db_backups/' . $newdbname . '.sql';


    if (file_exists($filename)) {

        return;
    } else {


        @$done = backup_tables('*', '../db_backups/', $_SESSION['dbname'], $dbhostc, $dbuserc, $dbpasswordc);

        if ($done == 1) {
            echo '<div class="row">'
            . '<div class="container">'
            . '<div class="mainindex well well-sm">'
            . 'First backup  databsae  done   '
            . '</div></div>'
            . '</div>';
        } else {
            echo '<div class="row">'
            . '<div class="container">'
            . '<div class="mainindex well well-sm">'
            . 'Backup error  '
            . '</div></div>'
            . '</div>';
        }
    }
}

function insertUserGroup() {
    global $userGroup;
    global $userGroupDAO;

    $userGroup->conditions = 0;
    $userGroup->currentdate = date("Y-m-d");
    $userGroup->level = 1;
    $userGroup->startpage = "index.php";
    $userGroup->usergroupdescription = "admin";
    $userGroup->usergroupname = "admin";

    $userGroupDAO->insert($userGroup);
}

function insertUser() {
    global $user;
    global $userDAO;

    $user->conditions = 0;
    $user->currentdate = date("Y-m-d");
    $user->employeename = "admin";
    $user->password = "123";
    $user->saveid = 1;
    $user->usergroupid = 1;
    $user->username = "admin";

    $userDAO->insert($user);
}

function CHECKdatabase($db_host, $db_user, $db_password) {

    $newDatabaseLink = mysql_connect('localhost', $db_user, $db_password) or die(mysql_error());

    mysql_select_db($_SESSION['dbname'], $newDatabaseLink) or die("Unable to select database: " . $_SESSION['dbname']);

    try {

        //insert in billsettings tbl
        mysql_query("CHECK TABLE  `accountmovement` ,  `assets` ,  `assetscat` ,  `bank` ,  `bankaccount` ,  `billname` ,  `billproperty` ,  `billsettings` ,  `buyandruternbill` ,  `buyandruternbilldetail` , `buybill` ,  `buybilldetail` ,  `capital` ,  `checkcontroller` ,  `checkdeposit` ,  `checkwithdrawal` , `cashtransfer`, `client` ,  `clientdebtchange` ,  `expenses` ,  `expensestype` ,  `kempiala` ,  `menuurl` , `movementmanage` ,  `newdbbackup` ,  `newdbname` ,  `partner` ,  `partnerwithdrawal` ,  `policy` ,  `product` ,  `productcat` ,  `productcatunit` ,  `productrecieve` ,  `productserial` , `productsetting` ,  `producttemp` ,  `producttempunit` ,  `productunit` ,  `programsettings` ,  `properties` ,  `relusergroupproperties` ,  `representativecompany` ,  `returnbuybill` , `returnbuybilldetail` ,  `returnsellbill` ,  `returnsellbilldetail` ,  `save` ,  `savedaily` ,  `sellandruternbilldetail` ,  `sellbill` ,  `sellbillandrutern` ,  `sellbilldetail` ,  `shippercompanies` , `sparepart` ,  `sparepartstore` ,  `sparepartstoredetails` ,  `sparepartstorereport` ,  `store` ,  `storedetail` ,  `storemovement` ,  `storereport` ,  `supplier` ,  `supplierdebtchange` , `transfermoney` ,  `unit` ,  `user` ,  `usergroup`"
                        , $newDatabaseLink) or die(mysql_error());

        return 1;
    } catch (Exception $e) {
        return 0;
    }
}

function repardatabase($db_host, $db_user, $db_password) {
    /* $db_host ="localhost"; //$_POST['db_host'];
      $db_user = "root";//$_POST['db_user'];
      $db_password = "123456";//$_POST['db_password'];
     */
    //print_r($_SESSION['dbname'].'l1111111111');
    $newDatabaseLink = mysql_connect($db_host, $db_user, $db_password) or die(mysql_error());

    mysql_select_db($_SESSION['dbname'], $newDatabaseLink) or die("Unable to select database: " . $rs['Database']);

    try {

        //insert in billsettings tbl
        mysql_query("REPAIR TABLE  `accountmovement` ,  `assets` ,  `assetscat` ,  `bank` ,  `bankaccount` ,  `billname` ,  `billproperty` ,  `billsettings` ,  `buyandruternbill` ,  `buyandruternbilldetail` , `buybill` ,  `buybilldetail` ,  `capital` ,  `checkcontroller` ,  `checkdeposit` ,  `checkwithdrawal` , `cashtransfer`  ,   `client` ,  `clientdebtchange` ,  `expenses` ,  `expensestype` ,  `kempiala` ,  `menuurl` , `movementmanage` ,  `newdbbackup` ,  `newdbname` ,  `partner` ,  `partnerwithdrawal` ,  `policy` ,  `product` ,  `productcat` ,  `productcatunit` ,  `productrecieve` ,  `productserial` , `productsetting` ,  `producttemp` ,  `producttempunit` ,  `productunit` ,  `programsettings` ,  `properties` ,  `relusergroupproperties` ,  `representativecompany` ,  `returnbuybill` , `returnbuybilldetail` ,  `returnsellbill` ,  `returnsellbilldetail` ,  `save` ,  `savedaily` ,  `sellandruternbilldetail` ,  `sellbill` ,  `sellbillandrutern` ,  `sellbilldetail` ,  `shippercompanies` , `sparepart` ,  `sparepartstore` ,  `sparepartstoredetails` ,  `sparepartstorereport` ,  `store` ,  `storedetail` ,  `storemovement` ,  `storereport` ,  `supplier` ,  `supplierdebtchange` , `transfermoney` ,  `unit` ,  `user` ,  `usergroup`"
                        , $newDatabaseLink) or die(mysql_error());

        mysql_close($newDatabaseLink);
        return 1;
    } catch (Exception $e) {
        mysql_close($newDatabaseLink);
        return 0;
    }
}

function backup_tables($tables, $backupdir, $dbname, $db_host, $db_user, $db_password) {


    $root = $db_user;
    $host = $db_host;
    $passd = $db_password;
    global $partition;
    global $ProgramsettingDAO;
    $generalSettings = $ProgramsettingDAO->load(1);
    $partition = $generalSettings->partition;
//$dbname='farm';
    $newname = date("Y-m-d");

//$ccccccccccc="//197.44.62.106/gt4apps/newstorex/db_backups/firstbackup_$newname.sql";
    $inrtoi = "../db_backups/firstbackup_$newname.sql";
//$command = "E:\AppServ\MySQL\bin\mysqldump --user=$root --password=$passd --host=$host $dbname > ../db_backups/firstbackup_$newname.sql";
    //$command = "$partition:\AppServ\MySQL\bin\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $ccccccccccc";
    $command = "$partition:\wamp\bin\mysql\mysql5.6.17\bin\mysqldump --user=$db_user --password=$db_password --host=$host $dbname > $inrtoi";

    $vvv = system($command);

    return 1;
//	echo $backupdir=;
    //$backupdir = "../db_backups";
    //echo $backupdir;
    //*** Start Transaction ***//
    /* $newDatabaseLink = mysql_connect('localhost', $db_user, $db_password) or die(mysql_error());

      mysql_select_db($_SESSION['dbname'],$newDatabaseLink) or die("Unable to select database: " . $rs['Database']);

      mysql_query("START TRANSACTION");
      mysql_query("BEGIN");

      //get all of the tables
      if($tables == '*')
      {
      $tables = array();
      $result = mysql_query('SHOW TABLES');

      while($row = mysql_fetch_row($result))
      {
      $tables[] = $row[0];
      }
      }
      else
      {
      $tables = is_array($tables) ? $tables : explode(',',$tables);
      }

      //cycle through
      foreach($tables as $table)
      {
      mysql_query("SET NAMES 'utf8'");
      mysql_query('SET CHARACTER_SET utf8');
      $result = mysql_query('SELECT * FROM '.$table);
      $num_fields = mysql_num_fields($result);

      $return.= 'DROP TABLE IF EXISTS '.$table.';';
      $rows = mysql_query('SHOW CREATE TABLE '.$table);
      if($result && $rows)
      {
      mysql_query("COMMIT");
      }
      else
      {
      mysql_query("ROLLBACK");
      }


      $row2 = mysql_fetch_row($rows);
      $return.= "\n\n".$row2[1].";\n\n";

      for ($i = 0; $i < $num_fields; $i++)
      {
      while($row = mysql_fetch_row($result))
      {
      $return.= 'INSERT INTO '.$table.' VALUES(';
      for($j=0; $j<$num_fields; $j++)
      {
      $row[$j] = addslashes($row[$j]);
      $row[$j] = ereg_replace("\n","\\n",$row[$j]);
      if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
      if ($j<($num_fields-1)) { $return.= ','; }
      }
      $return.= ");\n";
      }
      }
      $return.="\n\n\n";
      }
      //save file
      //echo $backupdir;
      $handle = fopen($backupdir.$dbname.'.sql','w+');
      //$handle = fopen($backupdir.''.date("Y-m-d").'.sql','w+');
      fwrite($handle,$return);
      fclose($handle);
      mysql_close($newDatabaseLink);
      if($handle)
      {
      return 1;
      }
      //return $message;

     */
}

/* function curPageURL() {
  $pageURL = 'http';
  if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
  $pageURL .= "://";
  if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  }
  return $pageURL;
  } */
?>
