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

/*	
 *	Author 	: Wahyu
 *	Tanggal : 22-10-2014	
 *	Revisi 	: 
 */ 
 
 /*	
 *	Tanggal : 06-01-2015	
 *	Revisi 	: Fachri
 */ 

class Deposit extends CI_Controller {
	// inisialisasi manual
	public $menu_id = 190;
	
	// inisialisasi otomatis
	public $add = "add";
	public $edit = "edit";
	public $delete = "delete";
	public $to_preview = "to_preview";
	public $to_pdf = "to_pdf";
	public $to_excel = "to_excel";
	
	public function __construct() {
        parent::__construct();
		$this->load->model('m_menu');
		$this->load->model('m_deposit');
        $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() {
		$group_menu             = $this->session->userdata('group_menu');
		// get link from tbl_menu 
		$data['menu_link'] 		= $this->m_menu->get_menulink($this->menu_id);
		
		// set data
		$data['menu_label'] 	= $this->m_menu->get_menulabel($this->menu_id);		
		
		$data['dep_number']  	= $this->m_deposit->create_dep_number(date('d-m-Y'));
		$data['date_now'] 		= date('d-m-Y');
		
		//panggil model hak akses untuk autoriti
		$data['group_user'] 	= $this->m_menu->group_user_autority($this->menu_id, $group_menu);
		// set for view
		$this->load->view('v_header');
		$this->load->view('cash_bank/deposit/v_deposit', $data);
		$this->load->view('v_footer');
	}
	
	public function get_akun_bank_add($branch_code, $currency_idr, $currency_code){
	    $CompanyCode 	= $this->session->userdata('company');
		$str_replace_branch = str_replace('_','-', $branch_code);
		$list_bank 		= $this->m_deposit->get_coa_bank_add($CompanyCode, $str_replace_branch, $currency_idr, $currency_code);
		echo"$list_bank";
	}
	
	public function get_akun_bank($brach_code, $currency_idr, $currency_code){
		$replace_branch = str_replace('_','-',$brach_code);
		
	    $CompanyCode 	= $this->session->userdata('company');
		//$BranchCode 	= $this->session->userdata('branch');
		$list_bank 		= $this->m_deposit->get_coa_bank($replace_branch, $currency_idr, $currency_code);
		echo"$list_bank";
	}
	
	public function get_petty_cash_add(){
	    $CompanyCode = $this->session->userdata('company');
		$BranchCode 	= $this->session->userdata('branch');
		$list_petty_cash =  $this->m_deposit->get_petty_cash_add($CompanyCode, $BranchCode);
		echo"$list_petty_cash";
	}
	
	public function get_petty_cash($brach_code){
		$replace_branch = str_replace('_','-',$brach_code);
		
	    $CompanyCode = $this->session->userdata('company');
		//$BranchCode 	= $this->session->userdata('branch');
		$list_petty_cash =  $this->m_deposit->get_petty_cash($CompanyCode, $replace_branch);
		echo"$list_petty_cash";
	}
	
	public function get_dep_number() {
        $preg_date      = $this->input->post('Dep_date') == '' ? date('d-m-Y') : $this->input->post('Dep_date');
        $dep_number    = $this->m_deposit->create_dep_number($preg_date);
        
//        print_r($data['sq_number1']);
        
        $result['status']   = true;
        $result['number']   = $dep_number;
        echo json_encode($result);
    }
	
	public function proses_tutup(){
		$this->db->trans_rollback();
		die();
	}
	
	// Function Insert
	public function insert() {
        $BranchCode 	= $this->session->userdata('branch');
		
        $bulan 					= date('m');
		$tahun 					= date('y');
		$cek_tahun 				= date('Y');
		$kode 					= "CD";
		$result_insert 			= 0;
		
		
		$txt_deposit_date 	= date("Y-m-d", strtotime($this->input->post('txt_deposit_date')));	
		$cmb_bank_from 		= $this->input->post('cmb_bank_from');
		$cmb_bank 			= $this->input->post('cmb_bank');
		$txa_memo 			= $this->input->post('txa_memo');
		$txt_amount 		= $this->input->post('txt_amount');
		$txt_deposit_no 	= $this->input->post('txt_deposit_no');
		$currency_code 		= $this->input->post('currency_code');
		$currency_code_to 	= $this->input->post('currency_code_to');
		$txt_rate 			= $this->input->post('txt_rate');
		
		///perhitungan usd to usd, idr to idr, idr to usd, sud to idr
		if($currency_code == $currency_code_to){
			$total 			= $txt_amount * $txt_rate;
			
			$total_debet 	= $txt_amount;
			$total_credit 	= $txt_amount;
		}
		else {
			if($currency_code_to == "IDR"){
				$total 			= $txt_amount;
				$total_debet 	= $txt_amount;
				$total_credit 	= $txt_amount / $txt_rate;
			}
			else{
				$total 			= $txt_amount * $txt_rate;
				$total_debet 	= $txt_amount;
				$total_credit 	= $txt_amount * $txt_rate;
			}
		}
		//end////////////////////////////////////////////////
		
		$this->db->trans_begin();
		$data_deposit = array(
			'BranchCode' 		=> $BranchCode,
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'BankPayment' 		=> $cmb_bank_from,
			'BankReceipt' 		=> $cmb_bank,
			'CqTermStatus' 		=> NULL,
			'CDepDesc' 			=> $txa_memo,
			'CDepTotalAmount'	=> $txt_amount,
			'CurrencyCode' 		=> $currency_code,
			'CurrencyCode_to' 	=> $currency_code_to,
			'CurrencyRate' 		=> $txt_rate,
			'TransStatus' 		=> 4,
			'LastUser' 			=> $this->session->userdata('username')
		);
		$result_insert = $this->m_deposit->insert_deposit($data_deposit);
		if($result_insert == 0){ $this->proses_tutup(); }
		
		$journal_debet = array(
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'CDepAccountNumber' => $cmb_bank,
			'CDepSaldoDebet'  	=> $total,
			'CDepSaldoCredit'  	=> 0,
			'AmountCurrency' 	=> $total_debet,
			'CDepDesc'  		=> $txa_memo,
			'CDepSignStatus' 	=> 0,
			'LastUser' 			=> $this->session->userdata('username')
		);
		$result_insert = $this->m_deposit->insert_journal_debit_deposit($journal_debet);
		if($result_insert == 0){ $this->proses_tutup(); }
		
        $journal_credit = array(
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'CDepAccountNumber' => $cmb_bank_from,
			'CDepSaldoDebet'  	=> 0,
			'CDepSaldoCredit'  	=> $total,
			'AmountCurrency' 	=> $total_credit,
			'CDepDesc'  		=> $txa_memo,
			'CDepSignStatus' 	=> 1,
			'LastUser' 			=> $this->session->userdata('username')
		);
		$result_insert = $this->m_deposit->insert_journal_credit_deposit($journal_credit);
		if($result_insert == 0){ $this->proses_tutup(); }
		
		if($result_insert == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification('insert', $result_insert);
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = get_notification('insert', $result_insert);
		}	

		echo json_encode($result);
	}
	
	public function edit(){
		$group_menu             = $this->session->userdata('group_menu');
		// get link from tbl_menu 
		$data['menu_link'] 		= $this->m_menu->get_menulink($this->menu_id);
		$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_deposit->get_detail($id);
		
		//panggil model hak akses untuk autoriti
		$data['group_user'] 	= $this->m_menu->group_user_autority($this->menu_id, $group_menu);
		
		// set for view
		$this->load->view('v_header');
		$this->load->view('cash_bank/deposit/v_edit_deposit', $data);
		$this->load->view('v_footer');
	}
	
	// Function Update
	public function update() {
        $BranchCode 		= $this->session->userdata('branch');		
		$txt_deposit_no 	= $this->input->post('txt_deposit_no');
		$txt_deposit_date 	= date("Y-m-d", strtotime($this->input->post('txt_deposit_date')));	
		$cmb_bank_from 		= $this->input->post('cmb_bank_from');
		$cmb_bank 			= $this->input->post('cmb_bank');
		$txa_memo 			= $this->input->post('txa_memo');
		$txt_amount 		= $this->input->post('txt_amount');
		$chk_suspend 		= $this->input->post('chk_suspend');
		$txt_rate 			= $this->input->post('txt_rate');
		$currency_code_to 	= $this->input->post('currency_code_to');
		$currency_code 		= $this->input->post('currency_code');
		$result_update 		= 0;
		
		///perhitungan usd to usd, idr to idr, idr to usd, sud to idr
		if($currency_code == $currency_code_to){
			$total 			= $txt_amount * $txt_rate;
			
			$total_debet 	= $txt_amount;
			$total_credit 	= $txt_amount;
		}
		else {
			if($currency_code_to == "IDR"){
				$total 			= $txt_amount;
				$total_debet 	= $txt_amount;
				$total_credit 	= $txt_amount / $txt_rate;
			}
			else{
				$total 			= $txt_amount * $txt_rate;
				$total_debet 	= $txt_amount;
				$total_credit 	= $txt_amount * $txt_rate;
			}
		}
		//end////////////////////////////////////////////////
		
		$data_deposit = array(
			//'BranchCode' 		=> $BranchCode,
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'BankPayment' 		=> $cmb_bank_from,
			'BankReceipt' 		=> $cmb_bank,
			'CqTermStatus' 		=> NULL,
			'CDepDesc' 			=> $txa_memo,
			'CurrencyCode' 		=> $currency_code,
			'CurrencyCode_to' 	=> $currency_code_to,
			'CurrencyRate' 		=> $txt_rate,
			'TransStatus' 		=> 4,
			'CDepTotalAmount' 	=> $txt_amount,
			'LastUser' 			=> $this->session->userdata('username')
		);
		
		$this->db->trans_begin();
		$result_update = $this->m_deposit->update_deposit($data_deposit, $txt_deposit_no);
		if($result_update == 0){ $this->proses_tutup(); }
		
		$result_update = $this->m_deposit->delete_deposit($txt_deposit_no);
		if($result_update == 0){ $this->proses_tutup(); }
		
        $journal_debet = array(
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'CDepAccountNumber' => $cmb_bank,
			'CDepSaldoDebet'  	=> $total,
			'CDepSaldoCredit'  	=> 0,
			'AmountCurrency' 	=> $total_debet,
			'CDepDesc'  		=> $txa_memo,
			'CDepSignStatus' 	=> 0,
			'LastUser' 			=> $this->session->userdata('username')
		);
		$result_update = $this->m_deposit->insert_journal_debit_deposit($journal_debet);
		if($result_update == 0){ $this->proses_tutup(); }
		
        $journal_credit = array(
			'CDepDate' 			=> $txt_deposit_date,
			'CDepNumber' 		=> $txt_deposit_no,
			'CDepAccountNumber' => $cmb_bank_from,
			'CDepSaldoDebet'  	=> 0,
			'CDepSaldoCredit'  	=> $total,
			'AmountCurrency' 	=> $total_credit,
			'CDepDesc'  		=> $txa_memo,
			'CDepSignStatus' 	=> 1,
			'LastUser' 			=> $this->session->userdata('username')
		);
		$result_update = $this->m_deposit->insert_journal_credit_deposit($journal_credit);
		if($result_update == 0){ $this->proses_tutup(); }
		
		if($result_update == 0) {
			$this->db->trans_rollback();
			$result['status'] = false;
			$result['message'] = get_notification('update', $result_update);
		}
		else {
			$this->db->trans_commit();
			$result['status'] = true;
			$result['message'] = get_notification('update', $result_update);
		}
		
		echo json_encode($result);
	}
	
	public function suspend() {
		// inisialisasi additional parameter
        $deposit_number = $this->input->post('id');
		$id = str_replace(".","/", $deposit_number);
		$hasil 		= 0;
		
		$data = array (
			'TransStatus' => 3,
			'LastUser' => $this->session->userdata("username")
		);
		
		$this->db->trans_begin();
		$cek_status = $this->m_deposit->cek_trans_status($id);
		
		if($cek_status == 6 || $cek_status == 4){
			$hasil = $this->m_deposit->pembatalan_transaksi($id, $data);
			if($hasil == 0){ $this->proses_tutup(); }
			
			if ($hasil == 0) {
				$this->db->trans_rollback();
				$hasil = 0;
			}
			else {
				$this->db->trans_commit();
				$hasil = 1;
			}	
				
			if($hasil){	
				echo json_encode(array('status'=>true, 'message'=>'Deposit berhasil dbatalkan'));
			} else {
				echo json_encode(array('status'=>false, 'message'=>'Pembatalan Deposit Gagal'));
			}
		} else {
			echo json_encode(array('status'=>false, 'message'=>'Deposit sudah tidak bisa dbatalkan'));
		}
	}
	
	public function suspend_data() {
		$id = $this->input->post('id');
		$hasil 				= 0;
		
		$data = array(
			'TransStatus'	=> 3,
			'LastUser'		=> $this->session->userdata('username')
		);
		
		$this->db->trans_begin();
		$hasil = $this->m_deposit->suspend($data, $id);
		if($hasil == 0){ $this->proses_tutup(); }
		
		if ($hasil == 0) {
			$this->db->trans_rollback();
			$hasil = 0;
		}
		else {
			$this->db->trans_commit();
			$hasil = 1;
		}
		
		if($hasil == 1){
			$result['status']	= true;
			$result['message']	= get_notification('suspend',$hasil);
		}
		else{
			$result['status'] 	= false;
			$result['message']	= get_notification('suspend',$hasil);
		}
		echo json_encode($result);
	}
	
	public function to_journal($id){
	    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
		
	    $CompanyCode = $this->session->userdata('company');
		
		$BranchCode 	= $this->session->userdata('branch');	
        $deposit_number = str_replace($data['menu_link'].'/to_journal/',"",$this->uri->uri_string());		
		
		$data['date_journal'] = $this->m_deposit->get_date_journal_deposit($deposit_number);
		
		$ambil_dari_cashdeposit = $this->m_deposit->get_branch($deposit_number);
		$branch = $ambil_dari_cashdeposit->BranchCode;
		
		$data['list_jurnal']  = $this->m_deposit->get_all_journal_deposit($deposit_number, $branch);
		
		$this->load->view('v_header');
		$this->load->view('cash_bank/deposit/v_print_journal_deposit', $data);	
		$this->load->view('v_footer');	
	}
	
	public function to_print($CDepNumber){
		
		$id = str_replace(".","/", $CDepNumber);  
		
		$detail  = $this->m_deposit->get_detail($id);
		
		$data['BankPayment']     = $this->m_deposit->get_account_name_bank_payment($detail->BankPayment);
		$data['BankReceipt']     = $this->m_deposit->get_account_name_bank_receipt($detail->BankReceipt);
		$data['CDepNumber']      = $detail->CDepNumber;
        $data['CDepDate']        = $detail->CDepDate;
        $data['CDepDesc']        = $detail->CDepDesc;
        $data['CDepTotalAmount'] = $detail->CDepTotalAmount;
		$data['AppLevel1Code'] = $detail->AppLevel1Code;
		$data['AppLevel1Date'] = $detail->AppLevel1Date;
		
		
		
		$this->load->view('v_header');
		$this->load->view('cash_bank/deposit/v_print_deposit', $data);	
		$this->load->view('v_footer');	
	}
	
	public function approval1() {
		if($this->session->userdata("jobtitle_status")== 0){
			$deposit_number= $this->input->post('txt_deposit_no');	
			
			$cek_app_status_mgr = $this->m_deposit->cek_status_app_mgr($deposit_number);
            if(!empty($cek_app_status_mgr)){
				$TransStatus = 2; 
				$stat_appfinished = array(
					'AppFinished' 		=> 1
				);
				$result_insert = $this->m_payment->update_journal_appfinis($stat_appfinished, $deposit_number);
				//if($result_insert == 0){ $this->proses_tutup(); }
				
			} 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_deposit->approval_status($data,$deposit_number);
				
				$app_finished = array('AppFinished' => 1);
				$cek_app = $this->m_deposit->cek_app($deposit_number);
				
				if(!empty($cek_app)){
					$this->m_deposit->status_finished($app_finished, $deposit_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){
			$deposit_number= $this->input->post('txt_deposit_no');	
			
            /* $cek_app_status_dir = $this->m_deposit->cek_status_app_dir($deposit_number);
            if(!empty($cek_app_status_dir)){
				$TransStatus = 2; 
			} else {
				$TransStatus = 5;
			} */
			
			$data = array (		
				'AppLevel1Status' 		=> 1,
				'TransStatus'           => 2,
				'AppLevel1Code'         => $this->session->userdata("username"),
				'AppLevel1Date'			=> date("Y-m-d"),	
				'LastUser' 				=> $this->session->userdata("username")
			);
			// transaction begin
			$this->db->trans_begin();
				$this->m_deposit->approval_status($data,$deposit_number);
				
				$app_finished = array('AppFinished' => 1);
				$cek_app = $this->m_deposit->cek_app($deposit_number);
				
				if(!empty($cek_app)){
					$this->m_deposit->status_finished($app_finished, $deposit_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);
		}
	}

	//Dswan function untuk ubah status transaksi menjadi 3 (cancel)
	public function cancel_transaction() {
		$deposit_number= $this->input->post('txt_deposit_no');	
		
		$data = array (	
			'TransStatus'           => 3
		);

		$cancel_trans = $this->m_deposit->cancel_status($data,$deposit_number);
		//echo $this->db->last_query();
		if ($cancel_trans['affected'] < 1) {
			$result['status'] = false;
			$result['message'] = 'Transaksi gagal dibatalkan';
		}
		else {
			$result['status'] = true;
			$result['message'] = 'Transaksi berhasil dibatalkan';
		}		
		echo json_encode($result);
	}
}