<!-- BACKUP -->
<?php

$backup_name = 'db_backup/backup_' . $database . '_(' . date('d-m-Y') . ').sql';
EXPORT_DATABASE($server, $username, $password, $database);

function EXPORT_DATABASE($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
	set_time_limit(3000);
	$mysqli = new mysqli($host, $user, $pass, $name);
	$mysqli->select_db($name);
	$mysqli->query("SET NAMES 'utf8'");
	$mysqli->query('SET GLOBAL FOREIGN_KEY_CHECKS = 0');
	$queryTables = $mysqli->query('SHOW TABLES');
	while ($row = $queryTables->fetch_row()) {
		$target_tables[] = $row[0];
	}
	if ($tables !== false) {
		$target_tables = array_intersect($target_tables, $tables);
	}
	$content = "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n--\r\n-- Database: `" . $name . "`\r\n--\r\n\r\n\r\n";

	$content .= 'SET GLOBAL FOREIGN_KEY_CHECKS = 0;';

	foreach ($target_tables as $table) {
		if (empty($table)) {
			continue;
		}
		$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 .= "\n\n" . $TableMLine[1] . ";\n\n";
		$TableMLine[1] = str_ireplace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS', $TableMLine[1]);

		$qTables = $mysqli->query('SHOW FULL TABLES');
		while ($rowTables = $qTables->fetch_row()) {
			if ($rowTables[0] ==  $table && $rowTables[1] == 'BASE TABLE') {
				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 .= "\nINSERT 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 .= 'SET GLOBAL FOREIGN_KEY_CHECKS = 1;';
	$content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
	$backup_name = $backup_name ? $backup_name : 'db_backup/backup_' . $name . '_(' . date('d-m-Y') . ').sql';

	// save to file
	$handle = fopen($backup_name, 'w+');
	fwrite($handle, $content);
	fclose($handle);
}

?>

<!-- RESTORE -->
<?php
if (isset($_POST['btn_restore'])) {
	$koneksi = mysqli_connect($server, $username, $password);
	mysqli_query('DROP DATABASE `' . $database . '`');
	mysqli_query('CREATE DATABASE `' . $database . '`');

	mysqli_select_db($database, $koneksi);

	$nama_file = $_FILES['datafile']['name'];
	$ukuran = $_FILES['datafile']['size'];

	if ($nama_file == "") {
		echo '<script type="text/javascript">toastr["error"]("File masih kosong","Gagal!")</script>';
	} else {
		//definisikan variabel file dan alamat file
		$uploaddir = 'db_restore/';
		$alamatfile = $uploaddir . $nama_file;

		if (move_uploaded_file($_FILES['datafile']['tmp_name'], $alamatfile)) {
			$filename = 'db_restore/' . $nama_file . '';
			$templine = '';
			$lines = file($filename);

			foreach ($lines as $line) {
				if (substr($line, 0, 2) == '--' || $line == '')
					continue;

				$templine .= $line;
				if (substr(trim($line), -1, 1) == ';') {
					mysqli_query($templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error() . '<br /><br />');
					$templine = '';
				}
			}
			echo '<script type="text/javascript">toastr["success"]("Berhasil membackup dan mendownload database.","Sukses!")</script>';
		} else {
			echo "Restore Database Gagal, kode error = " . $_FILES['location']['error'];
		}
	}
} else {
	unset($_POST['restore']);
}

?>

<div class="col-md-6">
	<div class="box box-primary">
		<div class="box-header with-border">
			<div class="box-title">Backup</div>
		</div>
		<div class="box-body">
			<div class="col-6 text-center">
				<div class="alert alert-danger text-center">
					<i class="fa fa-exclamation-triangle"></i> Warning!<br>
					Halaman ini digunakan untuk membackup seluruh database
				</div>
				<i class="fa fa-database" style="color:#03C9A9; font-size: 90pt"></i>
				<br><br>
				<a href="<?php echo $backup_name ?>" onclick="klik()" target='_BLANK' class="btn btn-primary" id="btnBackup" style="display: none">
					Download Backup Database
				</a>
			</div>
		</div>
	</div>
</div>

<div class="col-md-6">
	<div class="box box-primary">
		<div class="box-header with-border">
			<div class="box-title">Restore</div>
		</div>
		<div class="box-body">
			<form method="post" action="" enctype="multipart/form-data" id="frm-restore">
				<div class="form-group">
					<div class="row">
						<div class="col-md-5">
							<label>Masukkan file backup:</label>
						</div>
						<div class="col-md-6">
							<input type="file" name="datafile" class="form-control" />
						</div>
					</div>
				</div>
				<div class="form-group">
					<input type="submit" name="btn_restore" value="Restore" class="btn btn-primary" style="transition-delay: 100s;" />
				</div>
			</form>
		</div>
	</div>
</div>

<script type="text/javascript">
	$(document).ready(function() {
		$('#btnBackup').hide().delay(3000).fadeIn(1500);
	});

	function klik() {
		toastr["success"]("Berhasil membackup dan mendownload database.", "Sukses!")
	}
</script>