<?php
include "db_connection/db_connection.php";
	include "config/config.php";
/**
* Updated: Mohammad M. AlBanna
* Website: MBanna.info
*/

ini_set('display_errors', false);

error_reporting(-1);

set_error_handler(function($code, $string, $file, $line){
        throw new ErrorException($string, null, $code, $file, $line);
    });

register_shutdown_function(function(){
	global $connect;
        $error = error_get_last();
        if(null !== $error)
        {
		$start_date = date('Y-m-d H:i:s');
		$end_date = date('Y-m-d H:i:s');
		$ins_query = mysqli_query($connect,"insert into backup_details(start_date,end_date,status,file_name,created_by) values('".$start_date."','".$end_date."','0','','1')") or die(mysqli_error($connect));
		if($ins_query){
           // echo 'Failed to download';
		echo "<script>alert('Failed to Download');</script>";
	   echo "<script>window.location.href='backup.php?ret=f';</script>";
       exit;
		}
        }
    });



//MySQL server and database
$dbhost = $host;
$dbuser = $root;
$dbpass = $pswd;
$dbname = 'alday_accounts';
$tables = '*';

//Call the core function
backup_tables($dbhost, $dbuser, $dbpass, $dbname, $tables);

//Core function
function backup_tables($host, $user, $pass, $dbname, $tables = '*') {
   // $link = mysqli_connect($host,$user,$pass, $dbname);
   global $connect;
	try
{

    // Check connection
    if (mysqli_connect_errno())
    {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    }

    mysqli_query($connect, "SET NAMES 'utf8'");

    //get all of the tables
    if($tables == '*')
    {
        $tables = array();
        $result = mysqli_query($connect, 'SHOW TABLES');
		$ij=0;
        while($row = mysqli_fetch_row($result))
        {
			//if($ij<5){
            $tables[] = $row[0];
			//}
			$ij++;
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
//print_r($tables);
    $return = '';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($connect, 'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $num_rows = mysqli_num_rows($result);

        $return.= 'DROP TABLE IF EXISTS '.$table.';';
        $row2 = mysqli_fetch_row(mysqli_query($connect, 'SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
        $counter = 1;

        //Over tables
        for ($i = 0; $i < $num_fields; $i++) 
        {   //Over rows
            while($row = mysqli_fetch_row($result))
            {
                if($counter == 1){
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                } else{
                    $return.= '(';
                }

				//Over fields
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) {
						$return.= '"'.$row[$j].'"' ; 
					} else { 
						$return.= '""'; 
					}
                    if ($j<($num_fields-1)) { $return.= ','; }
                }

               if($num_rows == $counter){
                    $return.= ");\n";
                } else{
                    $return.= "),\n";
                }

				++$counter;
            }
        }
        $return.="\n\n\n";
    }
    $fileName = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
	$start_date = date('Y-m-d H:i:s');
	$ins_query = mysqli_query($connect,"insert into backup_details(start_date,end_date,status,file_name,created_by) values('".$start_date."','','1','".$fileName."','1')") or die(mysqli_error($connect));
    //save file
    $handle = fopen($fileName,'w');
    fwrite($handle,$return);

    fclose($handle);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fileName));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileName));
    readfile($fileName);
    exit;

	
    if(fclose($handle)){
       // echo "Done, the file name is: ".$fileName;
	   echo "<script>alert('Done');</script>";
	   echo "<script>window.location.href='backup.php?ret=s';</script>";
       exit;
    } 
	}
catch(\Exception $exception)
{
   // echo 'Caught in try/catch';
		echo "<script>alert('Failed to Download');</script>";
	   echo "<script>window.location.href='backup.php';</script>";
       exit;
}

}
