<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/function.php");

$zdir = $dbname;
$zcomp = 1;
$zdbroot = $zdir;
$focusfield = "submit";
$usertype = $_SESSION["usertype"];
$username = $_SESSION["username"];
$getusercode = mysqli_query($conn, "SELECT code,user FROM `passmain` WHERE user = '$username' ") or die(mysqli_error($conn));
$gusercode = mysqli_fetch_array($getusercode);
$zroot = $_SESSION["zdbroot"];
$zroot1 = substr($zroot, 0, -4);

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

// Database configuration
$host = "localhost";
$username = "techfar_FarTechFK";
$password = 'raJ$FK#3t';
$database_name = "$zdb";

// Get connection object and set the charset
$conn = mysqli_connect($host, $username, $password, $database_name);
$conn->set_charset("utf8");


// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

$sqlScript = "";
foreach ($tables as $table) {
    
    // Prepare SQLscript for creating table structure
    $query = "SHOW CREATE TABLE $table";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);
    
    $sqlScript .= "\n\n" . $row[1] . ";\n\n";
    
    
    $query = "SELECT * FROM $table";
    $result = mysqli_query($conn, $query);
    
    $columnCount = mysqli_num_fields($result);
    
    // Prepare SQLscript for dumping data for each table
    for ($i = 0; $i < $columnCount; $i ++) {
        while ($row = mysqli_fetch_row($result)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $columnCount; $j ++) {
                $row[$j] = $row[$j];
                
                if (isset($row[$j])) {
                    $sqlScript .= '"' . $row[$j] . '"';
                } else {
                    $sqlScript .= '""';
                }
                if ($j < ($columnCount - 1)) {
                    $sqlScript .= ',';
                }
            }
            $sqlScript .= ");\n";
        }
    }
    
    $sqlScript .= "\n"; 
}

if(!empty($sqlScript))
{
    // Save the SQL script to a backup file
    $backup_file_name = $database_name . '_backup_' . time() . '.sql';
    $fileHandler = fopen($backup_file_name, 'w+');
    $number_of_lines = fwrite($fileHandler, $sqlScript);
    fclose($fileHandler); 

    // Download the SQL backup file to the browser
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backup_file_name));
    ob_clean();
    flush();
    readfile($backup_file_name);
    exec('rm ' . $backup_file_name); 
}

//session_start();
//require("includes/check_auth_user.php");
//require("includes/dbconnect.php");
//require("includes/function.php");
//    
//
//$admin  = $_SESSION["admin_" . $dbname];
//
//$zdb    = $_SESSION["zdir"];
////browse($zdb);
//$datestamp = date("Y-m-d");      // Current date to append to filename of backup file in format of YYYY-MM-DD
//##################### 
////CONFIGURATIONS  
//#####################
//// Define the name of the backup directory
////CONFIGURATIONS  
//#####################
//// Define the name of the backup directory
//define("OUTPUT_DIR", 'backupdb');
//// Define  Database Credentials
//define('HOST', 'localhost');
//define('USER', 'fksys_Fir35Zar110');
//define('PASSWORD', 'zaR110#fiR35');
//define('DB_NAME', $zdb);
//
///*
//  Define the filename for the sql file
//  If you plan to upload the  file to Amazon's S3 service , use only lower-case letters
// */
//$fileName = 'mysqlbackup--' . date('d-m-Y') . '@' . date('h.i.s') . '.sql';
//// Set execution time limit
//
//if (function_exists('max_execution_time')) {
//    if (ini_get('max_execution_time') > 0)
//        set_time_limit(0);
//}
//
//###########################  
////END  OF  CONFIGURATIONS  
//###########################
//// Check if directory is already created and has the proper permissions
//
//
//if (!file_exists(OUTPUT_DIR))
//    mkdir(OUTPUT_DIR, 0700);
//if (!is_writable(OUTPUT_DIR))
//    chmod(OUTPUT_DIR, 0700);
//
//// Create an ".htaccess" file , it will restrict direct accss to the backup-directory . 
//$content = 'deny from all';
//$file = new SplFileObject(OUTPUT_DIR . '/.htaccess', "w");
//$file->fwrite($content);
//
//$mysqli = new mysqli(HOST, USER, PASSWORD, DB_NAME);
//if (mysqli_connect_errno()) {
//    printf("Connect failed: %s", mysqli_connect_error());
//    exit();
//}
//
//
//// Introduction information
//$return .= "--\n";
//$return .= "-- A Mysql Backup System \n";
//$return .= "--\n";
//$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n";
//$return = "--\n";
//$return .= "-- Database : " . DB_NAME . "\n";
//$return .= "--\n";
//$return .= "-- --------------------------------------------------\n";
//$return .= "-- ---------------------------------------------------\n";
//$return .= 'SET AUTOCOMMIT = 0 ;' . "\n";
//$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' . "\n";
//$tables = array();
//// Exploring what tables this database has
//$result = $mysqli->query('SHOW TABLES');
//// Cycle through "$result" and put content into an array
//while ($row = $result->fetch_row()) {
//    $tables[] = $row[0];
//}
//// Cycle through each  table
//foreach ($tables as $table) {
//// Get content of each table
//    $result = $mysqli->query('SELECT * FROM ' . $table);
//// Get number of fields (columns) of each table
//    $num_fields = $mysqli->field_count;
//// Add table information
//    $return .= "--\n";
//    $return .= '-- Tabel structure for table `' . $table . '`' . "\n";
//    $return .= "--\n";
//    $return.= 'DROP TABLE  IF EXISTS `' . $table . '`;' . "\n";
//// Get the table-shema
//    $shema = $mysqli->query('SHOW CREATE TABLE ' . $table);
//// Extract table shema 
//    $tableshema = $shema->fetch_row();
//// Append table-shema into code
//    $return.= $tableshema[1] . ";" . "\n\n";
//// Cycle through each table-row
//    while ($rowdata = $result->fetch_row()) {
//// Prepare code that will insert data into table 
//        $return .= 'INSERT INTO `' . $table . '`  VALUES ( ';
//// Extract data of each row 
//        for ($i = 0; $i < $num_fields; $i++) {
//            $return .= '"' . mysqli_real_escape_string($mysqli, $rowdata[$i]) . "\",";
//        }
//        // Let's remove the last comma 
//        $return = substr("$return", 0, -1);
//        $return .= ");" . "\n";
//    }
//    $return .= "\n\n";
//}
//
//// Close the connection
//$mysqli->close();
//$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n";
//$return .= 'COMMIT ; ' . "\n";
//$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n";
//
//
////$file = file_put_contents($fileName , $return) ; 
//$zip = new ZipArchive();
//
//
//$resOpen = $zip->open(OUTPUT_DIR . '/' . $fileName . ".zip", ZIPARCHIVE::CREATE);
//if ($resOpen) {
//    $zip->addFromString($fileName, "$return");
//}
//
//$zip->close();
//$fileSize = get_file_size_unit(filesize(OUTPUT_DIR . "/" . $fileName . '.zip'));
//$message = <<<msg
//  <h2>BACKUP  completed .</h2>
// 
//  the archive has the name of  : <b>  $fileName  </b> and it's file-size is :   $fileSize  .
//
// 
//msg;
//echo $message;
//
//// Function to append proper Unit after file-size . 
//function get_file_size_unit($file_size) {
//    switch (true) {
//        case ($file_size / 1024 < 1) :
//            return intval($file_size) . " Bytes";
//            break;
//        case ($file_size / 1024 >= 1 && $file_size / (1024 * 1024) < 1) :
//            return intval($file_size / 1024) . " KB";
//            break;
//        default:
//            return intval($file_size / (1024 * 1024)) . " MB";
//    }
//}
//
///*  Download Backup Into Zip for Local Computer   */
//
//// Creating zip File
//$zipfname = $zdb . "_" . date("Y-m-d_H-i-s").".zip";
//$zip = new ZipArchive();
//if($zip->open($zipfname,ZIPARCHIVE::CREATE)) 
//{
//   $zip->addFromString($fileName,$return);
//   $zip->close();
//}
// 
//// read zip file and send it to standard output
//if (file_exists($zipfname)) {
//    header('Content-Description: File Transfer');
//    header('Content-Type: application/octet-stream');
//    header('Content-Disposition: attachment; filename='.basename($zipfname));
//    flush();
//    readfile($zipfname);
//    exit; 
//}
//
///*  Email Part  */
//
//$htmlbody = " Your Mail Contant Here.... You can use html tags here...";
//$to = "bsufiyan79@gmail.com"; //Recipient Email Address
//$subject = "Test email with attachment"; //Email Subject
//$headers = "From: bsufiyan79@gmail.com\r\nReply-To: bsufiyan79@gmail.com";
//$random_hash = md5(date('r', time()));
//$headers .= "\r\nContent-Type: multipart/mixed; 
//boundary=\"PHP-mixed-".$random_hash."\"";
//// Set your file path here
////$attachment = chunk_split(base64_encode(file_get_contents('backupdb'))); 
//$attachment = $zipfname; 
//
//
////define the body of the message.
//$message = "--PHP-mixed-$random_hash\r\n"."Content-Type: multipart/alternative; 
//boundary=\"PHP-alt-$random_hash\"\r\n\r\n";
//$message .= "--PHP-alt-$random_hash\r\n"."Content-Type: text/plain; 
//charset=\"iso-8859-1\"\r\n"."Content-Transfer-Encoding: 7bit\r\n\r\n";
//
//
////Insert the html message.
//$message .= $htmlbody;
//$message .="\r\n\r\n--PHP-alt-$random_hash--\r\n\r\n";
//
//
////include attachment
//$message .= "--PHP-mixed-$random_hash\r\n"."Content-Type: application/zip; 
//name=\"$fileName\"\r\n"."Content-Transfer-Encoding: 
//base64\r\n"."Content-Disposition: attachment\r\n\r\n";
//
//$message .= $attachment;
//$message .= "/r/n--PHP-mixed-$random_hash--";
//
//
////send the email
//$mail = mail( $to, $subject , $message, $headers );
//
//echo $mail ? "Mail sent" : "Mail failed";
//
//
//
//
//?>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script>
            $('#buttonID').click(function(){
            $('#img').show(); //<----here
            $.ajax({
              ....
             success:function(result){
                 $('#img').hide();  //<--- hide again
            }
        }
        </script>
    </head>
    <body>
        <img src="..\images\loading.gif" id="img" style="display:none" >
    </body>        
</html>