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

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

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){


			$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,basename($filename));
			//$zip->addFile($filename);
			$zip->close();
			unlink($filename);

			$data['message']= array('success'=>true,'message'=>$this->lang->line('database_backup_saved_successfully')." File Name: ".$file_name_with_date.".zip");
			//echo json_encode(array('success'=>true,'message'=>$this->lang->line('database_backup_saved_successfully')));
		}
		$this->load->view("dbbackup",$data);

	}

	function deletefile($file_name){
		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){
			$current_directory=getcwd();
			$deletefile=$current_directory."\database_backup\\".$file_name;
			unlink($deletefile);
			$data['message']= array('success'=>true,'message'=>$this->lang->line('database_backup_deleted_successfully')." File Name: ".$file_name);
		}
		$this->load->view("dbbackup",$data);

		//echo json_encode(array('success'=>true,'message'=>$this->lang->line('database_backup_deleted_successfully')));
	}

	function periodic_sync(){

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){
			$this->load->model('Periodic_sync');
			$model = $this->Periodic_sync;
			$sync_complete = $model->do_period_sync(LOCATION_CODE);


			if($sync_complete==0){
				//echo json_encode(array('success'=>false,'message'=>"Error occour during process."));
				$data['message']= array('success'=>false,'message'=>"Error occour during process.");
			}
			elseif($sync_complete==1){
				//echo json_encode(array('success'=>true,'message'=>"Periodic sync has been successfully done."));
				$data['message']= array('success'=>true,'message'=>"Periodic sync has been successfully done.");
			}
			elseif($sync_complete==3){
				//echo json_encode(array('success'=>false,'message'=>"Server not found. please check internet connection."));
				$data['message']= array('success'=>false,'message'=>"Server not found. please check internet connection.");
			}
			elseif($sync_complete==3){
				//echo json_encode(array('success'=>false,'message'=>"Un-authorized Access."));
				$data['message']= array('success'=>false,'message'=>"Un-authorized Access.");
			}
		}else{
			$data['message']=array();
		}
		$this->load->view("sync",$data);

	}
	function regular_sync(){

		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){
			$this->load->model('Regular_sync');
			$model = $this->Regular_sync;


			$sync_complete = $model->do_regular_sync_user(LOCATION_CODE); ///1
			$sync_complete = $model->do_regular_sync_customer_add(LOCATION_CODE); ///2
			$sync_complete = $model->do_regular_sync_customer(LOCATION_CODE); ///3
			$sync_complete = $model->do_regular_sync_local_sale(LOCATION_CODE); ///4
			$sync_complete = $model->do_regular_sync_global_sale(LOCATION_CODE); ///5
			$sync_complete = $model->do_regular_sync_global_sale_delivery(LOCATION_CODE); ///6
			$sync_complete = $model->do_regular_sync_stock_moves(LOCATION_CODE); ///7

			if($sync_complete==0){
				//echo json_encode(array('success'=>false,'message'=>"Error occour during process."));
				$data['message']= array('success'=>false,'message'=>"Error occour during process.");
			}
			elseif($sync_complete==1){
				//echo json_encode(array('success'=>true,'message'=>"Periodic sync has been successfully done."));
				$data['message']= array('success'=>true,'message'=>"Regular sync has been successfully done.");
			}
			elseif($sync_complete==3){
				//echo json_encode(array('success'=>false,'message'=>"Server not found. please check internet connection."));
				$data['message']= array('success'=>false,'message'=>"Server not found. please check internet connection.");
			}
			elseif($sync_complete==3){
				//echo json_encode(array('success'=>false,'message'=>"Un-authorized Access."));
				$data['message']= array('success'=>false,'message'=>"Un-authorized Access.");
			}
		}else{
			$data['message']=array();
		}
		$this->load->view("sync",$data);

	}
	function sync(){
		$this->load->view("sync");
	}
	function upload_live_server($file_name){
		$pageWasRefreshed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';

		if(!$pageWasRefreshed){

			$ip = LIVE_SERVER_IP;
			exec("ping -n 1 $ip", $output, $status);

			if($status==0){

				$current_directory=getcwd();
				$filename=$current_directory."\database_backup\\".$file_name;
				/* Source File URL */
				$remote_file = LOCATION_CODE."_".$file_name;


				$file = $filename;
				$remote_file = $remote_file;

				// set up basic connection
				$conn_id = ftp_connect(LIVE_FTP_SERVER);

				// login with username and password
				$login_result = ftp_login($conn_id, LIVE_FTP_USER, LIVE_FTP_PASSWORD);

				// upload a file
				if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
					echo "successfully uploaded $file\n";
				} else {
					echo "There was a problem while uploading $file\n";
				}

				// close the connection
				ftp_close($conn_id);



				$filename = "debug.txt";
				$obj=fopen($filename, 'w');
				fwrite($obj, print_r("SHAWPON", TRUE));
				exit();









				////////////////////////////////////////////////////////////////////////////////////////////////
				include "ftp_class.php";

				$ftp = new ftp(TRUE);
				$ftp->Verbose = TRUE;
				//$ftp->LocalEcho = TRUE;

				if(!$ftp->SetServer(LIVE_FTP_SERVER)) {
					$ftp->quit();
					$data['message']= array('success'=>false,'message'=>"Setting server failed.");
					die("Setting server failed\n");
				}
				if (!$ftp->connect()) {
					$data['message']= array('success'=>false,'message'=>"Cannot connect.");
					die("Cannot connect\n");
				}



				if (!$ftp->login(LIVE_FTP_USER, LIVE_FTP_PASSWORD)) {
					$ftp->quit();
					$data['message']= array('success'=>false,'message'=>"Login failed.");
					die("Login failed\n");
				}

				if(!$ftp->SetType(FTP_AUTOASCII)){
					$data['message']= array('success'=>false,'message'=>"SetType FAILS.");
				}
				if(!$ftp->Passive(FALSE)){
					$data['message']= array('success'=>false,'message'=>"Passive FAILS.");
				}

				$ftp->chdir("apache");
				$ftp->cdup();

				$ftp->nlist("-la");

				$list=$ftp->rawlist(".", "-lA");
				if($list===false) {
					$data['message']= array('success'=>false,'message'=>"LIST FAILS.");
				}else {
					foreach($list as $k=>$v) {
						$list[$k]=$ftp->parselisting($v);
					}
				}

				/*
				if(FALSE !== $ftp->get($filename))
				echo $filename." has been downloaded.\n";
				else {
				$ftp->quit();
				die("Error!!\n");
				}
				*/
				$ftp->nlist("-la");

				if(FALSE !== $ftp->put($filename, $remote_file)){
					$data['message']= array('success'=>true,'message'=>$file_name." has been uploaded as ".$remote_file);

					$myfile = fopen($current_directory."\database_backup\uploadlogs.txt", "a") or die("Unable to open file!");
					fwrite($myfile, "\n". $file_name);
					fclose($myfile);

				}else {
					$ftp->quit();
					$data['message']= array('success'=>false,'message'=>"Error");
					die("Error!!\n");
				}
			}
		}
		$this->load->view("dbbackup",$data);

	}
}
?>