<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class backupmodel extends CI_Model {

	function getBackupList(){
		try {
			return $this->db->get('sys_backup');
		} catch (Exception $e) {
			return '';
		}
	}

	function getBackupData($id){
		try {
			$this->db->where('id',$id);
			$result = $this->db->get('sys_backup');
			if($result->num_rows>0){
				return $result->row()->filename;
			}else{
				return '';
			}
		} catch (Exception $e) {
			return '';
		}
	}

	function deleteBackupData($id){
		try {
			$this->db->query("DELETE FROM sys_backup WHERE id =".$id);
			$title = "DELETE Data sys_backup <br />dengan id [id=".$id."]";
			$this->add_audittrail("DELETE",$title,'DATA DELETED','sys_backup');
			return TRUE;
		} catch (Exception $e) {
			return FALSE;
		}

	}

	function addDataBackup($data){
		try {
			$this->db->insert('sys_backup',$data);
			$title = "Backup Database <br /> Tanggal ".$data['tanggal']."";
			$descrip = $this->fetch_description($title,$data);
			$this->add_audittrail("INSERT",$title,$descrip,'sys_backup');
			return TRUE;
		} catch (Exception $e) {
			return FALSE;
		}
	}

	function fetch_description($title,$data){
		$descrip = '<br><table style="vertical-align:top" cellspacing="0" cellpadding="1" border="1">';
		$descrip .= '<tr><th>Nama Kolom</th><th>Nilai</th></tr>';
		foreach ($data as $key => $value) {
			$descrip .= '<tr>';
			$descrip .= '<td>'.$key.'</td>';
			$descrip .= '<td>'.$value.'</td>';
			$descrip .= '</tr>';
		}
		$descrip .= '</table>';
		return $descrip;
	}

	function add_audittrail($action,$title,$descrip){
		try {
			$data = array(
				'datetime' => date("Y-m-d H:i:s"),
				'ipaddress' => $this->input->ip_address(),
				'username' => $this->session->userdata('username'),
				'tablename' => 'sys_users',
				'formname' => 'Data User',
				'action' => $action,
				'title' => $title,
				'description' => $descrip
			);
			$this->db->insert('sys_audittrail', $data);
		} catch (Exception $e) {
			
		}
	}

	function update_data($datas){
		try {
			foreach ($datas as $data) {
				$this->db->where('id', $data['id']);
				$this->db->set($data['col_name'],$data['value']);
				$this->db->update('sys_config'); 
			}
			$title = "EDIT System Configuration";
			$descrip = $this->fetch_description($title,$datas);
			$this->add_audittrail("UPDATE",$title,$descrip);
			return TRUE;
		} catch (Exception $e) {
			return $e;
		}
	}
}