<?php
require_once ("secure_area.php");
class Dbbackup extends Secure_area
{
	function __construct()
	{
		parent::__construct('dbbackup');
	}

	function index()
	{
		$this->load->view("dbbackup");
	}
	function createbackup(){

		$path_to_root=getcwd();
		include($path_to_root . "/application/config/database.php");
		$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
		mysql_select_db($db['default']['database'], $conn);

		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result)){
			$tables[] = $row[0];
		}

		foreach($tables as $table)
		{
			$result = mysql_query('SELECT * FROM '.$table);
			$numFields = mysql_num_fields($result);

			$sql .= 'DROP TABLE IF EXISTS '.$table.';';
			$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
			$sql.= "\n\n".$row2[1].";\n\n";

			for ($i = 0; $i < $numFields; $i++)
			{
				while($row = mysql_fetch_row($result))
				{
					$sql .= 'INSERT INTO '.$table.' VALUES(';
					for($j=0; $j<$numFields; $j++)
					{
						$row[$j] = addslashes($row[$j]);
						$row[$j] = ereg_replace("\n","\\n",$row[$j]);
						if (isset($row[$j]))
						{
							$sql .= '"'.$row[$j].'"' ;
						}
						else
						{
							$sql.= '""';
						}

						if ($j < ($numFields-1))
						{
							$sql .= ',';
						}
					}

					$sql.= ");\n";
				}
			}
			$sql.="\n\n\n";
		}

		//////////////////////////make a file//////
		$current_directory=getcwd();
		$file_name_with_date=date("Ymd_His", time())."_".$db['default']['database'];
		$filename = $current_directory.'\database_backup\\'.$file_name_with_date.".sql";


		if (!file_exists($filename)) {
			$fhandle = fopen($filename,"w");
			fwrite($fhandle,$sql);
			fclose($fhandle);
		}

		$zip = new ZipArchive();
		$zip->open($current_directory.'\database_backup\\'.$file_name_with_date.".zip", ZipArchive::CREATE);
		$zip->addFile($filename);
		$zip->close();
		unlink($filename);
		//$this->load->view("dbbackup");
		echo json_encode(array('success'=>true,'message'=>$this->lang->line('database_backup_saved_successfully')));
	}
	
	function deletefile(){
		$explodeURLArray=explode("/",$_SERVER['REQUEST_URI']);
		$current_directory=getcwd();
		$deletefile=$current_directory."\database_backup\\".end($explodeURLArray);
		unlink($deletefile);
		$this->load->view("dbbackup");
	}
}
?>