<?php 
#add 02/03/2017 23:08
ini_set('memory_limit', '-1');

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Backup extends CI_Controller {
	function index(){
		if($this->session->userdata('is_logged_in')==FALSE){
			redirect('login');
		}

		if($this->session->userdata('idgroup')>1){
			show_404();
			exit();
		}
		$data['params'] = $this->generateRandomString();
		$this->nativesession->set_flash_session('params', $data['params']);
		$data['page_title'] = 'BACKUP DATABASE';
		$data['main_body'] = 'sistem/backup';
		$this->load->model('sistem/backupmodel','backup');
		$data['backupList'] = $this->backup->getBackupList();
		$this->load->vars($data);
		$this->load->view('header');
		$this->load->view('body/body_new');
	}

	function generateRandomString($length = 20) {
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$charactersLength = strlen($characters);
		$randomString = '';
		for ($i = 0; $i < $length; $i++) {
			$randomString .= $characters[rand(0, $charactersLength - 1)];
		}
		return $randomString;
	}

	function dobackup(){
		if(empty($_POST)){
			show_404();
			exit();
		}
		if($this->session->userdata('is_logged_in')==FALSE){
			echo json_encode(array('st'=>0,'msg'=>'Please Refresh Your Browser'));
			return;
		}

		if($this->session->userdata('idgroup')>1){
			echo json_encode(array('st'=>0,'msg'=>'Execution Not Allowed'));
			return;
		}
		$params = $this->nativesession->get_flash_session('params');
		$inputParams = $this->input->post('params',TRUE);

		if($params!=$inputParams){
			echo json_encode(array('st'=>0,'msg'=>'Invalid Task'));
			return;
		}else{
			//ini_set('memory_limit', '128M');
			$this->load->dbutil();
			
			$prefs = array(
                'format'      => 'zip',
                'filename'    => 'backup_structure_data_db_'.date('Y-m-d').'.sql',
                'add_drop'    => TRUE,
                'add_insert'  => TRUE,
                'functions'   => TRUE,
				'procedures'  => TRUE,
				'views'  => TRUE,
                'newline'     => "\n"
              );
			$backup = $this->dbutil->backup($prefs);
			try {
				$direktori = 'resources/backup/db/';
				@mkdir($direktori,0750,true);
				#chmod($direktori, 0777);
				$jam = date('H:i:s');
				$jam = str_replace(':', '_', $jam);
				$filename = 'backup_structure_data_db_'.date('Y-m-d').'_jam_'.$jam;
				$filename = $filename.'.zip';
				write_file($direktori.$filename, $backup);
				#chmod($direktori, 0755);
				$this->load->model('sistem/backupmodel','backup');
				$data = array(
					'tanggal'	=> date('Y-m-d'),
					'jam'	=> date('H:i:s'),
					'filename'	=> $filename,
					'type'	=> 1,
					'location'	=> $direktori
					);
				$result = $this->backup->addDataBackup($data);
				//ini_set('memory_limit', '128M');
				echo json_encode(array('st'=>1,'msg'=>'Proses Backup Berhasil'));
				return;
			} catch (Exception $e) {
				echo json_encode(array('st'=>0,'msg'=>'Proses Backup Tidak Berhasil, Silahkan Ulangi Kembali'));
				return;
			}
		}
	}

	function doDownload($param){
		$id = $this->encrypt->decode(base64_decode($param));
		if(!is_numeric($id) OR intval($id)<1){
			show_404();
			exit();
		}
		$this->load->model('sistem/backupmodel','backup');
		$filename = $this->backup->getBackupData($id);
		$direktori = 'resources/backup/db/';
		$path = $direktori.$filename;
		$this->load->helper('download');
		$data = file_get_contents($path);
		force_download($filename, $data);
	}

	function doDelete(){
		$id = $this->encrypt->decode(base64_decode($this->input->post('params',TRUE)));
		if(!is_numeric($id) OR intval($id)<1){
			show_404();
			exit();
		}
		$this->load->model('sistem/backupmodel','backup');
		$filename = $this->backup->getBackupData($id);
		$direktori = 'resources/backup/db/';
		$path = $direktori.$filename;
		$del = $this->backup->deleteBackupData($id);
		if($del){
			@unlink($path);
			echo json_encode(array('st'=>1,'msg'=>'Data Backup Berhasil Dihapus'));
			return;
		}else{
			echo json_encode(array('st'=>0,'msg'=>'Data Backup Tidak Berhasil Dihapus'));
			return;
		}
		
	}

	function backupApp(){
		if($this->session->userdata('is_logged_in')==FALSE){
			redirect('login');
		}

		if($this->session->userdata('idgroup')>1){
			show_404();
			exit();
		}
		$this->load->library('zip');
		$path=FCPATH;
		$direktori = 'resources/backup/db/';
		$filename = 'App_backup_'.date('Y-m-d').'.zip';
		$backup = $this->zip->read_dir($path);
		$this->zip->download($filename);
	}
}