<?php
error_reporting(E_ERROR); //E_ALL
require_once('../models/sql/ConnectionProperty.class.php');
// include FTP class
include "../library/SFTP.php";

$DBName = getDB();

//it also set timezone to make date() function of php accurate
$ftpInfo = getFTPConfig($DBName);

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


// set SFTP object, use host, username and password
//$ftp = new SFTP("gt4host.com", "sawatime", "S@watime123456789");
$ftp = new SFTP($ftpInfo->remoteBackupLink, $ftpInfo->remoteBackupUser, $ftpInfo->remoteBackupPass);
//You almost always need to use the passive mode.
//PHP defaults to the active FTP mode. The active mode hardly ever works these days due to ubiquitous firewalls/NATs/proxies.
$ftp->SetFTPPassiveMode(TRUE);

// connect to FTP server
if($ftp->connect()) {
    //print "Connection successful";
    //downloadFTP($ftp, "my2.php", "my2Local.php");
    my_cd_mkdir($ftp, $ftpInfo->remoteBackupFolder);  
    if(!isset($do)||empty($do)){
        //uplode daily backup
        $filename = $DBName."_".date('Y-m-d').".sql";
        uploadFTP($ftp,"../db_backups/$filename",$filename);
    }elseif($do == "insta"){
        //upload instant backup
        my_cd_mkdir($ftp, "instantBackups");  
        $filename = date('Y-m-d').".txt";
        uploadFTP($ftp,"backup/$filename",$filename);
    }
    
    $ftp->close();
} else {
      //connection failed, display last error
      print "Connection failed: " . $ftp->error;
}

/*  ------------------------------------------------------------------------  */
function getDB(){
    ##1- set db name as last db name in dbNames.txt
    $databsesNames = trim(file_get_contents("../views/default/archiveview/dbNames.txt"));
    $databases = array_reverse(explode(",", $databsesNames));
    $DBName = $databases[0]; //"erp2016_7"
    return $DBName;
}
//it also set timezone to make date() function of php accurate
function getFTPConfig($DBName) {
    $data = new stdClass();
    //ConnectionProperty::getDatabase()
    $link = mysqli_connect(ConnectionProperty::getHost(), ConnectionProperty::getUser(), ConnectionProperty::getPassword(), $DBName);
    if (!$link) {
        //echo "Failed to connect to MySQL: " . mysqli_connect_error();
        throw new Exception('could not connect to database' . $DBName);
    } else {
        $result = mysqli_query($link, "SELECT timezone,remoteBackupLink,remoteBackupUser,remoteBackupPass,remoteBackupFolder FROM programsettings WHERE programsettingsid=1 limit 1");
        if (mysqli_num_rows($result) > 0) {
            // output data of each row
            while ($row = mysqli_fetch_assoc($result)) {
                date_default_timezone_set($row["timezone"]);
               // $smarty->assign("copyRightsStatment", $row["copyRightsStatment"]);
                $data->remoteBackupLink = $row["remoteBackupLink"];
                $data->remoteBackupUser = $row["remoteBackupUser"];
                $data->remoteBackupPass = $row["remoteBackupPass"];
                $data->remoteBackupFolder = $row["remoteBackupFolder"];
            }
        }
    }
    return $data;
}
function downloadFTP($ftp,$fileOnServer,$fileOnLocalHost){
    // download a file from FTP server
    // will download file "somefile.php" and  save locally as "localfile.php"
    //if($ftp->get("somefile.php", "localfile.php")) {
    if($ftp->get($fileOnServer, $fileOnLocalHost)) {
        print "File downloaded";
    } else {
        print "<br />Download failed: " . $ftp->error;
    }
}
function uploadFTP($ftp,$fileOnLocalHost,$fileOnServer){
    // upload file to FTP server
    // will upload file "local.php" and  save remotely as "remote.php"
    //if($ftp->put("local.txt", "remote.php")) {
    if($ftp->put($fileOnLocalHost, $fileOnServer)) {
          print "File uploaded";
    } else {
          print "<br />Upload failed: " . $ftp->error;
    }
}
//cd or mkdir and cd
//it is needed to sc directory by directory //jumping not allowed.it wont work
function my_cd_mkdir($ftp,$dirName){
    if(!empty($dirName)){
        if(!$ftp->cd($dirName)) {
            $ftp->mkdir($dirName);
            $ftp->cd($dirName);
              //print "<br />error: " . $ftp->error;
        } 
    }
}
?>