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

/*	
 *	Author 	: Wahyu
 *	Tanggal : 07-10-2014	
 *	Revisi 	: Fachri
 */ 

class Purchase_expense_cashbon extends CI_Controller {
	// inisialisasi manual
	public $menu_id = 234;	
	public $code = "Expense Cashbon Code";
	public $name = "Expense Cashbon";
	
	public function __construct() {
        parent::__construct();
		$this->load->model('m_menu');
		$this->load->model('custom/m_custom');
		$this->load->model('m_expense_cashbon');	
		$this->load->helper('message');
		$this->load->helper('convert_date');
		date_default_timezone_set('Asia/Jakarta');
	}	
	
	// Function Index	
	public function index() {
		// get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);		
		// set data
		$CompanyCode = $this->session->userdata('company');
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
		
		$department = $this->m_custom->get_department_by_name('EXIM');
		$data['department_code'] = $department[0]->DepartmentCode;
		
		$data['cachbon_number']      = $this->m_expense_cashbon->create_ebon_number(date('d-m-Y'));
		$data['pr_date']            = date('d-m-Y');
		// set for view
		$this->load->view('v_header');
		$this->load->view('expense_cashbon/v_purchase_expense_cashbon', $data);
		$this->load->view('v_footer');
	}
	
	public function get_department(){
	   $CompanyCode = $this->session->userdata('company');
	   $list_department =  $this->m_expense_cashbon->get_department($CompanyCode);
	  
	   echo"$list_department";
	}
	
	public function get_department_edit($departmen_code){
	   $replace_code = str_replace("_", "-", $departmen_code);
	   $explode_dep_code    = explode("-", $replace_code);
	   $var_Company_code = $explode_dep_code[0];
	   
	   $list_department =  $this->m_expense_cashbon->get_department_edit($var_Company_code, $replace_code);
	  
	   echo"$list_department";
	}
	
	public function get_employee($DepCode){
	   $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);		
       $depCode = str_replace($data['menu_link'].'/get_employee/',"",$this->uri->uri_string());
	   $employee =  $this->m_expense_cashbon->get_employee($depCode);
	   echo"$employee";
	}
	
	public function get_employee_edit($DepCode,$branchCode){
	   $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);		
       $depCode = str_replace('_', '-', $DepCode);
	   $branch_replace = str_replace('_', '-', $branchCode);
	   $employee =  $this->m_expense_cashbon->get_employee_edit($depCode, $branch_replace);
	   echo"$employee";
	}
	
	public function get_akun(){
		$CompanyCode = $this->session->userdata('company');
		$list_akun = $this->m_expense_cashbon->get_akun($CompanyCode);
		echo"$list_akun";
	}
	
	public function akun_cashbon(){
		$CompanyCode = $this->session->userdata('company');
		$list_akun_cashbon = $this->m_expense_cashbon->get_akun_cashbon($CompanyCode);
		echo $this->db->last_query();
		echo"$list_akun_cashbon";
	}
	
	/*Added by Hasan on 2015/03/23*/
	public function cashbon_account(){
		$company = $this->session->userdata('company');
		$list_akun_cashbon = $this->m_expense_cashbon->get_akun_cashbon($company);
		echo $list_akun_cashbon;
	}
	/*End of Added*/
	
	public function get_rate_currency(){
		$AccountNumber = $this->input->post('AccountNumber');
		$currency_rate = $this->m_expense_cashbon->get_currency_code($AccountNumber);
		echo"$currency_rate";
	}
	
	
	
	public function insert(){
	    //set post data
		$CompanyCode    = $this->session->userdata('company');
		$BranchCode 	= $this->session->userdata('branch');
		
		$DepartmentCode = $this->input->post('cmb_departement');
		$EmployeeCode 	= $this->input->post('cmb_employee');
		$EBonDate 		= date("Y-m-d", strtotime($this->input->post('txt_cashbon_date')));		                   
		$EBonNumber 	= $this->input->post('txt_exp_cashbon_no');
		$EBonDesc 		= $this->input->post('txa_description');
		$BankPayment 	= $this->input->post('cmb_bank');
		$CurrencyCode   = $this->input->post('currency_code');;
		$CurrencyRate   = $this->input->post('txt_rate');
		$ChequeNumber   = $this->input->post('txtcheque_no');
		$ChequeDate     = date("Y-m-d", strtotime($this->input->post('txt_cheque_date')));
		$ChequeAmount   = $this->input->post('txt_cheque_amount');
		$txt_amount   	= $this->input->post('txt_amount');
		$kategoriid   	= $this->input->post('kategoriid');
		$detail 		= json_decode($this->input->post('detail'));
		$total_amount   = $txt_amount * $CurrencyRate;
		
		
		$data_cashbon = array(
			'BranchCode' 		=> $BranchCode,
			'DepartmentCode' 	=> $DepartmentCode,
			'EmployeeCode' 		=> $EmployeeCode,
			'EBonDate' 			=> $EBonDate,
			'EBonNumber' 		=> $EBonNumber,
			'EBonDesc' 			=> $EBonDesc,
			'EBonAmount' 		=> $txt_amount,
			'BankPayment' 		=> $BankPayment,
			'CurrencyCode' 		=> $CurrencyCode,
			'CurrencyRate' 		=> $CurrencyRate,
			'ChequeNumber' 		=> $ChequeNumber,
			'ChequeDate' 		=> $ChequeDate,
			'ChequeAmount' 		=> $ChequeAmount,
			'EBonLockStatus' 	=> 1,
			'TransStatus' 		=> 4
		);
		$this->db->trans_begin();
		$result_insert = $this->m_expense_cashbon->insert_expense_cashbon($data_cashbon);
		if($result_insert == 0) {$this->trans_rollback('insert');}
		
		foreach($detail as $row){
			$ExpKategori	= $this->m_expense_cashbon->get_sys_expenses_akun($kategoriid);
			
			if($ExpKategori == false){
				$hasil = 0;
				$this->trans_rollback('journal');
			}
			else{
				$ebon_amount 	= $row->Amount;
				$ebon_Memo 		= $row->Memo;
				$akun_number 	=$ExpKategori->AccountNumber; 
				$detail_cashbon = array(
					'EBonNumber' 		=> $EBonNumber,
					'EBonAccountNumber' => $akun_number,
					'EBonAmount' 		=> $ebon_amount,
					'EbonAmountConvert' => $txt_amount,
					'EBonMemo' 			=> $ebon_Memo,
					'LastUser' 			=> $this->session->userdata('username')
				);
				$result_insert = $this->m_expense_cashbon->insert_detail_cashbon($detail_cashbon);
				if($result_insert == 0) {$this->trans_rollback('insert');}
			}
		}
		
		
		$data_journal_debit = array(
			'EBonDate' 				=> $EBonDate,
			'EBonNumber' 			=> $EBonNumber,
			'EBonAccountNumber'		=> $akun_number, 
			'EBonSaldoDebet' 		=> $total_amount,
			'EBonDesc' 				=> $ebon_Memo,
			'EBonSignStatus' 		=> 0,
			'AmountCurrency' 		=> $txt_amount,
			'LastUser' 				=> $this->session->userdata('username')
		);
		
		$result_insert = $this->m_expense_cashbon->insert_journal_expense_cashbon_debit($data_journal_debit);
		if($result_insert == 0) {$this->trans_rollback('insert');}
		
		$data_journal_credit = array(
			'EBonDate' 				=> $EBonDate,
			'EBonNumber' 			=> $EBonNumber,
			'EBonAccountNumber'		=> $BankPayment, 
			'EBonSaldoCredit' 		=> $total_amount,
			'EBonDesc' 				=> $ebon_Memo,
			'EBonSignStatus' 		=> 1,
			'AmountCurrency'		=> $txt_amount,
			'LastUser' 				=> $this->session->userdata('username')
		);
		
		$result_insert = $this->m_expense_cashbon->insert_journal_expense_cashbon_credit($data_journal_credit);
		if($result_insert == 0) {$this->trans_rollback('insert');}
		
		if($this->db->trans_status() == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification_transaksi('Expense Cashbon', 'insert', 0);
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = get_notification_transaksi('Expense Cashbon', 'insert', 1);
		}	

		echo json_encode($result);
	}
	
	public function edit(){
		// get link from tbl_menu 
		$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);		
		// set data
		$CompanyCode = $this->session->userdata('company');
		$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);

		// inisialisasi additional parameter
        $id = str_replace($data['menu_link'].'/edit/',"",$this->uri->uri_string());
		$data['detail'] = $this->m_expense_cashbon->get_detail($id);
		$data['amount_cashbon'] = $this->m_expense_cashbon->get_amount_cashbon($id);

		// set for view
		$this->load->view('v_header');
		$this->load->view('expense_cashbon/v_edit_expense_cashbon', $data);
		$this->load->view('v_footer');
	}
	
	public function ajax_detail_item($id){
	    $number = str_replace(".","/", $id);
		$replace_no = str_replace("_", "-", $number);
		$list_detail = $this->m_expense_cashbon->get_detail_item($replace_no);
		echo"$list_detail";
	}
	
	public function update(){
	    //set post data
		$CompanyCode    = $this->session->userdata('company');
		$BranchCode 	= $this->session->userdata('branch');	
		$DepartmentCode = $this->input->post('cmb_departement');
		$EmployeeCode 	= $this->input->post('cmb_employee');
		$EBonDate 		= date("Y-m-d", strtotime($this->input->post('txt_cashbon_date')));		                   
		$EBonNumber 	= $this->input->post('txt_exp_cashbon_no');
		$EBonDesc 		= $this->input->post('txa_description');
		$BankPayment 	= $this->input->post('cmb_bank');
		$bank_number 	= $this->input->post('bank_number');
		$CurrencyCode   = $this->input->post('currency_code');
		$CurrencyRate   = $this->input->post('txt_rate');
		$ChequeNumber   = $this->input->post('txtcheque_no');
		$ChequeDate     = date("Y-m-d", strtotime($this->input->post('txt_cheque_date')));
		$ChequeAmount   = $this->input->post('txt_cheque_amount');
		$txt_amount     = $this->input->post('txt_amount');
		$kategoriid   	= $this->input->post('kategoriid');
		$total_amount   = $txt_amount * $CurrencyRate;
		
		$data_cashbon = array(
			'BranchCode' => $BranchCode,
			'DepartmentCode' => $DepartmentCode,
			'EmployeeCode' => $EmployeeCode,
			'EBonDate' => $EBonDate,
			'EBonDesc' => $EBonDesc,
			'EBonAmount' => $txt_amount,
			'BankPayment' => $BankPayment,
			'CurrencyCode' => $CurrencyCode,
			'CurrencyRate' => $CurrencyRate,
			'ChequeNumber' => $ChequeNumber,
			'ChequeDate' => $ChequeDate,
			'ChequeAmount' => $ChequeAmount
		);
		$this->db->trans_begin();
		$result_update = $this->m_expense_cashbon->update_expense_cashbon($data_cashbon, $EBonNumber);
		if($result_update == 0) {$this->trans_rollback('update');}
		
		$detail_expense_cashbon=$this->input->post('detail_expense_cashbon');
		$detail_expense_cashbon=json_decode($detail_expense_cashbon);
		
		foreach($detail_expense_cashbon as $row){
			//$EBonAccountNumber 	= $row->EAccountNumber;
			$EBonMemo 		= $row->EBonMemo;
			$Amount 		= $row->EBonAmount;
			
			if($kategoriid != ""){
				$ExpKategori	= $this->m_expense_cashbon->get_sys_expenses_akun($kategoriid);
				$nomor_akun 	= $ExpKategori->AccountNumber;
				
				$detail_cashbon = array(
					'EBonAmount' => $Amount,
					'EBonMemo' => $EBonMemo,
					'EbonAmountConvert' => $txt_amount,
					'EBonAccountNumber' => $nomor_akun,
					'LastUser' => $this->session->userdata('username')
				);
				$result_update = $this->m_expense_cashbon->update_detail_cashbon($detail_cashbon, $EBonNumber);
				if($result_update == 0) {$this->trans_rollback('update');}
				
				if($ExpKategori == false){
					$hasil = 0;
					$this->trans_rollback('journal');
				}
				else{
					$data_journal_debit = array(
							'EBonDate' => $EBonDate,
							'EBonAccountNumber'	=> $nomor_akun, 
							'EBonSaldoDebet' => $total_amount,
							'EBonSaldoCredit' => 0,
							'AmountCurrency' => $txt_amount,
							'EBonDesc' => $EBonMemo,
							'LastUser' => $this->session->userdata('username')
						);
						
					$result_update = $this->m_expense_cashbon->update_journal_expense_cashbon_debit($data_journal_debit, $EBonNumber, 0);
					if($result_update == 0) {$this->trans_rollback('update');}
					
					$data_journal_credit = array(
						'EBonDate' 			=> $EBonDate,
						'EBonAccountNumber'	=> $BankPayment, 
						'EBonSaldoCredit' 	=> $total_amount,
						'EBonSaldoDebet' 	=> 0,
						'AmountCurrency' => $txt_amount,
						'EBonDesc' 			=> $EBonMemo,
						'LastUser' 			=> $this->session->userdata('username')
					);
					
					$result_update = $this->m_expense_cashbon->update_journal_expense_cashbon_credit($data_journal_credit, $EBonNumber, 1);
					if($result_update == 0) {$this->trans_rollback('update');}
				}
			}
			else{
				$detail_cashbon = array(
					'EBonAmount' => $Amount,
					'EBonMemo' => $EBonMemo,
					'EbonAmountConvert' => $txt_amount,
					//'EBonAccountNumber' => $nomor_akun,
					'LastUser' => $this->session->userdata('username')
				);
				$result_update = $this->m_expense_cashbon->update_detail_cashbon($detail_cashbon, $EBonNumber);
				if($result_update == 0) {$this->trans_rollback('update');}
				
				$data_journal_debit = array(
						'EBonDate' => $EBonDate,
						'EBonSaldoDebet' => $total_amount,
						'EBonSaldoCredit' => 0,
						'AmountCurrency' => $txt_amount,
						'EBonDesc' => $EBonMemo,
						'LastUser' => $this->session->userdata('username')
					);
					
				$result_update = $this->m_expense_cashbon->update_journal_expense_cashbon_debit($data_journal_debit, $EBonNumber, 0);
				if($result_update == 0) {$this->trans_rollback('update');}
				
				$data_journal_credit = array(
					'EBonDate' 			=> $EBonDate,
					'EBonSaldoCredit' 	=> $total_amount,
					'EBonSaldoDebet' 	=> 0,
					'AmountCurrency' => $txt_amount,
					'EBonDesc' 			=> $EBonMemo,
					'LastUser' 			=> $this->session->userdata('username')
				);
				
				$result_update = $this->m_expense_cashbon->update_journal_expense_cashbon_credit($data_journal_credit, $EBonNumber, 1);
				if($result_update == 0) {$this->trans_rollback('update');}
			}
			
			
			
			
			
			
					
			
		}
		
		
		
		if($this->db->trans_status() == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification_transaksi('Expense Cashbon', 'update', 0);
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = get_notification_transaksi('Expense Cashbon', 'update', 1);
		}	

		echo json_encode($result);
	}
	
	public function to_preview($EBonNumber){
	    $CompanyCode = $this->session->userdata('company');
		$replace_no = str_replace(".","/", $EBonNumber);  
		$cashbon_number = str_replace("_", "-", $replace_no);
		
		$cabon = $this->m_expense_cashbon->get_cash_bon_grup($cashbon_number);
		$cabon_branch = $cabon->BranchCode;
		$data['date_journal'] = $this->m_expense_cashbon->get_date_journal_cashbon($cashbon_number);
		$data['list_jurnal']  = $this->m_expense_cashbon->get_all_journal_cashbon($cashbon_number, $cabon->BranchCode);
		
		$this->load->view('v_header');
		$this->load->view('expense_cashbon/v_print_journal_expense_cashbon', $data);	
		$this->load->view('v_footer');	
	}
	
	public function to_print($EBonNumber){
		$id = str_replace(".","/", $EBonNumber);  
		
		$data['list_header'] = $this->m_expense_cashbon->get_detail_header($id);
		$data['detail_cashbon']  = $this->m_expense_cashbon->get_detail_cashbon($id);
		
		$this->load->view('v_header');
		$this->load->view('expense_cashbon/v_print_cashbon', $data);	
		$this->load->view('v_footer');	
	}
	
	public function suspend_data() {
		$id = $this->input->post('id');
        $result_insert = 0;
        $data = array(
                'TransStatus' 		=> 3,
                'LastUser'          => $this->session->userdata('username')
		);
		$this->db->trans_begin();
        $result_insert = $this->m_expense_cashbon->update_trans_status($id, $data);
		if($result_insert == 0){ $this->trans_rollback('suspend'); }
		
		if ($result_insert == 0) {
            $this->db->trans_rollback();
			$result['status'] 	= false;
            $result['message']	= get_notification('suspend',$result_insert);
        }
        else {
            $this->db->trans_commit();
            $result['status'] 	= true;
            $result['message']	= get_notification('suspend',$result_insert);
        }
        echo json_encode($result);
	}
	
	public function approval1() {
		if($this->session->userdata("jobtitle_status")== 0){
			$cashbon_number= $this->input->post('txt_exp_cashbon_no');	
			
            $cek_app_status_mgr = $this->m_expense_cashbon->cek_status_app_mgr($cashbon_number);
            if(!empty($cek_app_status_mgr)){
				$TransStatus = 1; 
			} else {
				$TransStatus = 4;
			}
			
			$data = array (		
				'AppLevel2Status' 		=> 1,
				'TransStatus'           => $TransStatus,
				'AppLevel2Code'         => $this->session->userdata("username"),
				'AppLevel2Date'			=> date("Y-m-d"),	
				'LastUser' 				=> $this->session->userdata("username")
			);
			
			// transaction begin
			$this->db->trans_begin();
			$this->m_expense_cashbon->approval_status($data,$cashbon_number);
			
			$app_finished = array('AppFinished' => 1);
			$cek_app = $this->m_expense_cashbon->cek_app($cashbon_number);
			
			if(!empty($cek_app)){
				$this->m_expense_cashbon->status_finished($app_finished, $cashbon_number);
			}
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] = false;
				$result['message'] = 'Approval Gaggal';
			}
			else {
				$this->db->trans_commit();
				$result['status'] = true;
				$result['message'] = 'Approval Berhasil';
			}		
			echo json_encode($result);
		}
	}
	
	public function approval2() {
		if($this->session->userdata("jobtitle_status")== 1){
			$cashbon_number= $this->input->post('txt_exp_cashbon_no');	
			
			/*$cek_app_status_dir = $this->m_expense_cashbon->cek_status_app_dir($cashbon_number);
            if(!empty($cek_app_status_dir)){
				$TransStatus = 1; 
			} else {
				$TransStatus = 5;
			}*/
			
			$data = array (		
				'AppLevel1Status' 		=> 1,
				'TransStatus'           => 1,
				'EBonLockStatus' 		=> 0,
				'AppLevel1Code'         => $this->session->userdata("username"),
				'AppLevel1Date'			=> date("Y-m-d"),	
				'LastUser' 				=> $this->session->userdata("username")
			);
			
			// transaction begin
			$this->db->trans_begin();
			$this->m_expense_cashbon->approval_status($data, $cashbon_number);
			
			$app_finished = array('AppFinished' => 1);
			$cek_app = $this->m_expense_cashbon->cek_app($cashbon_number);
			
			//if(!empty($cek_app)){
				$this->m_expense_cashbon->status_finished($app_finished, $cashbon_number);
			//}
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				$result['status'] = false;
				$result['message'] = 'Approval Gaggal';
			}
			else {
				$this->db->trans_commit();
				$result['status'] = true;
				$result['message'] = 'Approval Berhasil';
			}
			
			echo json_encode($result);
		}
	}
	
	public function trans_rollback($modus) {
        $this->db->trans_rollback();
        $result['status']   = false;

        if ($modus == 'journal') {
            $result['message']  = 'Pengaturan Preference Journal Template belum lengkap, silahkan atur ulang';
        }
        else {
            $result['message']  = get_notification_transaksi($this->name, $modus, 0);            
        }
		
		echo json_encode($result);
        die();
    }
	
	public function get_ebon_number(){
		$ebon_date  = $this->input->post('ebon_af_date') == '' ? date('d-m-Y') : $this->input->post('ebon_af_date');
		$ebon_no = $this->m_expense_cashbon->create_ebon_number($ebon_date);
        
		$result['status']   = true;
        $result['number']   = $ebon_no;
		
        echo json_encode($result);
	}
}