<?php 

	$isDbOnly = false;
	$isDownload = false;

	if (!empty($_GET['db']))
	{
		$isDbOnly = true;
	}

	if (!empty($_GET['download']))
	{
		$isDownload = true;
	}

	require("../env.php");
	require("lib/bk_db.php");
	require("lib/bk_zip.php");

	$fileName = "db-backup-" . $env_database["database"] . "-" . time() . ".sql";
	$sqlFile = "../" . $fileName;

	backup_tables($env_database["hostname"], $env_database["username"], $env_database["password"], $env_database["database"], '*', $sqlFile);

	if ($isDownload)
	{
		$zip_file = $fileName . ".zip";
		create_zip(array($sqlFile), $zip_file, is_file($zip_file), "../");
		downloadFile($zip_file);
		unlink($sqlFile);
		return;
	}

	echo $sqlFile . '<br><br>';

	if ($isDbOnly)
	{
		return;
	}


	$name_zip_file = date("j-n-Y");
	$name_zip_file .= "-outputbooks.zip";

	$files_to_zip = array();
	$exclude = array(
		"../application/logs",
		"../application/third_party/html2pdf",
		"../application/third_party/mpdf"
	);

	directoryToArray("../application", true, $files_to_zip, $exclude);
	directoryToArray("../assets/app", true, $files_to_zip);
	directoryToArray("../uploads", true, $files_to_zip);

	$files_to_zip[] = $sqlFile;

	$result = create_zip($files_to_zip, $name_zip_file, false, "../");

	echo $name_zip_file . '<br><br>';

	if(is_file($sqlFile))
	{
		unlink($sqlFile);
	}

	function sendToFtp($file='')
	{
		$server = "IP FTP";
		$ftp_user_name="Username FTP";
		$ftp_user_pass="Password FTP";

		$connection = ftp_connect($server);
		$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);
		if (!$connection || !$login)
		{
			die('Connection attempt failed!');
		}
		$upload = ftp_put($connection, $file, $file, FTP_ASCII);
		if (!$upload)
		{
			echo 'FTP upload failed!';
		}
		ftp_close($connection);

		// Delete file zip and sql after backup
		$files_db = glob("*.sql");
		foreach($files_db as $file_db)
		{
			if(is_file($file_db))
			{
				unlink($file_db);
			}
		}
		unlink($name_zip_file);
	}

	// sendToFtp();

