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

class Update_dl_ekstract extends CI_Controller {
	function __construct() {
        parent::__construct();
		$this->load->model('default/defaults', 'def');
		$this->source_path='';
		$hasil=$this->def->get_update_status();
		if(!empty($hasil)){
			if($hasil->num_rows()>0){
				$app_version = $this->session->userdata('app_version');
				if(!empty($app_version)){
					foreach ($hasil->result() as $key) {
						if(version_compare($app_version,  $key->patch_ver, '<')){
							$this->source_path=$key->source_path;
							break;
						}
					}
				}
			}
		}
	}
	
	function index(){
		if($this->session->userdata('is_logged_in')==FALSE){
			redirect('login');
		}
		if($this->session->userdata('idgroup')>1){
			$data['page_title'] = 'PAGE NOT FOUND';
			$data['main_body'] = 'update/extract_v_tri';
		}else{
			$data['page_title'] = 'UPDATE PATCH APLIKASI SIPP';
			$data['main_body'] = 'update/extract_v';
		}	

		$data['app_ver'] = $this->session->userdata('app_version');
		$data['source_path'] = $this->source_path;
		$this->load->vars($data);
		$this->load->view('header_min');
		$this->load->view('body/body_new'); 
	}

	function download(){
		if($this->source_path!=''){
			$PN_versions=$this->session->userdata('app_version');
		    $ver_updates='';
		    $getVersions = file_get_contents($this->source_path.'current-release-versions.php') or die ('ERROR');
		    if ($getVersions == ''){
				echo 'Checking versions gagal';
				return;
			}
			$extractPath= getcwd()."/";//use this for real
			//$extractPath= getcwd()."/TESTING/";//testing
		    $arr_versions=json_decode($getVersions, true);
			foreach ($arr_versions as $update_avail=>$arr_val) {
				if ($PN_versions<$update_avail){
					echo 'Installing Patch <strong>'.$update_avail.'</strong> <br>';
					$url = $this->source_path.$arr_val[0];
					$zipFile = ('resources/download/updates/update_sipp'.$arr_val[0]);// Local Zip File Path
					$file_check = $arr_val[1];
					$status = $this->donloat_file($url, $zipFile);
					if ($file_check===md5_file($zipFile)){
						$this->ekstrak2($zipFile, $extractPath);

						//update database disini
						$this->load->model('update/update_database');

					}else{
						echo 'Terjadi kesalahan saat mengunduh file update </br>'.$url;
						return;
					}
				}
			}
		}
	}

	function donloat_file($url, $zipFile){
		set_time_limit(0);
		file_put_contents( 'resources/download/progress.txt', '' );
		$this->nativesession->set('update_download_progress', 0);
		$zipResource = fopen($zipFile, "w");
		// Get The Zip File From Server
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_AUTOREFERER, true);
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_NOPROGRESS, false );
		curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array('Update_dl_ekstract', 'progressCallback' ) );
		curl_setopt($ch, CURLOPT_FILE, $zipResource);
		curl_setopt($ch, CURLOPT_TIMEOUT, 300);
		$page = curl_exec($ch);
		if(!$page) {
			echo "Error :- ".curl_error($ch);
			return;	
		};
		curl_close($ch);
		fclose($zipResource);
		return TRUE;
	}

	function progressCallback( $download_size, $downloaded_size, $upload_size, $uploaded_size ){
	    static $previousProgress = 0;
		if ( $download_size == 0 )
			$progress = 0;
		else
			$progress = round( $downloaded_size * 100 / $download_size );
		if ( $progress > $previousProgress){
			$previousProgress = $progress;
			$fp = fopen( 'resources/download/progress.txt', 'a' );
			fputs( $fp, "$progress\n" );
			fclose( $fp );
			
			$this->nativesession->set('update_download_progress', $progress);
			$this->nativesession->set('downloaded_size', $downloaded_size);
			$this->nativesession->set('download_size', $download_size);
	        session_write_close();
	        session_start();
		}
	}

	function ekstrak($zipFile, $extractPath=''){
		/* Open the Zip file */
		$zip = new ZipArchive;
		//$extractPath = ('resources/tmp/');
		if($zip->open($zipFile) != "true"){
		 	echo "Error :- Unable to open the Zip File";
			$zip->close(); 
			return;
		} 
		/* Extract Zip File */
		$zip->extractTo($extractPath);
		$zip->close();
		echo "Success:- Proses Ekstrak Berhasil";
	}

	function ekstrak2($zipFile,$extractPath=''){
		//Open The File And Do Stuff
		$zipHandle = zip_open($zipFile);
		if ($zipHandle){
			echo '<ul>';
			while ($aF = zip_read($zipHandle) ) {
				$thisFileName = zip_entry_name($aF);
				$thisFileDir = dirname($thisFileName);
				//Continue if its not a file
				echo '</br><li>Working on '.$thisFileName.'</li>';
				if ( substr($thisFileName,-1,1) == '/') continue;
								
				//Make the directory if we need to...
				if ( !is_dir ( $extractPath.$thisFileDir ) ){
					echo '<li>Creating Directory '.$extractPath.$thisFileDir.'</li>';
					@mkdir($extractPath.$thisFileDir,0750,true);
					echo '<li>Directory '.$extractPath.$thisFileDir.'........... <strong>CREATED</strong></li>';
				}else{
					echo '<li>Directory '.$extractPath.$thisFileDir.' already exist</li>';
				}
				
				//Overwrite the file
				if ( !is_dir($extractPath.$thisFileName) ) {
					echo '<li>File '.$extractPath.$thisFileName.'...........';
					$contents = zip_entry_read($aF, zip_entry_filesize($aF));
					$contents = str_replace("\r\n", "\n", $contents);
					$updateThis = '';
									
					//If we need to run commands, then do it.
					if ( $thisFileName == 'upgrade.php' ){
						$upgradeExec = fopen ('upgrade.php','w');
						fwrite($upgradeExec, $contents);
						fclose($upgradeExec);
						include ('upgrade.php');
						unlink('upgrade.php');
						echo' <strong>EXECUTED</strong></li>';
					}
					else
					{
						$updateThis = fopen($extractPath.$thisFileName, 'w');
						fwrite($updateThis, $contents);
						fclose($updateThis);
						unset($contents);
						echo' <strong>UPDATED</strong></li>';
					}
				}
			}
			echo '</ul>';
			$updated = true;
		}else{
			return;
		}
	}

}