<?php

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

/* 	
 * 	Author 	: Wahyu
 * 	Tanggal : 01-09-2014	
 * 	Revisi 	: 
 */

class Sales_journal extends CI_Controller {

    // inisialisasi manual
    public $menu_id     = 393;
    public $menu_model  = '';
    public $name        = 'Sales Journal';
    public $trans_data  = array();
    // 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_sales_journal');
        $this->load->model('m_account_journal');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('convert_date');
        $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 {
                    $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);

                    //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('sales/sales_journal/v_sales_journal', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    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================= */
        $this->db->join('am_branch', 'at_salesjournal.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee as created_by', 'at_salesjournal.CreatedBy=created_by.EmployeeCode', 'LEFT');

        if ($BranchCode != "") {
            $this->db->where('at_salesjournal.BranchCode', $BranchCode);
        } else {
            $this->db->where('at_salesjournal.BranchCode', $this->session->userdata('branch'));
        }

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


        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('at_salesjournal.SJrnDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('at_salesjournal.SJrnDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }

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

        $count_data = $this->db->count_all_results('at_salesjournal');

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

        /* ========================end======================================= */
        $result = $this->m_sales_journal->get_all(1);

        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]->SJrnNumber,
                'SJrnDate'      => $result[$i]->SJrnDate,
                'SJrnAmount'    => $result[$i]->SJrnAmount,
                'SJrnDesc'      => $result[$i]->SJrnDesc,
                'TransStatus'   => $TransStatus,
                'CreatedBy'     => $result[$i]->Created
            );
        }

        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) {
        $data['company'] = $this->m_sales_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_sales_journal->get_all_to_print($this->session->userdata('branch'));

        $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['list']           = $this->m_sales_journal->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('sales/sales_journal/v_preview_sales_journal', $data);
        $this->load->view('v_footer');
    }
    public function to_preview_LAMA($data_grid = null) {
        $data['company'] = $this->m_sales_journal->get_company_by_branch($this->session->userdata('branch'));
        //$data['list'] 		= $this->m_sales_journal->get_all_to_print($this->session->userdata('branch'));

        $data_grid = str_replace('__', '/', $data_grid);
        $data_grid = str_replace('_', '-', $data_grid);
        $data_grid = str_replace('%20', ' ', $data_grid);
        $arr_grid_lv1 = explode('linebaru', $data_grid);

        $obj_string = '[';

        for ($x = 0; $x < count($arr_grid_lv1) - 1; $x++) {
            $arr_data_lv1 = $arr_grid_lv1[$x];
            $arr_grid_lv2 = explode('spasi', $arr_data_lv1);

            $obj_string .= '{';
            for ($i = 0; $i < count($arr_grid_lv2); $i++) {
                $arr_grid_lv3 = explode(':', $arr_grid_lv2[$i]);
                if ($i < count($arr_grid_lv2) - 1) {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '",';
                } else {
                    $obj_string .= '"' . $arr_grid_lv3[0] . '":"' . $arr_grid_lv3[1] . '"';
                }
            }

            if ($x < count($arr_grid_lv1) - 2) {
                $obj_string .= '},';
            } else {
                $obj_string .= '}';
            }
        }

        $obj_string .= ']';

        $data['list'] = json_decode($obj_string);

        $this->load->view('v_header');
        $this->load->view('sales/sales_journal/v_preview_sales_journal', $data);
        $this->load->view('v_footer');
    }

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

        $this->load->view('v_header');
        $this->load->view('sales/sales_journal/v_preview_sales_journal', $data);
        $this->load->view('v_footer');
    }

    // Function Index	
    public function add($no_piutang = null) {
        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)
                     */
                    $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);

                    $CompanyCode = $this->session->userdata('company');
                    $BranchCode = $this->session->userdata('branch');

                    if ($no_piutang != null) {
                        $no_piutang = str_replace($data['menu_link'] . '/add/', "", $this->uri->uri_string());
                        $data['no_piutang'] = $no_piutang;
                    } else {
                        $data['no_piutang'] = '';
                    }

                    $data['sales_journal'] = $this->m_sales_journal->create_sales_journal_number(date('d-m-Y'), 1);
                    $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('sales/sales_journal/v_new_sales_journal', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    public function get_loan_payment_number() {
        $preg_date = $this->input->post('loan_payment_date') == '' ? date('d-m-Y') : $this->input->post('loan_payment_date');

        $pay_karyawan_number = $this->m_sales_journal->create_loan_payment_number($preg_date);

//        print_r($data['sq_number1']);

        $result['status'] = true;
        $result['number'] = $pay_karyawan_number;
        echo json_encode($result);
    }

    public function get_bank_account($CurrencyCode = '') {

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

        $bank_account = $this->m_sales_journal->m_get_bank_account($branch, $CurrencyCode);

        echo $bank_account;
    }

    public function get_expense_account() {

        $branch = $this->session->userdata('branch');
        //$CurrencyCode 		= ($this->input->post('CurrencyCode')) ? $this->input->post('CurrencyCode'):'';

        $expense_account = $this->m_sales_journal->m_get_expense_account($branch);

        echo $expense_account;
    }

    public function get_all_account() {
        $branch = $this->session->userdata('branch');
        $all_account = $this->m_sales_journal->m_get_all_account($branch);
        echo $all_account;
    }

    public function get_akun_bank_edit($BranchCode) {
        $branch_explode = str_replace('_', '-', $BranchCode);
        $list_akun = $this->m_sales_journal->get_akun_bank_edit($branch_explode);
        echo $list_akun;
    }

    public function get_invoice() {
        $BranchCode     = $this->session->userdata('branch');
		$cust = $this->input->post('cust_code');
		
        $list_invoice   = $this->m_sales_journal->m_get_invoice($BranchCode,$cust);
        //echo $this->db->last_query();
        echo json_encode($list_invoice);
    }

    public function get_invoice_fiscal() {
        $BranchCode     = $this->session->userdata('branch');
		$cust = $this->input->post('cust_code');
		
        $list_invoice   = $this->m_sales_journal->m_get_invoice_fiscal($BranchCode,$cust);
        //echo $this->db->last_query();
        echo json_encode($list_invoice);
    }

    public function get_company_edit($branch) {
        $branch_explode = str_replace('_', '-', $branch);
        $list_company = $this->m_sales_journal->get_company_edit($branch_explode);
        echo "$list_company";
    }

    public function get_company() {
        $branch = $this->session->userdata('branch');
        $list_company = $this->m_sales_journal->get_company_edit($branch);
        echo "$list_company";
    }

    public function get_payment_periode($payment_num) {

        $uri4 = $this->uri->segment(4);
        $uri5 = $this->uri->segment(5);
        $uri6 = $this->uri->segment(6);
        $SinvNumber = $uri4 . "/" . $uri5 . "/" . $uri6;
        $payment_period = $this->uri->segment(7);
        $currency_payment = $this->uri->segment(8);

        $list_payment = $this->m_sales_journal->get_payment_periode($SinvNumber, $payment_period, $currency_payment);
        //echo $this->db->last_query();

        echo $list_payment;
    }

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

        $list_payment = $this->m_sales_journal->get_payment_periode_cancel($payment_before);

        echo "$list_payment";
    }

    public function get_history_payment($SJrnNumber,$CurrencyCode,$type_fiscal) {

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

        $SJrnNumber = str_replace('__', '/', $SJrnNumber);
        $SJrnNumber = str_replace('_', '-', $SJrnNumber);


        $result = $this->m_sales_journal->get_history_payment($SJrnNumber,$CurrencyCode,$type_fiscal);

        echo json_encode($result);
    }

   public function trans_rollback($modus, $AccounName, $Currency) {
        $this->db->trans_rollback();
        $result['status'] = false;

        if ($modus == 'approval') {
            $result['message'] = get_notification($modus, 0);
        } else {
            $result['message'] = get_notification_preference($modus, 0, $AccounName, $Currency);
        }

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

    public function insert_group($BranchCode, $txt_date, $SJrnNumber, $SinvNumber, $txt_desc, $txt_amount, $txt_rate, $currency_code,$customer_code,$type_fiscal){

        $data_payment = array(
            'BranchCode'        => $BranchCode,
            'SJrnDate'          => $txt_date,
            'SJrnNumber'        => $SJrnNumber,
            'InvoiceType'       => $type_fiscal,
            'SInvNumber'        => $SinvNumber,
            'SJrnDesc'          => $txt_desc,
            'TransStatus'       => 5,
            'SJrnAmount'        => $txt_amount,
            'CustomerCode'      => $customer_code,
            'CurrencyCode'      => $currency_code,
            'CurrencyRate'      => $txt_rate,
            'CreatedBy'         => $this->session->userdata('username'),
            'CreatedAt'         => date('Y-m-d H:i:s'),
            'LastUser'          => $this->session->userdata('username')
        );

        $this->trans_data['insert_group']['data'] = $data_payment;
    }

    public function insert_detail($detail, $SJrnNumber,$currency_code) {

        foreach ($detail as $row) {

            /* =============================== get account number ============================== */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $currency_code->CurrencyCode, '1');

            if($acc_number == false){
                $this->trans_rollback('journal', 'Gain Account', '');
            }

            $detail_data = array(
                'SJrnNumber'        => $SJrnNumber,
                'SJrnAccountNumber' => $acc_number->AccountNumber,
                'SJrnAmount'        => $row->PaymentAmount,
                'SJrnMemo'          => $row->Memo,
                'SJrnRate'          => $row->SJrnRate,
                'LastUser'          => $this->session->userdata('username')
            );

            $this->trans_data['insert_detail']['data'][] = $detail_data;
        }
    }

    public function insert_journal($detail, $txt_date, $SinvNumber, $SJrnNumber,$txt_amount,$txt_desc, $txt_rate, $inv_rate,$fiscal_rate, $currency_code,$type_fiscal,$owing_amount){

        $total_credit = 0;
        $total_debet  = 0;

        if($type_fiscal == 1){

            $sisa_owing      = $this->m_sales_journal->get_amount_owing($SinvNumber,'=');

            $SalesAccount    = $this->m_account_journal->get_account_name('Piutang PPn Fiscal');

            if($SalesAccount == false){
               $this->trans_rollback('journal', 'Sales Account', '');
            }

            $journal_credit = array(
                'SJJDate'               => $txt_date,
                'SJrnNumber'            => $SJrnNumber,
                'SJJAccountNumber'      => $SalesAccount->AccountNumber,
                'SJJDebet'              => 0,
                'SJJCredit'             => $owing_amount,
                'AmountCurrency'        => $owing_amount,
                'SJJRate'               => 1,
                'SJJDesc'               => $txt_desc,
                'SJJSignStatus'         => 1,
                'LastUser'              => $this->session->userdata('username')
            );

            $total_credit += $owing_amount;
            $this->trans_data['insert_journal']['data'][] = $journal_credit;

            /*========================================= Journal Payment ==================================*/
                foreach ($detail as $row){
                    /* =============================== get account number ============================== */
                    $curr_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
                    $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $curr_code->CurrencyCode, '1');

                    if($acc_number == false){
                        $this->trans_rollback('journal', 'Gain Account', '');
                    }

                    /* ================================ get type n sub type account ========================== */
                    $type_acc = $this->m_account_journal->m_get_account_type($acc_number->AccountNumber);

                    /* =============================== find plus in coa, credit or debet ======================== */
                    $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                    /*==================== Convert Payment ==================================*/
                    $PaymentAmount_Convert = $this->convert_payment($type_fiscal,$currency_code,$row->CurrencyCode,$row->PaymentAmount,$row->SJrnRate);

                    $journal_debet = array(
                        'SJJDate'               => $txt_date,
                        'SJrnNumber'            => $SJrnNumber,
                        'SJJAccountNumber'      => $acc_number->AccountNumber,
                        'SJJDebet'              => $PaymentAmount_Convert,
                        'SJJCredit'             => 0,
                        'AmountCurrency'        => $row->PaymentAmount,
                        'SJJRate'               => $row->SJrnRate,
                        'SJJDesc'               => $txt_desc,
                        'SJJSignStatus'         => $debet_credit == 'Debet' ? 0:1,
                        'LastUser'              => $this->session->userdata('username')
                    );

                    $total_debet += $PaymentAmount_Convert;
                    $this->trans_data['insert_journal']['data'][] = $journal_debet;
                }
            /*======================================= end JOurnal Payment ====================================*/

            /*============================== Beban Pembulatan ===========================================*/

                /*================ Khusus beban pembulatan gunakan owing langsung dari database ===========================*/
                //$sisa_beban = $sisa_owing - $total_debet;

                //if($sisa_beban != 0){

                    //$curr_code_beban        = $this->m_account_journal->get_currency_code('','Beban Pembulatan', '');
                    //$acc_number_beban       = $this->m_account_journal->get_account_name('Beban Pembulatan', $curr_code_beban->CurrencyCode, '1');

                    //if($acc_number_beban == false){
                        //$this->trans_rollback('journal', 'Beban Pembulatan', '');
                    //}

                    /* ================================ get type n sub type account ========================== */
                    //$type_acc_beban = $this->m_account_journal->m_get_account_type($acc_number_beban->AccountNumber);

                    /* =============================== find plus in coa, credit or debet ======================== */
                    //$debet_credit_beban = $this->m_account_journal->debet_kredit($type_acc_beban->Type_Name, $type_acc_beban->Sub_Type_Name);

                    // $journal_beban = array(
                    //     'SJJDate'               => $txt_date,
                    //     'SJrnNumber'            => $SJrnNumber,
                    //     'SJJAccountNumber'      => $acc_number_beban->AccountNumber,
                    //     'SJJDebet'              => $sisa_beban > 0 ? abs($sisa_beban):0,
                    //     'SJJCredit'             => $sisa_beban < 0 ? abs($sisa_beban):0,
                    //     'AmountCurrency'        => abs($sisa_beban),
                    //     'SJJDesc'               => $txt_desc,
                    //     'SJJSignStatus'         => $sisa_beban > 0 ? 0:1,
                    //     'LastUser'              => $this->session->userdata('username')
                    // );

                    //$this->trans_data['insert_journal']['data'][] = $journal_beban;
                //}
            /*=========================================== end Beban Pembulatan ===================================*/

        }else{

            $ItemCategory       = $this->m_sales_journal->get_item_category($SinvNumber,'!=');
            $sisa_owing         = $this->m_sales_journal->get_amount_owing($SinvNumber,'!=');

            /*================================== Journal Invoice =======================================*/
                foreach($ItemCategory as $row){
                
                    if($row->ItemType == 0){
                        $SalesAccount    = $this->m_account_journal->get_cat_sales_account('SRAccountReceivable', $row->ItemCategoryID, $currency_code);
                    }else if($row->ItemType == 1){
                        $SalesAccount    = $this->m_account_journal->get_sys_service_account('Unbilled ', $currency_code,$row->ItemCategoryID);
                    }else{
                         $SalesAccount   = $this->m_account_journal->get_sys_advance_account('Unbilled ', $currency_code,$row->ItemCategoryID);
                    }

                    $ratioAmount    = ($sisa_owing * $row->ItemCategoryRatio) / 100;
                    
                    if($SalesAccount == false){
                        $this->trans_rollback('journal', 'Sales Account', '');
                    }

                    $journal_credit = array(
                        'SJJDate'               => $txt_date,
                        'SJrnNumber'            => $SJrnNumber,
                        'SJJAccountNumber'      => $SalesAccount->AccountNumber,
                        'SJJDebet'              => 0,
                        'SJJCredit'             => $ratioAmount * $inv_rate,
                        'AmountCurrency'        => $ratioAmount,
                        'SJJRate'               => 1,
                        'SJJDesc'               => $txt_desc,
                        'SJJSignStatus'         => 1,
                        'LastUser'              => $this->session->userdata('username')
                    );

                    $total_credit += ($ratioAmount * $inv_rate);
                    $this->trans_data['insert_journal']['data'][] = $journal_credit;
                }
            /*================================== end JOurnal Invoice ===========================*/

            /*============================================== JOurnal  Payment ================================*/
                foreach ($detail as $row){
                    /* =============================== get account number ============================== */
                    $curr_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
                    $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $curr_code->CurrencyCode, '1');

                    if($acc_number == false){
                        $this->trans_rollback('journal', 'Gain Account', '');
                    }

                    /* ================================ get type n sub type account ========================== */
                    $type_acc = $this->m_account_journal->m_get_account_type($acc_number->AccountNumber);

                    /* =============================== find plus in coa, credit or debet ======================== */
                    $debet_credit = $this->m_account_journal->debet_kredit($type_acc->Type_Name, $type_acc->Sub_Type_Name);

                    /*==================== Convert Payment ==================================*/
                    $PaymentAmount_Convert = $this->convert_payment($type_fiscal,$currency_code,$row->CurrencyCode,$row->PaymentAmount,$row->SJrnRate);

                    $journal_debet = array(
                        'SJJDate'               => $txt_date,
                        'SJrnNumber'            => $SJrnNumber,
                        'SJJAccountNumber'      => $acc_number->AccountNumber,
                        'SJJDebet'              => $PaymentAmount_Convert,
                        'SJJCredit'             => 0,
                        'AmountCurrency'        => $row->PaymentAmount,
                        'SJJRate'               => $row->SJrnRate,
                        'SJJDesc'               => $txt_desc,
                        'SJJSignStatus'         => $debet_credit == 'Debet' ? 0:1,
                        'LastUser'              => $this->session->userdata('username')
                    );

                    $total_debet += $PaymentAmount_Convert;
                    $this->trans_data['insert_journal']['data'][] = $journal_debet;
                }
            /*============================================ end JOurnal Payment ===================================*/

            if (doubleval($total_debet) != doubleval($total_credit)) {

                /* =============== get account selisih kurs ============================ */
                $rate_account = $this->m_sales_journal->get_rate_account($currency_code);

                //$gap_amount = (doubleval($inv_rate) - doubleval($txt_rate)) * doubleval($txt_amount);
                $gap_amount = (doubleval($total_credit) - doubleval($total_debet));

                /* ====================== insert journal selisih kurs account =============== */
                $journal_bank = array(
                    'SJJDate'            => $txt_date,
                    'SJrnNumber'         => $SJrnNumber,
                    'SJJAccountNumber'   => $rate_account,
                    'SJJDebet'           => $gap_amount > 0 ? abs($gap_amount) : 0,
                    'SJJCredit'          => $gap_amount < 0 ? abs($gap_amount) : 0,
                    'AmountCurrency'     => 0,
                    'SJJRate'            => 1,
                    'SJJDesc'            => $txt_desc,
                    'SJJSignStatus'      => $gap_amount > 0 ? 0 : 1,
                    'LastUser'           => $this->session->userdata('username')
                );

                if($gap_amount > 0){
                   $total_debet += abs($gap_amount); 
                }else{
                    $total_credit += abs($gap_amount);
                }

                $this->trans_data['insert_journal']['data'][] = $journal_bank;
            }

            //$sisa_beban = $sisa_owing - $total_debet;


            //if($sisa_beban != 0){

                //$curr_code_beban        = $this->m_account_journal->get_currency_code('','Beban Pembulatan', '');
                //$acc_number_beban       = $this->m_account_journal->get_account_name('Beban Pembulatan', $curr_code_beban->CurrencyCode, '1');

                //if($acc_number_beban == false){
                    //$this->trans_rollback('journal', 'Beban Pembulatan', '');
                //}

                /* ================================ get type n sub type account ========================== */
                //$type_acc_beban = $this->m_account_journal->m_get_account_type($acc_number_beban->AccountNumber);

                /* =============================== find plus in coa, credit or debet ======================== */
                //$debet_credit_beban = $this->m_account_journal->debet_kredit($type_acc_beban->Type_Name, $type_acc_beban->Sub_Type_Name);

                // $journal_beban = array(
                //     'SJJDate'               => $txt_date,
                //     'SJrnNumber'            => $SJrnNumber,
                //     'SJJAccountNumber'      => $acc_number_beban->AccountNumber,
                //     'SJJDebet'              => $sisa_beban > 0 ? abs($sisa_beban):0,
                //     'SJJCredit'             => $sisa_beban < 0 ? abs($sisa_beban):0,
                //     'AmountCurrency'        => abs($sisa_beban),
                //     'SJJDesc'               => $txt_desc,
                //     'SJJSignStatus'         => $sisa_beban > 0 ? 0:1,
                //     'LastUser'              => $this->session->userdata('username')
                // );

                // $this->trans_data['insert_journal']['data'][] = $journal_beban;
            //}
        }

    }

    function convert_payment($type_fiscal,$CurrCustomerCode,$CurrAccountCode,$PaymentAmount,$Rate){
        if($CurrCustomerCode == 'IDR'){
            if($type_fiscal == 1){
                if($CurrAccountCode == 'IDR'){
                    return $PaymentAmount;
                }else{
                    return $PaymentAmount * $Rate;
                }
            }else{
               if($CurrAccountCode == 'IDR'){
                    return $PaymentAmount;
                }else{
                    return $PaymentAmount * $Rate;
                } 
            }
        }else{
            if($type_fiscal == 1){
                if($CurrAccountCode == 'IDR'){
                    return $PaymentAmount;
                }else{
                    return $PaymentAmount * $Rate;
                }
            }else{
               if($CurrAccountCode == 'IDR'){
                    return $PaymentAmount;
                }else{
                    return $PaymentAmount * $Rate;
                } 
            }
        }
    }

    public function insert() {

        $BranchCode = $this->session->userdata('branch');

        $SinvNumber = $this->input->post('txt_payment_for');
        $txt_date   = date("Y-m-d", strtotime($this->input->post('txt_payment_date')));

        /* =============================== create number payment karyawan ====================== */
        $SJrnNumber = $this->m_sales_journal->create_sales_journal_number($txt_date, 1);

        $txt_desc           = $this->input->post('txa_memo');
        $txt_amount         = $this->input->post('txt_amount');
        $owing_amount       = $this->input->post('owing_amount');
        $txt_amount         = $this->input->post('txt_amount');
        $txt_rate           = $this->input->post('txt_rate');
        $inv_rate           = $this->input->post('inv_rate');
        $fiscal_rate        = $this->input->post('fiscal_rate');
        $currency_code      = $this->input->post('currency_code');
        $type_fiscal        = $this->input->post('type_fiscal');
        $customer_code      = $this->input->post('customer_code');
        $detail             = $this->input->post('detail');
        $detail             = json_decode($detail);

        $get_customer_for_lock_status = $this->m_sales_journal->get_customer_for_lock_status($customer_code);

        if($get_customer_for_lock_status->LockStatus == 1){

            $result['status']    = false;
            $result['message']   = "Transaksi gagal, customer code sudah di lock silahkan proses transaksi dengan customer ".$get_customer_for_lock_status->CustomerName."";
            echo json_encode($result);

        }else{

            /* ===================== data update lock customer =========================== */
            $data_islock_status = array(
                'LockStatus' => 1
            );

            /* =================================== set lock customer ===================== */
            $this->trans_data['islock_status']['data']          = $data_islock_status;
            $this->trans_data['islock_status']['customer_code'] = $customer_code;

            /* =================================== set insert group ============================== */
            $this->insert_group($BranchCode, $txt_date, $SJrnNumber, $SinvNumber, $txt_desc, $txt_amount, $txt_rate, $currency_code,$customer_code,$type_fiscal);

            /* =================================== set insert detail ============================= */
            $this->insert_detail($detail, $SJrnNumber,$currency_code);

            /* =================================== set insert journal ============================ */
            $this->insert_journal($detail, $txt_date, $SinvNumber, $SJrnNumber,$txt_amount,$txt_desc, $txt_rate, $inv_rate,$fiscal_rate, $currency_code,$type_fiscal,$owing_amount);

            // print_r($this->trans_data);
            // die();
            $result_return = $this->m_sales_journal->insert_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $SJrnNumber);
            } else {
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $SJrnNumber);
            }

            echo json_encode($result);
        }
    }

    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)
                     */
                    $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
                    $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_sales_journal->get_detail($id);
					
					if($data['detail']->InvoiceType == 0){						
						if($data['detail']->CustomerCode == 'IDR'){
							$convert_amount = $data['detail']->SJrnAmount / $data['detail']->InvoiceCurrRate;
						}
						else{
							$convert_amount = $data['detail']->SJrnAmount * $data['detail']->InvoiceCurrRate;
						}
					}
					else{
						$convert_amount = $data['detail']->SJrnAmount;
					}
					
					$data['convert_amount'] = $convert_amount;
                    //echo $this->db->last_query();

                    $data['invoice_no'] = $this->m_sales_journal->get_invoice_no_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('sales/sales_journal/v_edit_sales_journal', $data);
                    $this->load->view('v_footer');
                    //----------------------end--------------------------------------------------------		
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }

    function update_group($BranchCode, $txt_date, $SJrnNumber, $SinvNumber, $txt_desc, $owing_amount, $txt_rate, $currency_code,$customer_code,$type_fiscal) {

        $data_group = array(
            'InvoiceType'       => $type_fiscal,
            'SJrnDesc'          => $txt_desc,
            'SJrnAmount'        => $owing_amount,
            'CurrencyCode'      => $currency_code,
            'CurrencyRate'      => $txt_rate,
            'CustomerCode'      => $customer_code,
            'LastUser'          => $this->session->userdata('username')
        );

        $this->trans_data['update_group']['data'] = $data_group;
        $this->trans_data['update_group']['TransNumber'] = $SJrnNumber;
    }

    function update_detail($detail, $SJrnNumber) {
        foreach ($detail as $row) {
            /* =============================== get account number ============================== */
            $currency_code = $this->m_account_journal->get_currency_code('', $row->GLAccount, '');
            $acc_number = $this->m_account_journal->get_account_name($row->GLAccount, $currency_code->CurrencyCode, '1');
            if($acc_number == false){
                $this->trans_rollback('journal', 'Gain Account', '');
            }


            $detail_data = array(
                'SJrnNumber'        => $SJrnNumber,
                'SJrnAccountNumber' => $acc_number->AccountNumber,
                'SJrnAmount'        => $row->PaymentAmount,
                'SJrnMemo'          => $row->Memo,
                'SJrnRate'          => $row->SJrnRate,
                'LastUser'          => $this->session->userdata('username')
            );

            $this->trans_data['update_detail']['data'][] = $detail_data;
            $this->trans_data['update_detail']['SJrnDetailID'][] = $row->SJrnDetailID;
        }
    }

    public function update() {

        $BranchCode             = $this->session->userdata('branch');

        $SinvNumber             = $this->input->post('txt_payment_for');
        $txt_date               = date("Y-m-d", strtotime($this->input->post('txt_payment_date')));

        /* =============================== create number payment karyawan ====================== */
        $SJrnNumber             = $this->input->post('SJrnNumber');

        $txt_desc               = $this->input->post('txa_memo');
        $type_fiscal            = $this->input->post('type_fiscal');
        $txt_amount             = $this->input->post('txt_amount');
        $owing_amount           = $this->input->post('owing_amount');
        $owing_amount_hidden    = $this->input->post('owing_amount_hidden');
        $txt_amount             = $this->input->post('txt_amount');
        $txt_rate               = $this->input->post('txt_rate');
        $inv_rate               = $this->input->post('inv_rate');
        $fiscal_rate            = $this->input->post('fiscal_rate');
        $currency_code          = $this->input->post('currency_code');
        $category_id            = $this->input->post('category_id');
        $customer_code          = $this->input->post('customer_code');
        $InvoicePaymentID       = $this->input->post('InvoicePaymentID');
        $detail                 = $this->input->post('detail');
        $detail                 = json_decode($detail);
        $detail_id              = $this->input->post('detail_id');
        $detail_id              = json_decode($detail_id);

        /* =================================== update group ================================= */
        $this->update_group($BranchCode, $txt_date, $SJrnNumber, $SinvNumber, $txt_desc, $owing_amount, $txt_rate, $currency_code,$customer_code,$type_fiscal);

        /* =================================== set delete detail ================================================ */
        $this->trans_data['delete_detail']['total'] = count($detail_id);

        if (count($detail_id) > 0) {
            foreach ($detail_id as $SJrnDetailID) {
                $this->trans_data['delete_detail']['SJrnDetailID'][] = $SJrnDetailID;
            }
        }

        /* =================================== set update detail ================================ */
        $this->update_detail($detail, $SJrnNumber);

        /* =================================== set delete journal ================================ */
        $this->trans_data['delete_journal']['TransNumber'] = $SJrnNumber;

        /* =================================== set insert journal ================================ */
        // $this->insert_journal($detail, $txt_date, $SinvNumber, $SJrnNumber,$txt_amount,$txt_desc, $txt_rate, $inv_rate,$fiscal_rate, $currency_code,$category_id,$owing_amount_hidden);
        $this->insert_journal($detail, $txt_date, $SinvNumber, $SJrnNumber,$txt_amount,$txt_desc, $txt_rate, $inv_rate,$fiscal_rate, $currency_code,$type_fiscal,$owing_amount);
        
        $result_return = $this->m_sales_journal->update_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'update', 1, $SJrnNumber);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'update', 0, $SJrnNumber);
        }

        echo json_encode($result);
    }

    function approved_dir() {
        $SJrnNumber         = $this->input->post('SJrnNumber');
        $SinvNumber         = $this->input->post('txt_payment_for');
        $txt_amount         = doubleval($this->input->post('txt_amount'));
        $customer_code      = $this->input->post('customer_code');
        $type_fiscal        = $this->input->post('type_fiscal');

        $data_approval = array(
            "TransStatus"       => 2,
            "AppFinished"       => 1,
            "AppLevel2Status"   => 1,
            "AppLevel2Code"     => $this->session->userdata('username'),
            "AppLevel2Date"     => date('Y-m-d'),
            "LastUser"          => $this->session->userdata('username')
        );

        /* =============== data update islock =========================================== */
        $data_islock_status = array(
            'LockStatus' => 0
        );

        /* ==============  data update piutang menjadi finish =========================== */
        $data_invoice_finished = array('TransStatus' => 2);

        $get_invoice    = $this->m_sales_journal->m_cek_all_invoice($SinvNumber);
        $total_invoice  = $get_invoice['TotalInvoice'];

        $total_owing    = doubleval($get_invoice['TotalOwing']);

        $sisa_invoice   = round(($total_owing - $txt_amount),2); 

        /*========== update sales invoice jika total invoice amount == total invoice owing ======================*/
        $this->trans_data['update_invoice']['total'] = 0; 
        if($sisa_invoice <= 0){
            $this->trans_data['update_invoice']['total']        = 1;
            $this->trans_data['update_invoice']['data']         = $data_invoice_finished;
            $this->trans_data['update_invoice']['TransNumber']  = $SinvNumber;
        }
        /*================= end update sales invoice ===========================================*/

         /* ============================= fungsi update islock customer =================================== */
        $this->trans_data['islock_status']['data']          = $data_islock_status;
        $this->trans_data['islock_status']['customer_code'] = $customer_code;
        /*============================== end end ned end end ================================*/

        /*===================== update owing invoice receipt =========================*/
        if($type_fiscal == 1){
            $ItemCategory    = $this->m_sales_journal->get_item_category($SinvNumber,'=');
           foreach($ItemCategory as $row){
                $this->trans_data['invoice_receipt']['owing'][]               = $txt_amount;
                $this->trans_data['invoice_receipt']['InvoicePaymentID'][]    = $row->InvoicePaymentID;    
            }
        }else{
            $ItemCategory    = $this->m_sales_journal->get_item_category($SinvNumber,'!=');
            foreach($ItemCategory as $row){
                $this->trans_data['invoice_receipt']['owing'][]               = ($row->ItemCategoryRatio * $txt_amount) / 100;
                $this->trans_data['invoice_receipt']['InvoicePaymentID'][]    = $row->InvoicePaymentID;    
            }
        }

        /* =============================Fungsi Update sales journal menjadi finished =================================== */
        $this->trans_data['approve_data']['data']           = $data_approval;
        $this->trans_data['approve_data']['TransNumber']    = $SJrnNumber;
        /*=============================== end end end end ===========================================*/

        $result_return = $this->m_sales_journal->approve_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'approve', 1, $SJrnNumber);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'approve', 0, $SJrnNumber);
        }

        echo json_encode($result);
    }

    public function reversed_data() {
        /* ===================================Deklarasi Variabel untuk proses insert atau update=================================== */
        $SJrnNumber = $this->input->post('id');

        $arr_no             = explode("/", $SJrnNumber);
        $no_transaction     = substr($arr_no[1], 0, 4);
        $month_transaction  = substr($no_transaction, 0, 2);
        $year_transaction   = ((int) substr($no_transaction, 2, 2)) + 2000;

        $date_transaction   = $year_transaction . $month_transaction;

        $data_reversed_journal = array(
            'AppLevel2Status'   => 0,
            'AppLevel2Code'     => null,
            'AppLevel2Date'     => 0,
            'TransStatus'       => 5,
            'AppFinished'       => 0,
        );

        $data_reversed_invoice = array(
            'TransStatus' => 1
        );

        /* =============== data update islock =========================================== */
        $data_islock_status = array(
            'LockStatus' => 1
        );

        /* ============================= get SinvNumber ============ */
        $data_journal       = $this->m_sales_journal->get_invoice_data($SJrnNumber);

        $SInvNumber         = $data_journal['SInvNumber'];
        $customer_code      = $data_journal['CustomerCode'];
        $SJrnAmount         = $data_journal['SJrnAmount'];
        $type_fiscal        = $data_journal['InvoiceType'];

        // $get_invoice    = $this->m_sales_journal->m_cek_all_invoice($SInvNumber);
        // $total_invoice  = $get_invoice['TotalInvoice'];
        // $total_owing    = $get_invoice['TotalOwing'];

        // $sisa_invoice   = round(($total_invoice - $total_owing),4); 

        /* ============================== check period end ============================= */
        $check_period = $this->m_sales_journal->check_period_end($date_transaction);

        if ($check_period == false) {

            /*========== update sales invoice jika total invoice amount == total invoice owing ======================*/
            // $this->trans_data['reverse_invoice']['total'] = 0; 
            // if($sisa_invoice <= 0){
            //     $this->trans_data['reverse_invoice']['total']        = 1;
            $this->trans_data['reverse_invoice']['data']         = $data_reversed_invoice;
            $this->trans_data['reverse_invoice']['TransNumber']  = $SInvNumber;
            // }
            /*================= end update sales invoice ===========================================*/

            /* ============================= set reverse payment =================================== */
            $this->trans_data['reverse_journal']['data']        = $data_reversed_journal;
            $this->trans_data['reverse_journal']['TransNumber'] = $SJrnNumber;

           /*===================== update owing invoice receipt =========================*/
            if($type_fiscal == 1){
                $ItemCategory    = $this->m_sales_journal->get_item_category($SInvNumber,'=');
                foreach($ItemCategory as $row){
                    $this->trans_data['invoice_receipt']['owing'][]                 = $SJrnAmount;
                    $this->trans_data['invoice_receipt']['InvoicePaymentID'][]      = $row->InvoicePaymentID;  
                }
                
            }else{
                $ItemCategory    = $this->m_sales_journal->get_item_category($SInvNumber,'!=');
                foreach($ItemCategory as $row){
                    $this->trans_data['invoice_receipt']['owing'][]               = ($row->ItemCategoryRatio * $SJrnAmount) / 100;
                    $this->trans_data['invoice_receipt']['InvoicePaymentID'][]    = $row->InvoicePaymentID;    
                }
            }

             /* ============================= fungsi update islock customer =================================== */
            $this->trans_data['islock_status']['data']          = $data_islock_status;
            $this->trans_data['islock_status']['customer_code'] = $customer_code;
            /*============================== end end ned end end ================================*/

            /* ============================= set delete reconcile =============================================== */
            $this->trans_data['delete_reconcile']['TransNumber'] = $SJrnNumber;

            $result_return = $this->m_sales_journal->reverse_transsaction($this->trans_data);

            $this->trans_data = [];

            if ($result_return) {
                $result['status'] = true;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $SJrnNumber);
            } else {
                $result['status'] = false;
                $result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $SJrnNumber);
            }

            echo json_encode($result);
        } else {

            $result['status'] = false;
            $result['message'] = get_notification('reverse_in_period', 0);
            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');
        $SJrnNumber = str_replace($data['menu_link'] . '/to_journal/', "", $this->uri->uri_string());
        $explode_branch = explode('/', $SJrnNumber);
        $branch_explode = $explode_branch[0];

        $data['date_journal'] = $this->m_sales_journal->get_date_journal_payment($SJrnNumber);
        $data['list_jurnal'] = $this->m_sales_journal->get_all_journal_payment($SJrnNumber, $branch_explode);
        //echo $this->db->last_query();

        $this->load->view('v_header');
        $this->load->view('sales/sales_journal/v_print_journal_sales_journal', $data);
        $this->load->view('v_footer');
    }

    public function suspend_data() {

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

        $SJrnNumber = str_replace(".", "/", $id);

        /* ========================== get piutang no ============================ */
        $data_journal   = $this->m_sales_journal->get_invoice_data($SJrnNumber);
        $SInvNumber     = $data_journal['SInvNumber'];
        $customer_code  = $data_journal['CustomerCode'];

        /* ============================= set data update payment ================= */
        $data = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata('username')
        );

       /* ===================== data update lock customer =========================== */
        $data_islock_status = array(
            'LockStatus' => 0
        );

        /* ========================== set update is lock piutang ===================== */
        $this->trans_data['islock_status']['customer_code'] = $customer_code;
        $this->trans_data['islock_status']['data']          = $data_islock_status;

        /* ========================== set update trans status ======================== */
        $this->trans_data['suspend_data']['data'] = $data;
        $this->trans_data['suspend_data']['TransNumber'] = $SJrnNumber;

        $result_return = $this->m_sales_journal->suspend_transsaction($this->trans_data);

        $this->trans_data = [];

        if ($result_return) {
            $result['status'] = true;
            $result['message'] = get_notification_transaksi($this->name, 'suspend', 1, $SJrnNumber);
        } else {
            $result['status'] = false;
            $result['message'] = get_notification_transaksi($this->name, 'suspend', 0, $SJrnNumber);
        }

        echo json_encode($result);
    }

    public 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);

        $BranchCode = $this->session->userdata('branch');

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

        if ($payment_no != "") {

            $data['detail'] = $this->m_sales_journal->get_detail_item_print($payment_no);
            $data['list'] = $this->m_sales_journal->get_detail_item_print_journal($payment_no, $BranchCode);

            $this->load->view('v_header');
            $this->load->view('sales/sales_journal/v_print_detail_sales_journal', $data);
            $this->load->view('v_footer');
        }
    }

    function get_bank_balance() {
        $AccountNumber = $this->input->post('AccountNumber');
        $branch = $this->session->userdata('branch');

        $bank_balance = $this->m_account_journal->m_get_bank_balance($branch, $AccountNumber);

        if ($bank_balance == false) {
            $return = array('message' => false, 'value' => 0);
        } else {
            $return = array('message' => true, 'value' => $bank_balance);
        }

        echo json_encode($return);
    }

    function get_gl_account($CurrencyCode) {
        $branch = $this->session->userdata('branch');
        $result = $this->m_sales_journal->m_get_gl_account($branch, $CurrencyCode);
		//echo $this->db->last_query();
        echo json_encode($result);
    }

}
