<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 05-08-2014	
 * 	Revisi 	: Fachri
 */

class Journal_voucher extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 96;
    public $menu_model = 'm_journalvoucher';
    public $name = "Journal Voucher";

    public function __construct() {
        parent::__construct();
        $this->load->model('m_journalvoucher');
        $this->load->model('m_account_journal');
        $this->load->model('m_menu');
		$this->load->model('custom/m_custom');
        $this->load->helper('convert_date');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

		}else{
			$username       = $this->session->userdata('username');
			$session_id     = $this->session->userdata('session_id');
			$this->m_login->delete_session($username,$session_id);
			$this->session->sess_destroy();

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }

    //Function Index
    public function index() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);

            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_model'] = $this->menu_model;

                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('general_ledger/v_journal_voucher', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function add() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $data['date_now'] = date('d-m-Y');

                    $this->load->view('v_header');
                    $this->load->view('general_ledger/v_new_journal_voucher', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function insert() {
        /*
          Dekalr variabel
         */
        $txt_voucher_date = $this->input->post('txt_voucher_date');

        /* =====================================jcos number========================================== */
        $txt_jv_no = $this->m_journalvoucher->create_jv_number($txt_voucher_date);
        /* ========================================================================================== */
        $sub_total_kredit = $this->input->post('sub_total_kredit');
        $sub_total_debet = $this->input->post('sub_total_debet');

        $txa_description = $this->input->post('txa_description');
        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
        /* ==================ENd==================================== */
        if (count($detail) > 0) {
            $this->db->trans_begin();

            $insert_group = $this->insert_group($txt_voucher_date, $txt_jv_no, $txa_description, $sub_total_kredit, $sub_total_debet);
            $insert_detail = $this->insert_detail($detail, $txt_voucher_date, $txt_jv_no, $txa_description);

            /* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $txt_jv_no);
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $txt_jv_no);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = "Journal Voucher gagal disimpan. Tidak ada item pada Journal Voucher.";

            echo json_encode($result);
            die();
        }
        echo json_encode($result);
    }

    function insert_group($txt_voucher_date, $txt_jv_no, $txa_description, $sub_total_kredit, $sub_total_debet) {
        $data_group = array(
            'BranchCode' => $this->session->userdata('branch'),
            'JVchDate' => date("Y-m-d", strtotime($txt_voucher_date)),
            'JVchNumber' => $txt_jv_no,
            'JVchDesc' => $txa_description,
            'JVchTotalDebet' => $sub_total_debet,
            'JVchTotalCredit' => $sub_total_kredit,
            'JVchType' => 1,
            'CreatedBy' => $this->session->userdata('username'),
            'CreatedAt' => date('Y-m-d'),
            'TransStatus' => 4,
            'LastUser' => $this->session->userdata('username')
        );
        $this->m_journalvoucher->insert($data_group);
    }

    function insert_detail($detail, $txt_voucher_date, $txt_jv_no, $txa_description) {
        foreach ($detail as $row) {

            $Debit_Currency = $row->Debit_Currency;
            $Credit_Currency = $row->Credit_Currency;
            $CurrencyRate = $row->Rate;
            $AccountNumber = $row->AccountNumber;
            $Memo = $row->Memo;

            $data_detail = array(
                'JVchNumber' => $txt_jv_no,
                'JVchAccount' => $row->AccountNumber,
                'JVchDebetSaldo' => $row->Debit,
                'JVchCreditSaldo' => $row->Credit,
                'JVchDetailMemo' => $row->Memo,
                'JVchRate' => $row->Rate,
                'CustomerCode' => $row->CustomerCode,
                'CurrencyCode' => $row->CurrencyCode,
                'VendorCode' => $row->VendorCode,
                'LastUser' => $this->session->userdata('username')
            );
            $this->m_journalvoucher->insert_detail($data_detail);

            /*
              Function Nature Credit/Debit
             */
            $nature_journal = $this->m_account_journal->debet_kredit($row->AccountType, $row->SubTypeName);
            if ($nature_journal == "Debet") {
                if ($Debit_Currency != 0) {
                    $sign_status = 0;
                    $value_debet_credit = $Debit_Currency / $CurrencyRate;
                } else if ($Credit_Currency != 0) {
                    $sign_status = 1;
                    $value_debet_credit = $Credit_Currency / $CurrencyRate;
                }
            } else {
                if ($Debit_Currency != 0) {
                    $sign_status = 1;
                    $value_debet_credit = $Debit_Currency / $CurrencyRate;
                } else if ($Credit_Currency != 0) {
                    $sign_status = 0;
                    $value_debet_credit = $Credit_Currency / $CurrencyRate;
                }
            }
            /* ======================End================================== */
            $this->insert_journal($Debit_Currency, $Credit_Currency, $AccountNumber, $txt_voucher_date, $txt_jv_no, $txa_description, $sign_status, $value_debet_credit);
        }
    }

    function insert_journal($Debit_Currency, $Credit_Currency, $AccountNumber, $txt_voucher_date, $txt_jv_no, $txa_description, $sign_status, $value_debet_credit) {
        $data_journal = array(
            'JVchDate' => date("Y-m-d", strtotime($txt_voucher_date)),
            'JVchNumber' => $txt_jv_no,
            'JVchDesc' => $txa_description,
            'JVchAccountNumber' => $AccountNumber,
            'JVchSaldoDebet' => $Debit_Currency,
            'JVchSaldoCredit' => $Credit_Currency,
            'JVchSignStatus' => $sign_status,
            'AmountCurrency' => $value_debet_credit,
            'LastUser' => $this->session->userdata('username')
        );

        $this->m_journalvoucher->insert_journal($data_journal);
    }

    public function edit() {
        if ($this->session->userdata("login") == TRUE) {
            $group_menu = $this->session->userdata('group_menu');
            /*
              untuk di index/list = get_menu_by_group,
              untuk di add = get_menu_by_group_add
              untuk di edit = get_menu_by_group_edit
             */
            $arr_group_id = $this->m_menu->get_menu_by_group_edit($group_menu, $this->menu_id);
            //--------------------------end-----------------------------------------------------------
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    /*
                      modul untuk akses add masing masing modul berebda
                      jangan lupa copy $data nya (jika dia bener langsung ke add)
                     */
                    $id = $this->uri->segment(4) . '/' . $this->uri->segment(5) . '/' . $this->uri->segment(6);

                    $group_menu = $this->session->userdata('group_menu');

                    $data['detail'] = $this->m_journalvoucher->get_detail_edit($id);

                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $this->load->view('v_header');
                    $this->load->view('general_ledger/v_edit_journal_voucher', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function update() {
        /*
          Dekalr variabel
         */
        $txt_voucher_date = $this->input->post('txt_voucher_date');

        /* =====================================jcos number========================================== */
        $txt_jv_no = $this->input->post('txt_jv_no');
        /* ========================================================================================== */
        $sub_total_kredit = $this->input->post('sub_total_kredit');
        $sub_total_debet = $this->input->post('sub_total_debet');

        $txa_description = $this->input->post('txa_description');
        $detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);

        $detail_id = $this->input->post('detail_id');

        $detail_id = json_decode($detail_id);
        /* ==================ENd==================================== */
        if (count($detail) > 0) {
            $this->db->trans_begin();

            $this->update_group($txt_voucher_date, $txt_jv_no, $txa_description, $sub_total_kredit, $sub_total_debet);
            $this->update_detail_grid($detail, $txt_voucher_date, $txt_jv_no, $txa_description);

            /* ===========================delete detail================================================================= */
            if (count($detail_id) > 0) {
                foreach ($detail_id as $JVchDetailID) {
                    $this->m_journalvoucher->delete_data_grid($JVchDetailID);
                }
            }
            /* =============================end========================================================================== */

            /* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, $txt_jv_no);
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, $txt_jv_no);
            }
            /* ==================================end====================================================== */
        } else {
            $result['status'] = false;
            $result['message'] = "Journal Voucher gagal disimpan. Tidak ada item pada Journal Voucher.";

            echo json_encode($result);
            die();
        }
        echo json_encode($result);
    }

    function update_group($txt_voucher_date, $txt_jv_no, $txa_description, $sub_total_kredit, $sub_total_debet) {

        $data_group = array(
            'JVchDesc' => $txa_description,
            'JVchTotalDebet' => $sub_total_debet,
            'JVchTotalCredit' => $sub_total_kredit,
            'JVchType' => 1,
            'LastUser' => $this->session->userdata('username')
        );

        $this->m_journalvoucher->update($data_group, $txt_jv_no);
    }

    function update_detail_grid($detail, $txt_voucher_date, $txt_jv_no, $txa_description) {
        $this->m_journalvoucher->delete_jurnal($txt_jv_no);

        foreach ($detail as $row) {
            $Debit_Currency = $row->Debit_Currency;
            $Credit_Currency = $row->Credit_Currency;
            $AccountNumber = $row->AccountNumber;
            $Memo = $row->Memo;
            $JVchDetailID = $row->JVchDetailID;
            $CurrencyRate = $row->Rate;

            $CustomerCode = $row->Customer == '' ? '' : $row->CustomerCode;
            $VendorCode = $row->Vendor == '' ? '' : $row->VendorCode;

            $data_detail = array(
                'JVchDebetSaldo' => $row->Debit,
                'JVchCreditSaldo' => $row->Credit,
                'JVchDetailMemo' => $row->Memo,
                'JVchRate' => $row->Rate,
                'CustomerCode' => $CustomerCode,
                'VendorCode' => $VendorCode,
                'LastUser' => $this->session->userdata('username')
            );

            $this->m_journalvoucher->update_detail($data_detail, $JVchDetailID);

            /*
              Function Nature Credit/Debit
             */
            $nature_journal = $this->m_account_journal->debet_kredit($row->AccountType, $row->SubTypeName);
            if ($nature_journal == "Debet") {
                if ($Debit_Currency != 0) {
                    $sign_status = 0;
                    $value_debet_credit = $Debit_Currency / $CurrencyRate;
                } else if ($Credit_Currency != 0) {
                    $sign_status = 1;
                    $value_debet_credit = $Credit_Currency / $CurrencyRate;
                }
            } else {
                if ($Debit_Currency != 0) {
                    $sign_status = 1;
                    $value_debet_credit = $Debit_Currency / $CurrencyRate;
                } else if ($Credit_Currency != 0) {
                    $sign_status = 0;
                    $value_debet_credit = $Credit_Currency / $CurrencyRate;
                }
            }
            /* ======================End================================== */
            $this->insert_journal($Debit_Currency, $Credit_Currency, $AccountNumber, $txt_voucher_date, $txt_jv_no, $txa_description, $sign_status, $value_debet_credit);
        }
    }

    public function suspend_data() {
        $this->db->trans_begin();

        /* ======================deklarr variabel========================== */
        $id = $this->input->post('id');
        /* =======================end====================================== */

        /* ===================change trans status from table group=============== */
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );
        /* ========================end========================================== */
        $this->db->trans_begin();

        $this->m_journalvoucher->suspend($data, $id);

        /* =============================trans roll back dan trans commit============================/ */
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('suspend', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('suspend', 1);
        }
        /* ==================================end====================================================== */

        echo json_encode($result);
    }
	
	function reverse_data_detail() {
		try{
			
			$JVchType 	 = $this->input->post('JVchType');
			$txt_jv_no 	 = $this->input->post('txt_jv_no');
			$detail_post = $this->input->post('detail');
            $detail 	 = json_decode($detail_post);
			$get_sorddetail_dp = $this->m_journalvoucher->check_dp_for_reverse_jv($txt_jv_no,'at_sorddetaildp','DPUsed','SOrdNumber');
			$get_porddetail_dp = $this->m_journalvoucher->check_dp_for_reverse_jv($txt_jv_no,'at_pordetaildp','DPUsed','POrdNumber');
			
			/*Check Periode End*/
			$date_transaction 	= check_end_periode($txt_jv_no);
			
			$get_end_periode = $this->m_custom->check_period_end_custom($date_transaction);
			if ($get_end_periode) {
                throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
            }
			
			if($JVchType == 0){
				throw new Exception(get_notification('reverse_in_period', 0)); //sudah di end periode atau belum
			}
			else if($JVchType == 2){
				throw new Exception("Transaksi tidak bisa di reverse karna transaksi ini adalah initial value silahkan hubungi IT Devlop"); //sudah di end periode atau belum
			}
			else{
				foreach($detail as $row_detail){
					$DPAccount_Sales  	= $this->m_account_journal->get_account_name('Uang Muka Penjualan', $row_detail->CurrencyCode);
					$DPAccount_Purchase  = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $row_detail->CurrencyCode);
					
					if($row_detail->AccountNumber == $DPAccount_Sales->AccountNumber){
						if($get_sorddetail_dp->DPUsed > 0){
							throw new Exception("Transaksi gagal di Reverse, karena Transaksi DP ini sudah terpakai di Sales Receipt");
						}
						else{
							 $this->trans_data['delete_dp_sales']['TransNumber'][] = $txt_jv_no;
						}
					} else if($row_detail->AccountNumber == $DPAccount_Purchase->AccountNumber){
						if($get_porddetail_dp->DPUsed > 0){
							throw new Exception("Transaksi gagal di Reverse, karena Transaksi DP ini sudah terpakai di Purchase Payment");
						}
						else{
							$this->trans_data['delete_dp_purchase']['TransNumber'][] = $txt_jv_no;
						}
					}
				}
				
				$data = array(
					'TransStatus' => 4,
					'AppFinished' => 0,
					'AppLevel2Status' => 0,
					'AppLevel2Code' => NULL,
					'AppLevel2Date' => NULL,
					'LastUser' => $this->session->userdata("username")
				);
				$this->trans_data['update_group']['data'] = $data;
				$this->trans_data['update_group']['TransNumber'] = $txt_jv_no;
				
				$result_approve = $this->m_journalvoucher->reverse_transsaction($this->trans_data);
				$this->trans_data = [];
	
				if ($result_approve) {
					$result['status'] = true;
					$result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_jv_no);
				} else {
					$result['status'] = false;
					$result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_jv_no);
				}
				/* ==================================end====================================================== */
				echo json_encode($result);
			}
		}
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
	}
	
    public function approval() {
        try{

			$txt_jv_no = $this->input->post('txt_jv_no');
			$txt_voucher_date = $this->input->post('txt_voucher_date');
			$detail_post = $this->input->post('detail');
			$detail 	 = json_decode($detail_post);
				
			foreach($detail as $row_detail){
				$DPAccount_Sales  	= $this->m_account_journal->get_account_name('Uang Muka Penjualan', $row_detail->CurrencyCode);
				$DPAccount_Purchase  = $this->m_account_journal->get_account_name('Uang Muka Pembelian', $row_detail->CurrencyCode);
				
				if($row_detail->AccountNumber == $DPAccount_Sales->AccountNumber){
					$data_so_detail_dp = array(
						'SOrdNumber' => $txt_jv_no,
						'CustomerCode' => strtoupper($row_detail->CustomerCode),
						'InvoiceNumber' => $txt_jv_no,
						'SRecNumber' => $txt_jv_no,
						'SOrdTotalDP' => $row_detail->Credit,
						'Owing' => 0,
						'PaymentAmount' => $row_detail->Credit,
						'PaymentDate' => date('Y-m-d'),
						'PaidStatus' => 0,
						'DPUsed' => 0,
						'CurrencyRate' => $row_detail->Rate,
						'SaldoDPBalance' => $row_detail->Credit,
						'DPUsedBook' => 0,
						'IsEdit' => 0,
						'SOrdStatus' => 1,
						'StatusDPFor' => 1,
						'JVoucherBalance' => 0,
						'LastUser' => $this->session->userdata('username')
					);
					$this->trans_data['insert_sord_detail_dp']['data'][] = $data_so_detail_dp;
					
				} else if($row_detail->AccountNumber == $DPAccount_Purchase->AccountNumber){
					$data_po_detail_dp = array(
						'POrdNumber' => $txt_jv_no,
						'VendorCode' => strtoupper($row_detail->VendorCode),
						'PPayNumber' => $txt_jv_no,
						'POrdTotalDP' => $row_detail->Debit,
						'Owing' => 0,
						'PaymentAmount' => $row_detail->Debit,
						'PaymentDate' => date('Y-m-d'),
						'PaymentBefore' => 0,
						'DPUsed' => 0,
						'CurrencyRate' => $row_detail->Rate,
						'SaldoDPBalance' => $row_detail->Debit,
						'DPUsedBook' => 0,
						'IsEdit' => 0,
						'SOrdStatus' => 1,
						'StatusDPFor' => 1,
						'JVoucherBalance' => 0,
						'LastUser' => $this->session->userdata('username')
					);
					
					$this->trans_data['insert_pord_detail_dp']['data'][] = $data_po_detail_dp;
				}
			}
			
			$data = array(
				'TransStatus' => 2,
				'AppFinished' => 1,
				'AppLevel2Status' => 1,
				'AppLevel2Code' => $this->session->userdata("username"),
				'AppLevel2Date' => date("Y-m-d"),
				'LastUser' => $this->session->userdata("username")
			);
			$this->trans_data['update_group']['data'] = $data;
			$this->trans_data['update_group']['TransNumber'] = $txt_jv_no;
			
			$result_app = $this->m_journalvoucher->approved_transaction($this->trans_data);
			$this->trans_data 	= [];
			
			if ($result_app == 0) {
				$result['status'] 	= FALSE;
				$result['message']  = get_notification('approval', 0);
			}
			else {
				$result['status'] 	= TRUE;
				$result['message']  = get_notification('approval', 1);
			}
			/* ==================================end====================================================== */
			echo json_encode($result);
		}
		
		catch (Exception $e) {
            $result['status'] = false;
            $result['message'] = $e->getMessage();
            echo json_encode($result);
        }
    }

    //Function Menampilkan Data Pada Data Grid View
    //function get data to grid
    public function ajax() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $hasil = array();
        /* ===========rows*page tidak boleh melebihi dari jumlah data======= */

        /* =================================post dari find di kiri==================================================== */
        $param = $this->input->post('param');
        $Number = isset($param['txt_IDNumber']) ? $param['txt_IDNumber'] : '';
        $Desc = isset($param['txt_Description']) ? $param['txt_Description'] : '';

        $DateFrom = isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
        $DateTo = isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';
        $TransStatus = isset($param['chk_TransStatus']) ? $param['chk_TransStatus'] : '';
        $BranchCode = isset($param['cmb_branch']) ? $param['cmb_branch'] : '';
        /* ============================================end============================================================ */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        if ($BranchCode != "") {
            $this->db->where('at_journalvoucher.BranchCode', $BranchCode);
        } else {
            $this->db->where('at_journalvoucher.BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('at_journalvoucher.JVchNumber', $Number);
        } //change
        if ($Desc != "") {
            $this->db->like('at_journalvoucher.JVchDesc', $Desc);
        } //change
        if ($TransStatus != '') {
            $this->db->where_in('at_journalvoucher.TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('at_journalvoucher.TransStatus', array(0, 1, 4, 5, 6, 7));
        }


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_journalvoucher.JVchDate >=', date("Y-m-d", strtotime($DateFrom))); //change
                $this->db->where('at_journalvoucher.JVchDate <=', date("Y-m-d", strtotime($DateTo))); //change
            }
        }
        /* ==========================end================================================================= */
        $this->db->join('am_employee', 'am_employee.EmployeeCode = at_journalvoucher.CreatedBy', 'INNER');
        $count_data = $this->db->count_all_results('at_journalvoucher'); //change

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_journalvoucher->get_all(); //change

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(
                'TransNumber' => $result[$i]->JVchNumber,
                'JVchDate' => $result[$i]->JVchDate,
                'JVchDesc' => $result[$i]->JVchDesc,
                'JournalVoucherAmout' => $result[$i]->JournalVoucherAmout,
                'TransStatus' => $TransStatus,
                'CreatedBy' => $result[$i]->CreatedBy
            );
        }

        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
    }

    public function to_preview($obj_string = null) {
        // set data
//        $result = $this->m_journalvoucher->get_all();

        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
        $data['company_code']   = $data_filter['cmb_company'];
        $data['branch_code']    = $data_filter['cmb_branch'];
        $result                 = $this->m_journalvoucher->get_all_to_print($data_filter);
        $hasil = [];
        foreach ($result as $row) {
            $id = $row->JVchNumber;
            $JVchDate = convert_to_dmy($row->JVchDate);
            $Amount = $this->m_journalvoucher->get_jvch_amount($id);

            $hasil[] = array(
                'JVchNumber' => $row->JVchNumber,
                'JVchDate' => $JVchDate,
                'JournalVoucherAmout' => $Amount,
                'JVchDesc' => $row->JVchDesc
            );
        }

        $data['list'] = $hasil;

        $this->load->view('v_header');
        $this->load->view('general_ledger/v_preview_journal_voucher', $data);
        $this->load->view('v_footer');
    }

    function to_preview_journal() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $id = str_replace($data['menu_link'] . '/to_preview_journal/', "", $this->uri->uri_string());

        $data['detail'] = $this->m_journalvoucher->get_detail($id);

        $data['list'] = $this->m_journalvoucher->get_journal_by_number($id);

        $this->load->view('v_header');
        $this->load->view('general_ledger/v_preview_journal_detail_voucher', $data);
        $this->load->view('v_footer');
    }

    public function to_print() {
        // set data
        $data['list'] = $this->m_piutang_karyawan->get_all();

        $this->load->view('v_header');
        $this->load->view('cash_and_bank/piutang_karyawan/v_preview_piutang_karyawan', $data);
        $this->load->view('v_footer');
    }

    function to_print_detail() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
        $companyCode = $this->session->userdata('company');

        $id = str_replace($data['menu_link'] . '/to_print_detail/', "", $this->uri->uri_string());

        if ($id != "") {
            $data['detail'] = $this->m_journalvoucher->get_detail_print($id);
            $data['list'] = $this->m_journalvoucher->get_detail_item_print($id);

            // echo $this->db->last_query();   
            $this->load->view('v_header');
            $this->load->view('list/general_ledger/v_print_detail_jv', $data);
            $this->load->view('v_footer');
        }
    }

    /* ============================pencarian dari job costing waktu pop up======================================= */

    function get_akun() {
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
        $hasil = array();

        /* =================================post dari find di atas pop up==================================================== */
        $param = $this->input->post('param');
        $AccountNumber = isset($param['txt_AccountNumber']) ? $param['txt_AccountNumber'] : '';
        $AccountName = isset($param['txt_AccountName']) ? $param['txt_AccountName'] : '';
        /* ============================================end============================================================ */

        /* ===========================count data tabel job costing================================== */
        $this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_compaccountgl.CompanyCode', $this->session->userdata('company'));
        $this->db->where_in('at_compaccountgl.TransStatus', array(2));
        $this->db->where('am_accountgl.AccountChild', 1);
        $this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));
        $this->db->where('am_accountsubtype.StatusSelected', 1);


        if ($AccountNumber != "") {
            $this->db->like('am_accountgl.AccountNumber', $AccountNumber);
        }
        if ($AccountName != "") {
            $this->db->like('am_accountgl.AccountName', $AccountName);
        }

        $this->db->join('am_accountsubtype', 'am_accountsubtype.AccountSubTypeID = am_accountgl.AccountSubTypeID', 'inner');
        $this->db->join('at_compaccountgl', 'at_compaccountgl.AccountNumber = am_accountgl.AccountNumber', 'inner');
        $count_data = $this->db->count_all_results('am_accountgl');
        /* ======================================end================================================ */

        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }

        /* ===============ambil data dari model jv============================ */
        $result = $this->m_journalvoucher->get_akun();
        /* ======================end================================= */

        for ($i = 0; $i <= ($rows - 1); $i++) {
            $hasil[] = array(
                'AccountNumber' => $result[$i]->AccountNumber,
                'AccountName' => $result[$i]->AccountName,
                'AccountTypeName' => $result[$i]->AccountTypeName,
                'AccountSubTypeID' => $result[$i]->AccountSubTypeID,
                'CurrencyCode' => $result[$i]->CurrencyCode,
                'CurrencyRate' => $result[$i]->CurrencyRate,
                'TypeName' => $result[$i]->TypeName
            );
        }
        /* ===================jika kondisi kosong dari array $hasil======================= */
        if (empty($hasil)) {
            $emptyVar = array();
            echo json_encode($emptyVar);
        } else {
            $result = array();
            $result['total'] = $count_data;
            $result['rows'] = $hasil;
            echo json_encode($result);
        }
        /* ==============================end=========================================== */
    }

    /* ====================================end============================================================================== */

    function vendor($currency) {
        $data = $this->m_journalvoucher->get_vendor($currency);
        echo json_encode($data);
    }

    function customer($currency) {
        $data = $this->m_journalvoucher->get_customer($currency);
        echo json_encode($data);
    }

    function get_jv_detail() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $id = str_replace($data['menu_link'] . '/get_jv_detail/', "", $this->uri->uri_string());

        if (!empty($id)) {
            echo json_encode($this->m_journalvoucher->get_journal_detail($id));
        } else {
            echo '[]';
        }
    }

}
