<?php

class M_purchase_journal extends CI_Model {

    public $table           = "at_purchasejournal";
    public $detail          = "at_pjrndetail";
    public $journal         = "at_pjjournal";
    public $PInv            = "at_purchaseinvoice";
    public $InvPayment      = "at_invoicepayment";
    public $company         = "am_company";
    public $branch          = "am_branch";
    public $account         = "at_compaccountgl";
    public $am_account      = "am_accountgl";
    public $employee        = "am_employee";
    public $reconcile       = "at_bankreconcille";
    public $acc_type        = 'am_accounttype';
    public $sub_type        = "am_accountsubtype";
    public $period          = "at_periodend";
    public $department      = "am_department";
    public $vendor          = "am_vendor";


    function get_all($type) {
        /* =========================lemparan parah dari custom.js untuk searching_data_transaksi===================== */
        $param = $this->input->post('param');
        /* ====================================end=================================================================== */

        /* =================================post dari find di kiri==================================================== */
        $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============================================================ */

        /* ======================================scrol view 1-150======================================= */
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $beginning = ($page - 1) * $rows;
        $end = $page * $rows;
        /* ============================================================================================== */

        /* ==========================================by session======================================================= */
        $sess_company       = $this->session->userdata('company');
        $sess_branch        = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');
        /* =========================================================================================================== */

        $this->db->select('gr.PJrnDate, gr.PJrnNumber, br.BranchName, gr.PJrnAmount,
		                   gr.PJrnDesc, gr.TransStatus, em.EmployeeName as Created');
        $this->db->from($this->table.' as gr');
        $this->db->join($this->branch.' as br', 'gr.BranchCode=br.BranchCode', 'INNER');
        $this->db->join($this->employee.' as em', 'gr.CreatedBy=em.EmployeeCode', 'LEFT');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('gr.PJrnNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('gr.PJrnDesc', $Desc);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('gr.BranchCode', $BranchCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi by company-------------------------------------//
            /*
              branch status 0 = HO
              branch status 1 = depo/branch
              jangan lupa sesion data di atas untuk setiap kondisi
              jangan lupa tambahin case when trans status
             */
            $this->db->where('gr.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

        /* =====================================================find by date================================================== */
        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('gr.PJrnDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('gr.PJrnDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ======================================================end=========================================================== */

        /* =====================================================find by status================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('gr.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('gr.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }

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

        /* ==============================================sort tabel asc========================================================== */
        $this->db->order_by('gr.TransStatus', 'ASC');
        $this->db->order_by('gr.PJrnNumber', 'ASC');
        /* ===============================end================================================================================= */
        $query = $this->db->limit($end, $beginning);
        $query = $this->db->get();
        return $query->result();
    }

    function count_payment_number($bulan, $cek_tahun, $BranchCode) {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where('MONTH(LPDate)', $bulan);
        $this->db->where('YEAR(LPDate)', $cek_tahun);
        $this->db->where('BranchCode', $BranchCode);
        return $this->db->get()->num_rows();
    }

    function get_company_edit($branch_explode) {
        //$jobtitle = $this->session->userdata("jobtitle");
        $this->db->select('*');
        $this->db->from('am_branch');

        //$this->db->where('CompanyCode', $CompanyCode);
        $this->db->where('BranchCode', $branch_explode);

        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function get_last_payment_number($BranchCode) {
        $qty = "SELECT MAX(LPNumber) as LPNumber FROM at_loanpayment WHERE BranchCode='$BranchCode'";
        return $this->db->query($qty)->result();
    }

    /* ======================penomeran transaksi new======================================================= */

    function check_code_exist_1($PJrnNumber) {
        $query = $this->db->get_where($this->table, array('PJrnNumber' => $PJrnNumber), 1, 0);

        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function create_purchase_journal_number($date) {
        $branch = $this->session->userdata('branch');

        if ($date != '') {
            $month = date('m', strtotime($date));
            $year = date('y', strtotime($date));
        } else {
            $month = date('m');
            $year = date('y');
        }


        $pa_number = $branch . "/" . $month . $year . "PJ/";

        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(PJrnNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(PJrnNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('PJrnNumber', $pa_number);
        $query = $this->db->get($this->table);
        $this->db->_protect_identifiers = true;

        $num = $query->row()->New_Number;
        $long = strlen($num);

        if ($long == 1) {
            $number = '00' . $num;
        } elseif ($long == 2) {
            $number = '0' . $num;
        } else {
            $number = $num;
        }

        $pa_new_number = $pa_number . $number;

        while ($this->check_code_exist_1($pa_new_number)) {
            $num++;
            $long = strlen($num);

            if ($long == 1) {
                $number = '00' . $num;
            } elseif ($long == 2) {
                $number = '0' . $num;
            } else {
                $number = $num;
            }

            $pa_new_number = $pa_number . $number;
        }

        return $pa_new_number;
    }

    //custom data
    function get_company($CompanyCode) {
        $this->db->select('*');
        $this->db->from($this->company);
        //$this->db->where('CompanyCode', $CompanyCode);
        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function get_akun_bank($ComCode) {
        $this->db->select('ac.AccountNumber,ag.AccountName,ag.CurrencyCode');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ac.AccountNumber=ag.AccountNumber', 'inner');
        $this->db->join($this->branch . ' as br', 'ac.BranchCode=br.BranchCode', 'INNER');
        $this->db->join($this->sub_type . ' as sub', 'ag.AccountSubTypeID=sub.AccountSubTypeID', 'inner');
        $this->db->where_in('sub.AccountTypeName', array('Bank'));
        $this->db->where('ac.BranchCode', $ComCode);
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ag.CurrencyCode', 'IDR');
        $this->db->where('ac.TransStatus', 2);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('br.BranchStatus', 0);
        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function update_is_lock($data_islock_status, $VendorCode) {
        $this->db->update($this->vendor, $data_islock_status, array('VendorCode' => $VendorCode));
    }

    function m_get_invoice($BranchCode, $vendor_code) {

        $this->db->select("gr.VendorCode,cs.VendorName,br.BranchName,gr.BranchCode,gr.InvoiceNumber,gr.InvoiceDate,gr.InvoiceCurrCode,gr.InvoiceCurrRate,gr.InvoiceFiscalRate,sum(gr.InvoiceAmount) as Invoice_Amount,sum(gr.InvoiceOwing) as Invoice_Owing,(CASE WHEN cs.LockStatus=1 THEN 'Locked' ELSE 'UnLock' end) as LockStatus,gr.InvoicePaymentID");
        $this->db->from($this->InvPayment . ' as gr');
        $this->db->join($this->branch . ' as br', 'br.BranchCode=gr.BranchCode','inner');
        $this->db->join($this->vendor.' as cs','cs.VendorCode=gr.VendorCode','inner');
        $this->db->where('round(gr.InvoiceOwing,2) >',0);
        $this->db->where('gr.ItemCategoryID !=',-3);
        $this->db->where('gr.BranchCode', $BranchCode);
		$this->db->where('gr.VendorCode', $vendor_code);
		$this->db->where('gr.InvoiceType', 0);
        $this->db->group_by('gr.InvoiceNumber');
        $this->db->order_by('gr.InvoiceDate','ASC');
        $query = $this->db->get();

        return $query->result();
    }

    function m_get_invoice_fiscal($BranchCode, $vendor_code) {

        $this->db->select("gr.VendorCode,cs.VendorName,br.BranchName,gr.BranchCode,gr.InvoiceNumber,gr.InvoiceDate,gr.InvoiceCurrCode,gr.InvoiceCurrRate,gr.InvoiceFiscalRate,sum(gr.InvoiceAmount) as Invoice_Amount,sum(gr.InvoiceOwing) as Invoice_Owing,(CASE WHEN cs.LockStatus=1 THEN 'Locked' ELSE 'UnLock' end) as LockStatus,gr.InvoicePaymentID");
        $this->db->from($this->InvPayment . ' as gr');
        $this->db->join($this->branch . ' as br', 'br.BranchCode=gr.BranchCode','inner');
        $this->db->join($this->vendor.' as cs','cs.VendorCode=gr.VendorCode','inner');
        $this->db->where('round(gr.InvoiceOwing,2) >',0);
        $this->db->where('gr.ItemCategoryID',-3);
		$this->db->where('gr.InvoiceType', 0);
        $this->db->where('gr.BranchCode', $BranchCode);
		$this->db->where('gr.VendorCode', $vendor_code);
        $this->db->group_by('gr.InvoiceNumber');
        $this->db->order_by('gr.InvoiceDate','ASC');
        $query = $this->db->get();

        return $query->result();
    }

    function get_item_category($InvoiceNumber,$opr){
        $this->db->select('ItemCategoryID,ItemCategoryRatio,InvoicePaymentID,ItemType');
        $this->db->from($this->InvPayment.' as gr');
        $this->db->where('gr.ItemCategoryID '.$opr,-3);
        $this->db->where('gr.InvoiceNumber',$InvoiceNumber);

        $query = $this->db->get()->result();
        return $query;
    }

    function get_akun_bank_edit($ComCode) {

        $this->db->select('ac.AccountNumber,ag.AccountName,ag.CurrencyCode');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ac.AccountNumber=ag.AccountNumber', 'inner');
        $this->db->join($this->branch . ' as br', 'ac.BranchCode=br.BranchCode', 'INNER');
        $this->db->join($this->sub_type . ' as sub', 'ag.AccountSubTypeID=sub.AccountSubTypeID', 'inner');
        $this->db->where_in('sub.AccountTypeName', array('Bank'));
        $this->db->where('ac.BranchCode', $ComCode);
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ag.CurrencyCode', 'IDR');
        $this->db->where('ac.TransStatus', 2);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('br.BranchStatus', 0);
        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function get_sisa_piutang($PInvNumber) {
        $this->db->select("sum(dt.PaymentPerPeriod) as total_payment,sum(dt.ExpenseAmount) as TotalExpense");
        $this->db->from($this->table_payment . ' as gr');
        $this->db->join($this->detail_payment . ' as dt', 'dt.LPNumber=gr.LPNumber', 'inner');
        $this->db->join($this->table_piutang . ' as hr', 'hr.PInvNumber=gr.PInvNumber', 'inner');
        $this->db->where('gr.PInvNumber', $PInvNumber);
        $this->db->where('gr.TransStatus !=', 3);
        $query = $this->db->get();
        return $query->row();
    }

    function get_sisa_piutang_new($PInvNumber) {
        //$this->db->select("sum(dt.PaymentPerPeriod) as total_payment,sum(dt.ExpenseAmount) as TotalExpense");
        $this->db->select('dt.PaymentBalance');
        $this->db->from($this->table_payment . ' as gr');
        $this->db->join($this->detail_payment . ' as dt', 'dt.LPNumber=gr.LPNumber', 'inner');
        $this->db->join($this->table_piutang . ' as hr', 'hr.PInvNumber=gr.PInvNumber', 'inner');
        $this->db->where('gr.PInvNumber', $PInvNumber);
        $this->db->where_not_in('gr.TransStatus', array(3, 4, 5));
        $this->db->order_by('dt.LPDetailID', 'DESC');
        $this->db->limit(1);
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            $this->db->select("gr.LFAmount as PaymentBalance");
            $this->db->from($this->table_piutang . ' as gr');
            $this->db->where('gr.PInvNumber', $PInvNumber);
            $this->db->where('gr.TransStatus', 1);
            $query = $this->db->get();
            return $query->row();
        }
    }

    function get_payment_periode($PInvNumber, $payment_period, $payment_currency) {
        $this->db->select("dt.LPDetailID,ag.AccountName as ExpenseAccount,dt.ExpenseAmount as ExpenseAmount1,dt.LPNumber,dt.PaymentPeriod,
							dt.PaymentPerPeriod as PaymentPerPeriod1,dt.PaymentBalance,dt.LoanPayment,
							(CASE 
								WHEN gr.CurrencyCode='$payment_currency' THEN 
									(CASE WHEN hr.CurrencyCode='IDR' THEN (dt.ExpenseAmount / gr.CurrencyRate) ELSE (dt.ExpenseAmount * gr.CurrencyRate) END)
								ELSE
									'0' END) AS  ExpenseAmount2,
							(CASE 
								WHEN gr.CurrencyCode='$payment_currency' THEN
									(CASE WHEN hr.CurrencyCode='IDR' THEN (dt.PaymentPerPeriod / gr.CurrencyRate) ELSE (dt.PaymentPerPeriod * gr.CurrencyRate) END)
								ELSE
									'0' END) AS  PaymentPerPeriod2,
							(case when gr.TransStatus = 5 then 'Not Yet Paid'
                            when gr.TransStatus = 2 then 'Paid'
                            end) as Status
							");
        $this->db->from($this->detail . ' as dt');
        $this->db->join($this->table . ' as gr', 'gr.LPNumber=dt.LPNumber');
        $this->db->join($this->table_piutang . ' as hr', 'hr.PInvNumber=gr.PInvNumber', 'INNER');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=dt.ExpenseAccount', 'LEFT');
        $this->db->where('gr.PInvNumber', $PInvNumber);
        $this->db->where('dt.PaymentPeriod <=', $payment_period);
        $this->db->where('gr.TransStatus !=', 3);
        $this->db->order_by('dt.PaymentPeriod', 'ASC');
        $query = $this->db->get();
        $result = $query->result();
        return json_encode($result);
    }

    function get_payment_periode_cancel($PInvNumber) {
        $this->db->select("*,
							(case when at_loanpayment.TransStatus = 5 then 'Not Yet Paid'
                            when at_loanpayment.TransStatus = 2 then 'Paid'
                            end) as Status
							");
        $this->db->from($this->detail);
        $this->db->join('at_loanpayment', 'at_loanpayment.LPNumber=at_lpdetail.LPNumber');
        $this->db->where('at_loanpayment.PInvNumber', $PInvNumber);
        $this->db->where('at_loanpayment.TransStatus !=', 3);
        $query = $this->db->get();
        $result = $query->result();
        return json_encode($result);
    }

    function get_no_payment_before($piutang_no) {
        $this->db->select('LPNumber');
        $this->db->from($this->table);
        $this->db->where('PInvNumber', $piutang_no);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $LPNumber = $row->LPNumber;
            }

            return $LPNumber;
        } else {
            return FALSE;
        }
    }

    // end custom

    function get_coa_piutang_karyawan($branch_code) {
        $this->db->select('at_compaccountgl.AccountNumber');
        $this->db->from('at_compaccountgl');
        $this->db->join('am_accountgl', 'at_compaccountgl.AccountNumber=am_accountgl.AccountNumber');

        $this->db->where('at_compaccountgl.CompanyCode', $company);
        $this->db->where('at_compaccountgl.BranchCode', $branch_code);
        $this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));
        $this->db->where('am_accountgl.TransStatus', 2);
        $this->db->like('am_accountgl.AccountName', 'Piutang Karyawan');

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $AccountNumber = $row->AccountNumber;
            }

            return $AccountNumber;
        } else {
            return FALSE;
        }
    }

    function cek_payment_data($PInvNumber) {
        $this->db->select('PInvNumber');
        $this->db->from('at_loanpayment');
        $this->db->where('PInvNumber', $PInvNumber);
        $this->db->where('TransStatus !=', 3);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $PInvNumber = $row->PInvNumber;
            }

            return $PInvNumber;
        } else {
            return FALSE;
        }
    }

    function get_max_period($PInvNumber) {
        $this->db->select_max('PaymentPeriod');
        $this->db->from('at_lpdetail');
        $this->db->join('at_loanpayment', 'at_loanpayment.LPNumber = at_lpdetail.LPNumber');
        $this->db->where('at_loanpayment.PInvNumber', $PInvNumber);
        $this->db->where('at_loanpayment.TransStatus !=', 3);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $PaymentPeriod = $row->PaymentPeriod;
            }

            return $PaymentPeriod;
        } else {
            return 0;
        }
    }

    function get_payment_balance($PInvNumber) {
        $this->db->select_min('PaymentBalance');
        $this->db->from('at_lpdetail');
        $this->db->join('at_loanpayment', 'at_loanpayment.LPNumber = at_lpdetail.LPNumber');
        $this->db->where('at_loanpayment.PInvNumber', $PInvNumber);
        $this->db->where('at_loanpayment.TransStatus !=', 3);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $PaymentBalance = $row->PaymentBalance;
            }

            return $PaymentBalance;
        } else {
            return FALSE;
        }
    }

    function get_amount_owing($PInvNumber,$opr){
        $this->db->select('sum(gr.InvoiceOwing) as Invoice_Owing');
        $this->db->from($this->InvPayment.' as gr');
        $this->db->where('gr.ItemCategoryID '.$opr,-3);
        $this->db->where('gr.InvoiceNumber',$PInvNumber);

        $query = $this->db->get();
        if($query->num_rows()>0){
            $row = $query->row();

            return $row->Invoice_Owing;
        }else{
            return 0;
        }
    }

    function get_history_payment($PJrnNumber,$CurrCustCode,$type_fiscal) {

        $this->db->select('dt.PJrnAmount as PaymentAmount,ag.AccountName as GLAccount,ag.CurrencyCode,dt.PJrnRate,dt.PJrnDetailID,dt.PJrnMemo as Memo');
        $this->db->from($this->detail . ' as dt');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=dt.PJrnAccountNumber', 'inner');
        $this->db->join($this->table . ' as gr', 'gr.PJrnNumber=dt.PJrnNumber', 'inner');
        //$this->db->join($this->InvPayment . ' as hr', 'hr.InvoiceNumber=gr.PInvNumber', 'inner');
        // $this->db->join($this->am_account . ' as agf', 'agf.AccountNumber=hr.LFAccount', 'inner');
        $this->db->where('dt.PJrnNumber', $PJrnNumber);
        //$this->db->where('hr.InvoicePaymentID',$InvoicePaymentID);

        $query = $this->db->get()->result();
        $result = [];
        $returnResult = array();

        foreach($query as $row){
            $result['PaymentAmount']    = $row->PaymentAmount;
            $result['GLAccount']        = $row->GLAccount;
            $result['PJrnDetailID']     = $row->PJrnDetailID;
            $result['Memo']             = $row->Memo;
            $result['CurrencyCode']     = $row->CurrencyCode;
            $result['PJrnRate']         = $row->PJrnRate;
            $result['PrimeAmount']      = $this->convert_PrimeAmount($CurrCustCode,$type_fiscal,$row->CurrencyCode,$row->PaymentAmount,$row->PJrnRate);
            array_push($returnResult,$result);
        }

        return $returnResult;
    }

    function convert_PrimeAmount($CurrCustCode,$type_fiscal,$CurrAccountCode,$Amount,$Rate){
        if($CurrCustCode != 'IDR'){
            if($type_fiscal != 1){
                if($CurrAccountCode != 'IDR'){
                    $PrimeAmount =  doubleval($Amount) * doubleval($Rate);
                }else{
                    $PrimeAmount =  doubleval($Amount); 
                }
            }else{
               if($CurrAccountCode != 'IDR'){
                    $PrimeAmount =  doubleval($Amount) * doubleval($Rate);
                }else{
                    $PrimeAmount =  doubleval($Amount);
                } 
            }
        }else{
            if($type_fiscal != 1){
                if($CurrAccountCode != 'IDR'){
                    $PrimeAmount =  doubleval($Amount) * doubleval($Rate);
                }else{
                    $PrimeAmount =  doubleval($Amount);
                }
            }else{
               if($CurrAccountCode != 'IDR'){
                    $PrimeAmount =  doubleval($Amount) * doubleval($Rate);
                }else{
                    $PrimeAmount =  doubleval($Amount);
                } 
            }
        }

        return $PrimeAmount;
    }

    function get_total_payment_period($PInvNumber) {
        $this->db->select('sum(PaymentPerPeriod) as total_payment_period');
        $this->db->from('at_lpdetail');
        $this->db->join('at_loanpayment', 'at_loanpayment.LPNumber = at_lpdetail.LPNumber');
        $this->db->where('at_loanpayment.PInvNumber', $PInvNumber);
        $this->db->where_in('at_loanpayment.TransStatus', array(2));
        $query = $this->db->get()->result_array();

        if (count($query) > 0) {
            return $query[0]['total_payment_period'];
        } else {
            return FALSE;
        }
    }

    function get_all_payment($PInvNumber) {
        $this->db->select('LPAmount,CurrencyRate');
        $this->db->from($this->table);
        $this->db->where('PInvNumber', $PInvNumber);
        $this->db->where('TransStatus', 2);

        $query = $this->db->get()->result();

        return $query;
    }

    function get_rate_account($currency_code) {
        $this->db->select('ac.AccountNumber');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=ac.AccountNumber', 'inner');
        $this->db->where('ag.AccountName', 'Selisih Kurs Transaksi ' . $currency_code);
        $query = $this->db->get()->result_array();

        if (count($query) > 0) {
            return $query[0]['AccountNumber'];
        } else {
            return FALSE;
        }
    }

    function get_invoice_no_detail($id) {
        $this->db->select('PInvNumber');
        $this->db->from($this->table);
        $this->db->where('PJrnNumber', $id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $PInvNumber = $row->PInvNumber;
            }

            return $PInvNumber;
        } else {
            return FALSE;
        }
    }

    function get_total_piutang_terakhir($id) {
        $this->db->select('LoanPayment');
        $this->db->from('at_lpdetail');
        $this->db->where('LPNumber', $id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $LoanPayment = $row->LoanPayment;
            }

            return $LoanPayment;
        } else {
            return FALSE;
        }
    }

    function insert_group($data_payment) {
        $this->db->insert($this->table, $data_payment);
    }

    function update_payment_karyawan($data_payment, $LPNumber) {
        $this->db->where('LPNumber', $LPNumber);
        return $this->db->update($this->table, $data_payment);
    }

    function insert_detail($detail_payment) {
        $this->db->insert($this->detail, $detail_payment);
    }

    function insert_journal($journal_data) {
        $this->db->insert($this->journal, $journal_data);
    }

    function get_expt_payment() {
        $this->db->select('ExpCategoryID');
        $this->db->from('sys_expensedetail');
        $this->db->where('ExpDetailName', 'Pembayaran Piutang');
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $ExpCategoryID = $row->ExpCategoryID;
            }

            return $ExpCategoryID;
        } else {
            return FALSE;
        }
    }

    function get_account_payment($ExpCategoryID) {
        $this->db->select('AccountNumber');
        $this->db->from('sys_expenseaccount');
        $this->db->join('sys_expensedetail', 'sys_expenseaccount.ExpCategoryID=sys_expensedetail.ExpCategoryID', 'INNER');
        $this->db->where('sys_expenseaccount.ExpCategoryID', $ExpCategoryID);
        $this->db->where('sys_expenseaccount.AccountCode', 'Payable');
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $AccountNumber = $row->AccountNumber;
            }

            return $AccountNumber;
        } else {
            return FALSE;
        }
    }

    function insert_journal_credit_payment($journal_credit) {
        $this->db->insert('at_lpjournal', $journal_credit);
    }

    function get_detail($id) {

        $this->db->select('gr.*,hr.InvoiceCurrRate,hr.InvoiceFiscalRate,hr.ItemCategoryID,em.DepartmentCode,em.EmployeeCode as CreatedBy');
        $this->db->from($this->table . ' as gr');
        $this->db->join($this->InvPayment . ' as hr', 'hr.InvoiceNumber=gr.PInvNumber');
        $this->db->join($this->employee . ' as em', 'em.EmployeeCode=gr.CreatedBy', 'inner');
        $this->db->where('gr.PJrnNumber', $id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return false;
        }
    }

    function get_date_journal_payment($payment_number) {
        $this->db->select('gr.*, br.BranchName, cp.CompanyName');
        $this->db->from($this->table . ' as gr');
        $this->db->join($this->branch . ' as br', 'br.BranchCode=gr.BranchCode');
        $this->db->join($this->company . ' as cp', 'cp.CompanyCode=br.CompanyCode');
        $this->db->where('gr.PJrnNumber', $payment_number);
        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function get_all_journal_payment($payment_number, $branch_explode) {
        $this->db->select('ag.AccountName, ag.AccountNumber, jr.PJJDebet,jr.AmountCurrency,
						   jr.PJJCredit, jr.PJJDesc, jr.PJrnNumber, jr.PJJAccountNumber,br.BranchName as TransBranchName');
        $this->db->from($this->journal . ' as jr');
        $this->db->join($this->account . ' as ac', 'ac.AccountNumber=jr.PJJAccountNumber', 'inner');
        $this->db->join($this->am_account . ' as ag', 'ac.AccountNumber=ag.AccountNumber', 'inner');
        $this->db->join($this->branch.' as br','br.BranchCode=jr.TransBranchCode','inner');
        $this->db->where('ac.BranchCode', $branch_explode);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('jr.PJrnNumber', $payment_number);
        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function cek_approval_payment($payment_no) {
        $this->db->select('AppLevel1Status');
        $this->db->from($this->table);
        $this->db->where('LPNumber', $payment_no);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $AppLevel1Status = $row->AppLevel1Status;
            }

            return $AppLevel1Status;
        } else {
            return FALSE;
        }
    }

    function suspend_data($payment_no, $data) {
        $this->db->where('PJrnNumber', $payment_no);
        $this->db->update($this->table, $data);
    }

    function update_status_approval($data, $pay_number) {
        $this->db->where('PJrnNumber', $pay_number);
        $this->db->update($this->table, $data);
    }

    function update_invoice_receipt($InvoicePaymentID, $owing,$op) {
        $this->db->set('InvoiceOwing','InvoiceOwing '.$op.' '.$owing,false);
        $this->db->where('InvoicePaymentID', $InvoicePaymentID);
        $this->db->update($this->InvPayment);
    }

    function update_group($data_group, $txt_payment_no) {
        $this->db->where('PJrnNumber', $txt_payment_no);
        $this->db->update($this->table, $data_group);
    }

    function update_detail($detail_data, $PJrnDetailID) {
        $this->db->where('PJrnDetailID', $PJrnDetailID);
        $this->db->update($this->detail, $detail_data);
    }

    function delete_detail($PJrnDetailID) {
        $this->db->delete($this->detail, array('PJrnDetailID' => $PJrnDetailID));
    }

    function get_adebt_number($id) {
        $this->db->select('PInvNumber');
        $this->db->from($this->table);
        $this->db->where('PJrnNumber', $id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                $PInvNumber = $row->PInvNumber;
            }

            return $PInvNumber;
        } else {
            return FALSE;
        }
    }

    function m_delete_journal($txt_payment_no) {
        $this->db->where('PJrnNumber', $txt_payment_no);
        $this->db->delete($this->journal);
    }

    function update_approved_data($data_approval, $pay_number) {
        $this->db->update($this->table, $data_approval, array('LPNumber' => $pay_number));
    }

    function get_invoice_data($PJrnNumber) {
        $this->db->select('gr.PInvNumber,gr.VendorCode,gr.PJrnAmount,gr.InvoiceType');
        $this->db->from($this->table . ' as gr');
        $this->db->where('gr.PJrnNumber', $PJrnNumber);

        $query = $this->db->get()->result_array();

        if (count($query) > 0) {
            return $query[0];
        } else {
            return 0;
        }
    }

    function m_cek_all_invoice($PInvNumber) {
        $this->db->select('gr.InvoiceAmount,gr.InvoiceOwing');
        $this->db->from($this->InvPayment.' as gr');
        $this->db->where('gr.InvoiceNumber', $PInvNumber);

        $query = $this->db->get()->result_array();

        $total_invoice  = 0;
        $total_owing    = 0;

        for($x=0;$x<count($query);$x++){
            $total_invoice  += doubleval($query[$x]['InvoiceAmount']);
            $total_owing    += doubleval($query[$x]['InvoiceOwing']);
        }

        $return['TotalInvoice'] = $total_invoice;
        $return['TotalOwing']   = $total_owing;

        return $return;
    }

    function m_cek_status_period_piutang($piutang_no, $periode) {
        $this->db->select('gr.LFIsLock');
        $this->db->from($this->table_piutang . ' as gr');
        $this->db->join($this->detail . ' as dt', 'dt.PInvNumber=gr.PInvNumber', 'inner');
        $this->db->where('gr.PInvNumber', $piutang_no);
        $this->db->where('dt.PaymentPeriod', $periode);

        $query = $this->db->get()->result_array();

        if ($query[0]['LFIsLock'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    function update_to_reverse_journal($number_payment, $data_reversed_payment) {
        $this->db->where('PJrnNumber', $number_payment);
        $this->db->update($this->table, $data_reversed_payment);
    }

    function update_to_reverse_invoice($number_piutang, $data_reversed_piutang) {
        $this->db->where('PInvNumber', $number_piutang);
        $this->db->update($this->InvPayment, $data_reversed_piutang);
    }

    function update_invoice($data_invoice, $PInvNumber) {
        $this->db->update($this->PInv, $data_invoice, array('PInvNumber' => $PInvNumber));
    }

    function get_detail_item_print($payment_no) {
        $this->db->select('gr.*,,br.BranchName,la.AccountName as Loan_Account ,br.BranchAddress,pr.EmployeeName as nm_prepared,dr.EmployeeName as nm_direktur');
        $this->db->from($this->table . ' as gr');
        $this->db->join($this->branch . ' as br', 'br.BranchCode = gr.BranchCode', 'INNER');
        $this->db->join($this->employee . ' as pr', 'pr.EmployeeCode=gr.CreatedBy', 'LEFT');
        $this->db->join($this->employee . ' as dr', 'dr.EmployeeCode=gr.AppLevel2Code', 'LEFT');
        $this->db->join($this->am_account . ' as la', 'la.AccountNumber=gr.PJrnAccountCategory', 'LEFT');
        $this->db->where('PJrnNumber', $payment_no);
        $query = $this->db->get();
        return $query->row();
    }

    function get_detail_item_print_journal($payment_no) {
        $this->db->select('ag.AccountName as Account_Name,dt.PJrnMemo as Memo,dt.PJrnAmount as Amount');
        $this->db->from($this->detail . ' as dt');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=dt.PJrnAccountNumber', 'inner');
        $this->db->where('dt.PJrnNumber', $payment_no);
        $this->db->order_by('dt.PJrnDetailID', 'ASC');

        $query = $this->db->get()->result_array();

        return $query;
    }

    function m_get_total_piutang($PInvNumber) {
        $this->db->select('LFAmount,JVoucherBalance');
        $this->db->from('at_loanfunding');
        $this->db->where('PInvNumber', $PInvNumber);

        $query = $this->db->get()->result_array();
        if (count($query) > 0) {
            return $query[0];
        } else {
            return false;
        }
    }

    function m_get_total_payment($PInvNumber) {

        $Trans = array(2, 4);

        $this->db->select('sum(dt.PaymentPerPeriod) as total_payment');
        $this->db->from($this->table_payment . ' as gr');
        $this->db->join($this->detail_payment . ' as dt', 'dt.LPNumber=gr.LPNumber', 'inner');
        $this->db->where('gr.PInvNumber', $PInvNumber);
        $this->db->where_in('gr.TransStatus', $Trans);

        $query = $this->db->get()->result_array();
        if (count($query) > 0) {
            return $query[0]['total_payment'];
        } else {
            return false;
        }
    }

    function delete_reconcile($TransNumber) {
        $this->db->where('TransNumber', $TransNumber);
        $this->db->delete($this->reconcile);
    }

    function check_period_end($periodend) {
        $this->db->select('PeriodEnd');
        $this->db->from($this->period);
        $this->db->where('PeriodEnd', $periodend);

        $query = $this->db->get()->result_array();

        if (count($query) > 0) {
            return true;
        } else {
            return false;
        }
    }

    function m_get_bank_account($branch, $CurrencyCode) {
        $this->db->select('ag.AccountNumber,ag.AccountName,ag.CurrencyCode');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=ac.AccountNumber', 'inner');
        $this->db->join($this->sub_type . ' as sub', 'sub.AccountSubTypeID=ag.AccountSubTypeID', 'inner');
        $this->db->join($this->acc_type . ' as acc', 'acc.AccountTypeID=sub.AccountTypeID', 'inner');

        if ($CurrencyCode != 'IDR') {
            $this->db->where_in('ag.CurrencyCode', array($CurrencyCode, 'IDR'));
        }

        $this->db->where('acc.AccountTypeName', 'Cash / Bank');
        $this->db->where('ac.BranchCode', $branch);
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('ac.TransStatus', 2);

        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function m_get_expense_account($branch) {
        $this->db->select('ag.AccountNumber,ag.AccountName,ag.CurrencyCode');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=ac.AccountNumber', 'inner');
        $this->db->join($this->sub_type . ' as sub', 'sub.AccountSubTypeID=ag.AccountSubTypeID', 'inner');
        $this->db->join($this->acc_type . ' as acc', 'acc.AccountTypeID=sub.AccountTypeID', 'inner');
        //$this->db->where_in('acc.AccountTypeName',array('Expense','Other Expense','Revenue','Other Revenue'));
        $this->db->where('ac.BranchCode', $branch);
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('ac.TransStatus', 2);

        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function m_get_all_account($branch) {
        $this->db->select('ag.AccountNumber,ag.AccountName,ag.CurrencyCode');
        $this->db->from($this->account . ' as ac');
        $this->db->join($this->am_account . ' as ag', 'ag.AccountNumber=ac.AccountNumber', 'inner');
        $this->db->join($this->sub_type . ' as sub', 'sub.AccountSubTypeID=ag.AccountSubTypeID', 'inner');
        $this->db->join($this->acc_type . ' as acc', 'acc.AccountTypeID=sub.AccountTypeID', 'inner');
        $this->db->where('ag.CurrencyCode', 'IDR');
        $this->db->where('ac.BranchCode', $branch);
        $this->db->where('ag.AccountChild', 1);
        $this->db->where('ac.GLSaldoYears', date('Y'));
        $this->db->where('ac.TransStatus', 2);

        $query = $this->db->get();

        $result = $query->result();
        return json_encode($result);
    }

    function get_company_by_branch($sess_branch) {
        $this->db->select('CompanyName,BranchName');
        $this->db->from('am_company');
        $this->db->join('am_branch', 'am_branch.CompanyCode = am_company.CompanyCode', 'inner');
        // $this->db->join($this->table,$this->table.'.BranchCode = am_branch.BranchCode','inner');
        $this->db->where('am_branch.BranchCode', $sess_branch);
        $query = $this->db->get();
        return $query->row();
    }

    function get_all_to_print($data_filter) {
        /* =================================post dari find di kiri==================================================== */
        $BranchCode     = $data_filter['cmb_branch'];
        $Number         = $data_filter['txt_IDNumber'];
        $Desc           = $data_filter['txt_Description'];
        $DateFrom       = $data_filter['txt_DateFrom'];
        $DateTo         = $data_filter['txt_DateTo'];
        $TransStatus    = $data_filter['chk_TransStatus'];
        /* ============================================end============================================================ */
        
        /* ==========================================by session======================================================= */
        $sess_company = $this->session->userdata('company');
        $sess_branch = $this->session->userdata('branch');
        $sess_branch_status = $this->session->userdata('branch_status');
        /* =========================================================================================================== */

        $this->db->select('gr.PJrnDate, gr.PJrnNumber, am_branch.BranchName, gr.PJrnAmount,
		                   gr.PJrnDesc, gr.TransStatus, created_by.EmployeeName as Created');
        $this->db->from($this->table.' as gr');
        $this->db->join('am_branch', 'gr.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee as created_by', 'gr.CreatedBy=created_by.EmployeeCode', 'LEFT');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('gr.PJrnNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('gr.PJrnDesc', $Desc);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('gr.BranchCode', $BranchCode);
        } else {
            /*
              inisialisasi untuk loading pertama page branch info
             */
            //----------------kondisi by company-------------------------------------//
            /*
              branch status 0 = HO
              branch status 1 = depo/branch
              jangan lupa sesion data di atas untuk setiap kondisi
              jangan lupa tambahin case when trans status
             */
            $this->db->where('gr.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

        /* =====================================================find by date================================================== */
        if ((($DateFrom != '') && ($DateTo != ''))) {
            if ($DateFrom <= $DateTo) {
                $this->db->where('gr.PJrnDate >=', date("Y-m-d", strtotime($DateFrom)));
                $this->db->where('gr.PJrnDate <=', date("Y-m-d", strtotime($DateTo)));
            }
        }
        /* ======================================================end=========================================================== */

        /* =====================================================find by status================================================== */
        if (!empty($TransStatus)) {
            $this->db->where_in('gr.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('gr.TransStatus', array(0, 1, 4, 5, 6, 7, 8));
        }

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

        /* ==============================================sort tabel asc========================================================== */
        $this->db->order_by('gr.TransStatus', 'ASC');
        $this->db->order_by('gr.PJrnNumber', 'ASC');
        /* ===============================end================================================================================= */
        $query = $this->db->get();
        return $query->result();
    }
    function get_all_to_print_LAMA($sess_branch) {
        $this->db->select('gr.LJDate,gr.PJrnNumber,
			gr.LJDesc,gr.LJAmount');
        $this->db->from($this->table . ' as gr');
        $this->db->where('gr.BranchCode', $sess_branch);

        $query = $this->db->get();
        return $query->result();
    }

    function get_max_period_finished($no_piutang) {
        $this->db->select('max(PaymentPeriod) as period');
        $this->db->from($this->detail . ' as dt');
        $this->db->join($this->table . ' as gr', 'gr.LPNumber=dt.LPNumber', 'inner');
        $this->db->where('dt.PInvNumber', $no_piutang);
        $this->db->where_not_in('gr.TransStatus', array(3));

        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $row = $query->row();
            return $row->period;
        } else {
            return 0;
        }
    }

    function get_akun($Currency,$Branch) {
        /* ======================================scrol view 1-150======================================= */
        $page = ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
        $rows = ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;

        $account_code   = isset($_POST['AccountNo']) ? mysql_real_escape_string($_POST['AccountNo']) : '';
        $account_name   = isset($_POST['AccountName']) ? mysql_real_escape_string($_POST['AccountName']) : '';

        $beginning = ($page - 1) * $rows;
        $end = $page * $rows;
        /* ============================================================================================== */

        /* =================================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============================================================ */

        /* =========================by session==================================================================== */
        $sess_branch = $this->session->userdata('branch');
        $sess_company = $this->session->userdata('company');
        /* =============================end====================================================================== */

        $this->db->select('at_compaccountgl.AccountNumber, am_accountgl.AccountName,am_accountgl.AccountLevel, am_accountgl.AccountSubTypeID, am_accountgl.CurrencyCode, am_currency.CurrencyRate, am_accountsubtype.AccountTypeName as SubtypeName, am_accounttype.AccountTypeName as TypeName');
        $this->db->from($this->account);
        $this->db->join('am_accountgl', 'at_compaccountgl.AccountNumber=am_accountgl.AccountNumber');
        $this->db->join('am_accountsubtype', 'am_accountgl.AccountSubTypeID=am_accountsubtype.AccountSubTypeID');
        $this->db->join('am_currency', 'am_currency.CurrencyCode = am_accountgl.CurrencyCode');
        $this->db->join('am_accounttype', 'am_accounttype.AccountTypeID = am_accountsubtype.AccountTypeID');

        $this->db->where('at_compaccountgl.BranchCode', $Branch);
        $this->db->where('am_currency.CompanyCode', $sess_company);
        $this->db->where('am_accountgl.AccountChild', 1);
        $this->db->where('at_compaccountgl.TransStatus', 2);
		//$this->db->where('am_accountgl.CurrencyCode', $Currency);
        
        //$this->db->where('am_accountgl.CurrencyCode', 'IDR');
        $this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));

        if($Currency == 'IDR'){

        }else{
            $this->db->where_in('am_accountgl.CurrencyCode', array($Currency,'IDR'));
        }

        /* ===============================================pencarian pas pop up jika kondisi tidak sama dengan kosong ================== */
        if ($account_code != '') {
            $this->db->like('am_accountgl.AccountNumber', $account_code);
        }
        if ($account_name != '') {
            $this->db->like('am_accountgl.AccountName', $account_name);
        }
        /* ====================================end====================================================================================== */
		
        $this->db->order_by('at_compaccountgl.AccountNumber', 'asc');
		
        $query =  $this->db->get()->result();
        return $query;
		// $return = array();
		// foreach($query as $row){
  //           if(in_array($row->TypeName,array('Revenue','Expense','COGS / COGM (Cost Of Goods Made)','Other Revenue','Other Expense'))){
  //               $return[] = $row;
  //           }else{
  //               if($row->CurrencyCode == $Currency){
  //                   $return[] = $row;
  //               }
  //           }
  //       }

  //       return $return;
    }

    function insert_transsaction($trans_data) {

        $this->db->trans_start();

        /* ======================= insert group transaction ============================ */
        $this->insert_group($trans_data['insert_group']['data']);

        /* =========================== update is lock piutang ========================= */
        $this->update_is_lock($trans_data['islock_status']['data'], $trans_data['islock_status']['vendor_code']);
        /* =========================== end update is lock piutang ===================== */

        /* =========================== insert detail ============================ */
        for ($x = 0; $x < count($trans_data['insert_detail']['data']); $x++) {
            $this->insert_detail($trans_data['insert_detail']['data'][$x]);
        }
        /* =========================== end insert detail ========================== */

        /* ===================== insert journal ================================ */
        for ($x = 0; $x < count($trans_data['insert_journal']['data']); $x++) {
            $this->insert_journal($trans_data['insert_journal']['data'][$x]);
        }
        /* ===================== end insert journal =============================== */

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function update_transsaction($trans_data) {

        $this->db->trans_start();

        /* ====================== update group ==================== */
        $this->update_group($trans_data['update_group']['data'], $trans_data['update_group']['TransNumber']);

        /* ======================== delete detail ======================= */
        if ($trans_data['delete_detail']['total'] > 0) {
            for ($x = 0; $x < $trans_data['delete_detail']['total']; $x++) {
                $this->delete_detail($trans_data['delete_detail']['PJrnDetailID'][$x]);
            }
        }

        /* ======================= update detail ============================== */
        for ($x = 0; $x < count($trans_data['update_detail']['data']); $x++) {
            $this->update_detail($trans_data['update_detail']['data'][$x], $trans_data['update_detail']['PJrnDetailID'][$x]);
        }

        /* ========================= delete journal =============================== */
        $this->m_delete_journal($trans_data['delete_journal']['TransNumber']);

        /* ===================== insert journal ================================ */
        for ($x = 0; $x < count($trans_data['insert_journal']['data']); $x++) {
            $this->insert_journal($trans_data['insert_journal']['data'][$x]);
        }

        /* ===================== end insert journal =============================== */
        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function approve_transsaction($trans_data) {

        $this->db->trans_start();

        /* ============================================= approval transaction =================================================== */
        $this->update_status_approval($trans_data['approve_data']['data'], $trans_data['approve_data']['TransNumber']);

        /* =========================================== unlock customer ==================================================== */
        $this->update_is_lock($trans_data['islock_status']['data'], $trans_data['islock_status']['vendor_code']);

        for($x=0;$x<count($trans_data['invoice_receipt']['owing']);$x++){
            $this->update_invoice_receipt($trans_data['invoice_receipt']['InvoicePaymentID'][$x], $trans_data['invoice_receipt']['owing'][$x],'-');
        }

        if($trans_data['update_invoice']['total'] > 0){
            $this->update_invoice($trans_data['update_invoice']['data'],$trans_data['update_invoice']['TransNumber']);
        }

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function reverse_transsaction($trans_data) {
        $this->db->trans_start();

        /* ====================================================== reverse journal ==================================================== */
        $this->update_to_reverse_journal($trans_data['reverse_journal']['TransNumber'], $trans_data['reverse_journal']['data']);

         // if($trans_data['reverse_invoice']['total'] > 0){
            $this->update_invoice($trans_data['reverse_invoice']['data'],$trans_data['reverse_invoice']['TransNumber']);
        // }

        /*=========================== update invoice receipt =========================================*/
        for($x=0;$x<count($trans_data['invoice_receipt']['owing']);$x++){
            $this->update_invoice_receipt($trans_data['invoice_receipt']['InvoicePaymentID'][$x], $trans_data['invoice_receipt']['owing'][$x],'+');
        }

        /* =========================================== unlock customer ==================================================== */
        $this->update_is_lock($trans_data['islock_status']['data'], $trans_data['islock_status']['vendor_code']);

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

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function suspend_transsaction($trans_data) {

        $this->db->trans_start();

        /* ===================================== suspend payment ============================================ */
        $this->suspend_data($trans_data['suspend_data']['TransNumber'], $trans_data['suspend_data']['data']);

        /* ===================================== update piutang ============================================ */
        $this->update_is_lock($trans_data['islock_status']['data'], $trans_data['islock_status']['vendor_code']);

        $this->db->trans_complete();

        if ($this->db->trans_status() === FALSE) {
            return false;
        } else {
            return true;
        }
    }

    function get_list_branch($company){
        $this->db->select('br.BranchCode,br.BranchName');
        $this->db->from($this->branch.' as br');
        $this->db->where('br.CompanyCode',$company);
        $this->db->where('br.TransStatus',1);

        $query = $this->db->get()->result();
        return $query;

    }

}
