<?php

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

class M_purchase_payment extends CI_Model {

    public $table = "at_purchasepayment";
    public $payment = "at_invoicepayment";
    public $detail = "at_ppaydetail";
    public $journal = "at_ppayjournal";
    public $bank = "am_bank";
    public $vendor = "am_vendor";
    public $branch = "am_branch";
    public $company = "am_company";
    public $currency = "am_currency";
    public $account_gl = "am_accountgl";
    public $comp_gl = "at_compaccountgl";
    public $employee = "am_employee";

    function get_all() {
        /* =========================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'] : '';
        $VendorCode = isset($param['cmb_VendorCode']) ? $param['cmb_VendorCode'] : '';
        $PaymentStatus = isset($param['cmb_PaymentStatus']) ? $param['cmb_PaymentStatus'] : '';
        /* ============================================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("at_purchasepayment.PPayNumber, at_purchasepayment.PPayDate, at_purchasepayment.PPayDesc,br_paid.BranchName as BranchPaid,
							at_purchasepayment.PInvTotalAmount, at_purchasepayment.PPayTotalDPUsed, at_purchasepayment.PPayTotalAmount, at_purchasepayment.PPayTotalDiscount,
							at_purchasepayment.PPayTotalOwing, at_purchasepayment.PPayTotalDiscount, at_purchasepayment.PaymentStatus, at_purchasepayment.TransStatus,
							am_branch.BranchName,am_vendor.VendorName, created.EmployeeName as CreatedBy");
        $this->db->from($this->table);

        $this->db->join('am_vendor', 'at_purchasepayment.VendorCode=am_vendor.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchasepayment.BranchCode=am_branch.BranchCode', 'INNER');
		$this->db->join('am_branch as br_paid', 'at_purchasepayment.BranchPaidFor=br_paid.BranchCode', 'INNER');
		$this->db->join('am_employee as created', 'created.EmployeeCode=at_purchasepayment.CreatedBy', 'INNER');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('at_purchasepayment.PPayNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('at_purchasepayment.PPayDesc', $Desc);
        }
        if ($VendorCode != "") {
            $this->db->like('at_purchasepayment.VendorCode', $VendorCode);
        }
        if ($PaymentStatus == "All") {
            
        } else {
            $this->db->like('at_purchasepayment.PaymentStatus', $PaymentStatus);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('at_purchasepayment.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('at_purchasepayment.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

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

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

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

    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'];
        $VendorCode     = $data_filter['cmb_VendorCode'];
        $PaymentStatus  = $data_filter['cmb_PaymentStatus'];
        /* ============================================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("at_purchasepayment.PPayNumber, at_purchasepayment.PPayDate, at_purchasepayment.PPayDesc,
                            at_purchasepayment.PInvTotalAmount, at_purchasepayment.PPayTotalDPUsed, at_purchasepayment.PPayTotalAmount, at_purchasepayment.PPayTotalDiscount,
                            at_purchasepayment.PPayTotalOwing, at_purchasepayment.PPayTotalDiscount, at_purchasepayment.PaymentStatus,
                            am_branch.BranchName,am_vendor.VendorName
                            ,(case 
                            when at_purchasepayment.TransStatus = 1 then 'On Progress'
                            when at_purchasepayment.TransStatus = 2 then 'Finished'
                            when at_purchasepayment.TransStatus = 3 then 'Suspend'
                            when at_purchasepayment.TransStatus = 4 then 'Need App. Mgr.'
                            when at_purchasepayment.TransStatus = 5 then 'Need App. Dir.'
                            when at_purchasepayment.TransStatus = 6 then 'Need App. Dir. & Mgr.'
                            when at_purchasepayment.TransStatus = 9 then 'Canceled by Dir.'
                            else 'Unknown' end) as TransStatus");
        $this->db->from($this->table);

        $this->db->join('am_vendor', 'at_purchasepayment.VendorCode=am_vendor.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchasepayment.BranchCode=am_branch.BranchCode', 'INNER');

        /* ===================================find by number dan desc========================================================= */
        if ($Number != "") {
            $this->db->like('at_purchasepayment.PPayNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('at_purchasepayment.PPayDesc', $Desc);
        }
        if ($VendorCode != "") {
            $this->db->like('at_purchasepayment.VendorCode', $VendorCode);
        }
        if ($PaymentStatus == "All") {
            
        } else {
            $this->db->like('at_purchasepayment.PaymentStatus', $PaymentStatus);
        }
        /* =============================================end=================================================================== */

        /* ===================================find by branch code========================================================= */
        /*
          get data dari  combobox find di view
         */
        if ($BranchCode != "") {
            $this->db->where('at_purchasepayment.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('at_purchasepayment.BranchCode', $sess_branch);
            //-----------------------end-------------------------------------------------//
        }
        /* =======================================================end======================================================== */

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

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

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

    function get_all2($ho) {
        $Number = $this->input->post('No') ? $this->input->post('No') : '';
        $Desc = $this->input->post('Desc') ? $this->input->post('Desc') : '';
        $DateStart = $this->input->post('DateStart') ? $this->input->post('DateStart') : '';
        $DateEnd = $this->input->post('DateEnd') ? $this->input->post('DateEnd') : '';
        $Vendor = $this->input->post('Vendor') ? $this->input->post('Vendor') : '';
        $TransStatus = $this->input->post('TransStatus') ? $this->input->post('TransStatus') : '';
        $approval = $this->input->post('approval') ? $this->input->post('approval') : '';

        $this->db->select("(case when at_purchasepayment.TransStatus=1 then 'On Progress'
                            when at_purchasepayment.TransStatus=2 then 'Finished'
                            when at_purchasepayment.TransStatus=3 then 'Susppend'
                            when at_purchasepayment.TransStatus=4 then 'Managerial App'
                            when at_purchasepayment.TransStatus=5 then 'Direksi APP'
                            when at_purchasepayment.TransStatus=6 then 'MGR & DIR App'
                            else 'Waiting' end) as Status, 
                            at_purchasepayment.*, at_ppaydetail.PInvNumber, at_ppaydetail.PInvDate, 
                            at_purchaseinvoice.PRecNumber, at_purchaseinvoice.PRecDate, at_purchaseinvoice.PInvDesc, 
                            am_branch.BranchName,am_vendor.VendorName");
        $this->db->from($this->table);
        $this->db->join($this->detail, 'at_purchasepayment.PPayNumber=at_ppaydetail.PPayNumber', 'INNER');
        $this->db->join('at_pinvdetail', 'at_ppaydetail.PInvNumber=at_pinvdetail.PInvNumber', 'LEFT');
        $this->db->join('at_purchaseinvoice', 'at_pinvdetail.PInvNumber=at_purchaseinvoice.PInvNumber', 'LEFT');
        $this->db->join('am_vendor', 'at_purchasepayment.VendorCode=am_vendor.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchasepayment.BranchCode=am_branch.BranchCode', 'INNER');

        if ($this->session->userdata('jobtitle') != 'DIR') {
            if ($ho) {
                $this->db->where('am_branch.CompanyCode', $this->session->userdata('company'));
            } else {
                $this->db->where('am_branch.BranchCode', $this->session->userdata('branch'));
            }
        }

        $this->db->like('at_purchasepayment.PPayNumber', $Number);
        $this->db->like('at_purchasepayment.PPayDesc', $Desc);
        $this->db->like($this->table . '.VendorCode', $Vendor);

        if ($approval == "") {
            $this->db->like('at_purchasepayment.AppLevel1Status', $approval);
            $this->db->like('at_purchasepayment.AppLevel2Status', $approval);
        } elseif ($approval == 0) {
            $this->db->where_in("at_purchasepayment.TransStatus", array(4, 5, 6));
        } elseif ($approval == 1) {
            $this->db->where("at_purchasepayment.TransStatus", 1);
        }

        if ($DateStart != '' && $DateEnd != '') {
            $this->db->where('PPayNumber >=', date("Y-m-d", strtotime($DateStart)));
            $this->db->where('PPayNumber <=', date("Y-m-d", strtotime($DateEnd)));
        }

        if ($TransStatus != '') {
            $this->db->where_in('at_purchasepayment.TransStatus', $TransStatus);
        }

        $this->db->group_by($this->table . '.PPayNumber');
        $this->db->order_by($this->table . '.PPayNumber', 'ASC');

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

    function get_detail($ppay_number) {
        $this->db->select("pp.*, cg.GLSaldoBSheet as BankBalance, br.BranchName, cp.CompanyName, 
                           bk.BankOutCode, vd.VendorCode, vd.VendorName, vd.VendorAddress, vd.VendorCity, vd.VendorState, vd.VendorCountry, vd.SaldoDPPartial, 
                           vd.VendorPostalCode, vd.SaldoDPBalance,vd.SaldoDPReturn, vd.SaldoDPUsed, cy.CurrencyCode, cy.CurrencyName, cy.CurrencyRate");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->comp_gl . ' as cg', 'cg.AccountNumber = pp.BankPayment', 'INNER');
        $this->db->join($this->account_gl . ' as ag', 'ag.AccountNumber = cg.AccountNumber', 'INNER');
        $this->db->join($this->bank . ' as bk', 'bk.BankID = ag.BankID', 'INNER');
        $this->db->join($this->vendor . ' as vd', 'vd.VendorCode = pp.VendorCode', 'INNER');
        $this->db->join($this->branch . ' as br', 'br.BranchCode = pp.BranchCode', 'INNER');
        $this->db->join($this->company . ' as cp', 'cp.CompanyCode = br.CompanyCode', 'INNER');
        $this->db->join($this->currency . ' as cy', 'cy.CurrencyCode = pp.CurrencyCode', 'INNER');
        $this->db->where('pp.PPayNumber', $ppay_number);

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

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

    function get_detail_for_suspend($ppay_number) {
        $this->db->select("pp.*, ppd.PPayInvoiceType, ppd.PPayAmount, ppd.PPayDPUsed, ppd.POrdNumber");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->detail . ' as ppd', 'ppd.PPayNumber = pp.PPayNumber', 'INNER');
        $this->db->where('pp.PPayNumber', $ppay_number);
        $query = $this->db->get();

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

    function check_app_level($ppay_number) {
        $this->db->select("pp.AppLevel2Status, pp.AppLevel1Status, pp.VendorCode, pp.BranchPaidFor, pp.PPayTotalAmount");
        $this->db->from($this->table . ' as pp');
        $this->db->where('pp.PPayNumber', $ppay_number);
        $query = $this->db->get();

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

    function check_app_level_end_grid($ppay_number) {
        $this->db->select("pp.AppLevel2Status, pp.AppLevel1Status, pp.VendorCode, pp.BranchPaidFor, pp.PPayTotalAmount, ppd.PInvNumber");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->detail . ' as ppd', 'ppd.PPayNumber = pp.PPayNumber', 'INNER');

        $this->db->where('pp.PPayNumber', $ppay_number);
        $query = $this->db->get();

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

    //Daswan Get detail print
    function get_detail_print($ppay_number) {
        $this->db->select("pp.*, GLSaldoBalance" . CURRENT_PERIOD . " as BankBalance, br.BranchName, cp.CompanyName,
                           bk.BankOutCode, bk.BankName,bk.BankCode, vd.VendorName, vd.VendorAddress, vd.VendorCity, vd.VendorState, vd.VendorCountry, 
                           vd.VendorPostalCode, vd.SaldoDPBalance, vd.SaldoDPUsed,vd.PhoneNumber, cy.CurrencyCode, cy.CurrencyName, cy.CurrencyRate,
                           cr.EmployeeName as nm_prepared, mng.EmployeeName as nm_manager, dir.EmployeeName as nm_direktur");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->comp_gl . ' as cg', 'cg.AccountNumber = pp.BankPayment', 'INNER');
        $this->db->join($this->account_gl . ' as ag', 'ag.AccountNumber = cg.AccountNumber', 'INNER');
        $this->db->join($this->bank . ' as bk', 'bk.BankID = ag.BankID', 'INNER');
        $this->db->join($this->vendor . ' as vd', 'vd.VendorCode = pp.VendorCode', 'INNER');
        $this->db->join($this->branch . ' as br', 'br.BranchCode = pp.BranchCode', 'INNER');
        $this->db->join($this->company . ' as cp', 'cp.CompanyCode = br.CompanyCode', 'INNER');
        $this->db->join($this->currency . ' as cy', 'cy.CurrencyCode = pp.CurrencyCode', 'INNER');
        $this->db->join($this->employee . ' as cr', 'cr.EmployeeCode = pp.CreatedBy', 'LEFT');
        $this->db->join($this->employee . ' as mng', 'mng.EmployeeCode = pp.AppLevel1Code', 'LEFT');
        $this->db->join($this->employee . ' as dir', 'mng.EmployeeCode = pp.AppLevel2Code', 'LEFT');
        $this->db->where('pp.PPayNumber', $ppay_number);
        $query = $this->db->get();

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

    //Daswan get detail invoice to print
    function get_detail_invoice_print($ppay_number) {
        $this->db->_protect_identifiers = false;
        $this->db->select("(case when ppd.PPayPaidStatus = 1 then 'Yes' else 'No' end) as Paid,
                           (case when ppd.PPayInvoiceType = 0 then 'PI' else 'PO' end) as Invoice_Type,
                            ppd.PPayDetailID, ppd.InvoicePaymentID, pp.PPayNumber as PaymentNumber, ppd.PInvNumber as Invoice_Number, 
                            ppd.PInvDate as Invoice_Date, sum(ppd.PInvAmount) as Invoice_Amount, sum(PInvOwing) as Invoice_Owing, 
                            ppd.PPayDiscDate as Payment_DiscDate, sum(ppd.PPayDiscount) as Payment_Discount, sum(ppd.PPayDPUsed) as Payment_DP, sum(ppd.PPayRounded) as Load_Rounding, 
                            sum(ppd.PPayAmount) as Payment_Amount, sum(ppd.PPayCurrency) as Payment_Currency, 
                            ppd.PInvCurrRate as InvoiceCurrRate, ppd.ItemCategoryID, 0 as UnPaid,
                           (case when PPayInvoiceType = 0 then 'Invoice' else 'Down Payment' end) as PaymentType,
                           (case when ppd.PPayInvoiceType = 1 then 0 else sum(ppd.PPayDPUsed) end) as Old_Payment_DP,
                           (case when PPayInvoiceType = 0 and PPayFiscalStatus = 0 then 'Invoice' 
                                 when PPayInvoiceType = 0 and PPayFiscalStatus = 1 then 'PPn Fiscal'
                                 else 'Down Payment' end) as ItemCategoryCode");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->detail . ' as ppd', 'ppd.PPayNumber = pp.PPayNumber', 'LEFT');
        $this->db->where('pp.PPayNumber', $ppay_number);
        $this->db->group_by('Invoice_Number');
        $this->db->order_by('PInvDate', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = false;

        return $query->result_array();
    }

    function get_detail_invoice($ppay_number) {
        $this->db->_protect_identifiers = false;
        $this->db->select("(case when ppd.PPayPaidStatus = 1 then 'Yes' else 'No' end) as Paid,
                           (case when ppd.PPayInvoiceType = 0 then 'PI' else 'PO' end) as Invoice_Type,
                            ppd.PPayDetailID, ppd.PInvFiscalRate as InvoiceFiscalRate, ppd.InvoicePaymentID, pp.PPayNumber as PaymentNumber, ppd.PInvNumber as Invoice_Number, ppd.POrdNumber as Select_DP,
							sum(ppd.PInvAmountTemp) as InvoiceOwingHidden, 
							sum(PInvOwing) as InvoiceOwingHiddenNew,
                            ppd.PInvDate as Invoice_Date, sum(ppd.PInvAmount) as Invoice_Amount, sum(PInvOwing) as Invoice_Owing, sum(ppd.PInvAmountTemp) as InvoiceAmountCopy,
                            ppd.PPayDiscDate as Payment_DiscDate, sum(ppd.PPayDiscount) as Payment_Discount, sum(ppd.PPayDPUsed) as Payment_DP, sum(ppd.PPayRounded) as Load_Rounding, ppd.PPayInvoiceType, ppd.PPayDate, ppd.PPayTime,
                            sum(ppd.PPayAmount) as Payment_Amount, sum(ppd.PPayCurrency) as Payment_Currency, 
                            ppd.PInvCurrRate as InvoiceCurrRate, ppd.ItemCategoryID, 0 as UnPaid,
                           (case when PPayInvoiceType = 0 then 'Invoice' else 'Down Payment' end) as PaymentType,
                           (case when ppd.PPayInvoiceType = 1 then sum(ppd.PPayAmount) else sum(ppd.PPayDPUsed) end) as Old_Payment_DP,
                           (case when PPayInvoiceType = 0 and PPayFiscalStatus = 0 then 'Invoice' 
                                 when PPayInvoiceType = 0 and PPayFiscalStatus = 1 then 'PPn Fiscal'
                                 else 'Down Payment' end) as ItemCategoryCode");
        $this->db->from($this->table . ' as pp');
        $this->db->join($this->detail . ' as ppd', 'ppd.PPayNumber = pp.PPayNumber', 'LEFT');
        $this->db->where('pp.PPayNumber', $ppay_number);
        $this->db->group_by('Invoice_Number');
        $this->db->order_by('PInvDate', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = false;

        return $query->result();
    }

    function get_ppay_detail($pinv_number, $ppay_number) {
        $this->db->select('*');
        $this->db->from($this->detail);
        $this->db->where('PInvNumber', $pinv_number);
        $this->db->where('PPayNumber', $ppay_number);
        $this->db->order_by('PPayDetailID', 'ASC');
        $query = $this->db->get();

        return $query->result();
    }

    function get_payment($invoice_number, $invoice_type, $ppn_fiscal) {
        $this->db->select('*');
        $this->db->from($this->payment);
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceType', $invoice_type);
        $this->db->where('PPnFiscalStatus', $ppn_fiscal);
        $this->db->order_by('InvoicePaymentID', 'ASC');
        $query = $this->db->get();

        return $query->result();
    }

    function get_payment_by_id($invoice_payment_id) {
        $this->db->select('*');
        $this->db->from($this->payment);
        $this->db->where('InvoicePaymentID', $invoice_payment_id);
        $query = $this->db->get();

        return $query->result();
    }

    function get_journal_by_number($Number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select('at_ppayjournal.*,am_accountgl.AccountNumber,am_accountgl.AccountName');
        $this->db->from($this->journal);
        $this->db->join($this->account_gl, "am_accountgl.AccountNumber=at_ppayjournal.PPayAccountNumber", "INNER");

        $this->db->where('at_ppayjournal.PPayNumber', $Number);
        //$this->db->order_by('at_ppayjournal.PPaySaldoCredit', 'ASC');

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

    function get_bank_account($currency_code) {
        $this->db->select('at_compaccountgl.AccountNumber, am_accountgl.AccountName, am_bank.BankOutCode, am_bank.BankInCode,
                           am_currency.CurrencyCode, am_currency.CurrencyName, am_currency.CurrencyRate, am_bank.BankName, at_compaccountgl.GLSaldoBSheet as BankBalance');
        $this->db->from('at_compaccountgl');
        $this->db->join('am_accountgl', 'at_compaccountgl.AccountNumber = am_accountgl.AccountNumber', 'INNER');
        $this->db->join('am_accountsubtype', 'am_accountsubtype.AccountSubTypeID = am_accountgl.AccountSubTypeID', 'INNER');

        $this->db->join('am_bank', 'am_bank.BankID = am_accountgl.BankID', 'INNER');
        $this->db->join('am_currency', 'am_accountgl.CurrencyCode = am_currency.CurrencyCode', 'INNER');
        $this->db->where('at_compaccountgl.CompanyCode', $this->session->userdata('company'));
        $this->db->where('at_compaccountgl.BranchCode', $this->session->userdata('branch'));
        $this->db->where('at_compaccountgl.GLSaldoYears', date('Y'));
        $this->db->where('am_accountsubtype.AccountTypeName', 'Bank');
        $this->db->where('am_accountgl.AccountChild', 1);
        $this->db->where('am_accountgl.TransStatus', 2);
        $this->db->where('am_currency.CompanyCode', $this->session->userdata('company'));

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

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

    function check_code_exist($Number) {
        $query = $this->db->get_where($this->table, array('PPayNumber' => $Number), 1, 0);

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

    function check_approval_status($PPayNumber) {
        $query = $this->db->get_where($this->table, array('PPayNumber' => $PPayNumber, 'AppLevel1Status' => 1, 'AppLevel2Status' => 1), 1, 0);

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

    function create_pp_number($PPayDate = '', $BankOutCode) {
        $branch = $this->session->userdata('branch');

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

        $pp_number = $branch . "/" . $month . $year . "PP/" . $BankOutCode . "/";

        $this->db->_protect_identifiers = false;
        $this->db->select('(CASE 
                              WHEN MAX(CONVERT(SUBSTR(PPayNumber, -3),signed)) IS NULL then 1
                              ELSE MAX(CONVERT(SUBSTR(PPayNumber, -3),signed)) + 1 END) as New_Number');
        $this->db->like('PPayNumber', $pp_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;
        }

        $new_pp_number = $pp_number . $number;

        while ($this->check_code_exist($new_pp_number)) {
            $num++;
            $long = strlen($num);

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

            $new_pp_number = $pp_number . $number;
        }

        return $new_pp_number;
    }
	
	function reverse_trasaction($transaction_data){
		$this->db->trans_start();
        if (!empty($transaction_data['update_vendor']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_vendor']['data']); $x++) {
                $this->m_vendors->update($transaction_data['update_vendor']['data'][$x],$transaction_data['update_vendor']['VendorCode'][$x],$transaction_data['update_vendor']['BranchCode'][$x]);
            }
        }
		if (!empty($transaction_data['update_dp']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_dp']['data']); $x++) {
                $this->update_po_detail_dp_by_vendor($transaction_data['update_dp']['data'][$x],$transaction_data['update_dp']['VendorCode'][$x],$transaction_data['update_dp']['SOrdDetailDPID'][$x],$transaction_data['update_dp']['Select_DP'][$x]);
            }
        }
		if (!empty($transaction_data['update_pi']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_pi']['data']); $x++) {
				$this->m_purchase_invoice->update($transaction_data['update_pi']['data'][$x], $transaction_data['update_pi']['InvoiceNumber'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_payment']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_payment']['data']); $x++) {
				$this->m_purchase_payment->update_payment($transaction_data['update_payment']['data'][$x], $transaction_data['update_payment']['InvoicePaymentID'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_po']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_po']['data']); $x++) {
				$this->m_purchase_order->update($transaction_data['update_po']['data'][$x], $transaction_data['update_po']['InvoiceNumber'][$x]);
            }
        }
		
		if (!empty($transaction_data['delete_dp']['PPayNumber'])) {
            for ($x = 0; $x < count($transaction_data['delete_dp']['PPayNumber']); $x++) {
            	$this->delete_dp($transaction_data['delete_dp']['PPayNumber'][$x]);
			}
        }
		
		$this->update($transaction_data['update_data']['data'],$transaction_data['update_data']['PPayNumber']);	
		
		if (!empty($transaction_data['update_data_giro']['data'])) {
			$this->m_purchase_giro->update($transaction_data['update_data_giro']['data'],$transaction_data['update_data_giro']['PGirNumber']);
		}
		
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
	}
	
    function insert($data) {
        $this->db->insert($this->table, $data);
    }

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

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

    function delete_journal($id) {
        $this->db->delete($this->journal, array('PPayNumber' => $id));
    }

    function update($data, $id) {
        $this->db->update($this->table, $data, array('PPayNumber' => $id));
    }

    function update_detail_by_ppaynum($data, $PPayNumber, $PInvNumber) {
        $this->db->update($this->detail, $data, array('PPayNumber' => $PPayNumber, 'PInvNumber' => $PInvNumber));
    }

    function update_detail($data, $ppay_detail_id) {
        $this->db->update($this->detail, $data, array('PPayDetailID' => $ppay_detail_id));
    }

    function update_journal_invoice($txt_no, $data, $id, $invoice_number) {
        $this->db->update($this->journal, $data, array('PPayNumber' => $txt_no, 'PPayAccountNumber' => $id, 'PInvNumber' => $invoice_number));
    }
	
    function update_journal($txt_no, $data, $id) {
        $this->db->update($this->journal, $data, array('PPayNumber' => $txt_no, 'PPayAccountNumber' => $id));
    }

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

    function update_payment($data, $invoice_payment_id) {
        $this->db->update($this->payment, $data, array('InvoicePaymentID' => $invoice_payment_id));
    }

    function update_po_detail_dp_by_vendor($data, $id, $id_detail, $pord_number) {
        $this->db->update('at_pordetaildp', $data, array('VendorCode' => $id, 'POrdDetailDPID' => $id_detail, 'POrdNumber' => $pord_number));
    }

    function update_po_detail_dp_pay_before($data, $id, $pord_number, $POrdDetailDPID) {
        $this->db->update('at_pordetaildp', $data, array('VendorCode' => $id, 'POrdNumber' => $pord_number, 'POrdDetailDPID' => $POrdDetailDPID));
    }

    function update_po_detail_dp_for_pp($data, $id, $POrdDetailDPID) {
        $this->db->update('at_pordetaildp', $data, array('VendorCode' => $id, 'POrdDetailDPID' => $POrdDetailDPID));
    }

    function update_po_detail_dp_by_sal($data, $id) {
        $this->db->update('at_pordetaildp', $data, array('POrdNumber' => $id));
    }

    function insert_po_detail_dp($data) {
        $this->db->insert('at_pordetaildp', $data);
    }
	
	function delete_dp($id){
		$this->db->delete('at_pordetaildp', array('PPayNumber' => $id));
    }
	
    function set_finish_payment($invoice_number) {
        $this->db->select('*');
        $this->db->from($this->payment);
        $this->db->where('InvoiceNumber', $invoice_number);
        $this->db->where('InvoiceOwing', 0);
        $this->db->group_by('InvoiceNumber');
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $data_payment = array(
                'LockedStatus' => 2,
                'LastUser' => $this->session->userdata("username")
            );
        } else {
            $data_payment = array(
                'LockedStatus' => 0,
                'LastUser' => $this->session->userdata("username")
            );
        }

        $this->db->update($this->payment, $data_payment, array('InvoiceNumber' => $invoice_number));

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

    function get_pordetail_dp_invoice_or_return($vendor_code, $POrdNumber, $status_transaction) {
        $this->db->select('POrdTotalDP, Owing, PaymentAmount, VendorCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, POrdDetailDPID, DPUsed, SOrdStatus, JVoucherBalance');
        $this->db->from('at_pordetaildp');
        $this->db->where('VendorCode', $vendor_code);
        $this->db->where('POrdNumber', $POrdNumber);
        $this->db->where('StatusDPFor', $status_transaction);
        $this->db->where('(SaldoDPBalance - DPUsedBook) >', 0);

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

        return $query->result();
    }

    function get_saldo_detail_dp($id, $POrdNumber, $status_transaction) {
        $this->db->_protect_identifiers = FALSE;
        if ($status_transaction == 4) {
            $this->db->select("at_pordetaildp.POrdNumber, sum(at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed) as PaymentAmount_SUM,
							sum(at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed) as Payment_Used, at_pordetaildp.VendorCode, 'No' as Status");
        } else if ($status_transaction == 6) {
            $this->db->select("at_pordetaildp.SOrdStatus, at_pordetaildp.JVoucherBalance, at_pordetaildp.POrdTotalDP, at_pordetaildp.Owing, 
								at_pordetaildp.PaymentAmount, at_pordetaildp.VendorCode, at_pordetaildp.SaldoDPBalance, at_pordetaildp.POrdNumber, 
								at_pordetaildp.CurrencyRate, at_pordetaildp.DPUsedBook, at_pordetaildp.IsEdit, at_pordetaildp.POrdDetailDPID, 
								at_pordetaildp.DPUsed, at_pordetaildp.PaymentBefore, at_pinvjournal.PInvSaldoCredit");
            $this->db->join('at_purchaseinvoice', 'at_purchaseinvoice.POrdNumber = at_pordetaildp.POrdNumber', 'INNER');
            $this->db->join('at_pinvjournal', 'at_pinvjournal.PInvNumber = at_purchaseinvoice.PInvNumber', 'INNER');
        } else {
            $this->db->select("SOrdStatus, JVoucherBalance, POrdTotalDP, Owing, PaymentAmount, VendorCode, SaldoDPBalance, POrdNumber, 
								CurrencyRate, DPUsedBook, IsEdit, POrdDetailDPID, DPUsed, PaymentBefore");
        }

        $this->db->from('at_pordetaildp');
        $this->db->where('at_pordetaildp.VendorCode', $id);
        if ($status_transaction == 1) {
            $this->db->where('POrdNumber', $POrdNumber);
        } else if ($status_transaction == 2) {
            $this->db->where('POrdNumber', $POrdNumber);
            $this->db->where('(SaldoDPBalance - DPUsed) >', 0);
        } else if ($status_transaction == 3) {
            $this->db->where('TransactionNumber', $POrdNumber);
        } else if ($status_transaction == 4) {
            $this->db->where('StatusDPFor', 1);
            $this->db->where('(SaldoDPBalance - DPUsed) >', 0);
            $this->db->group_by('POrdNumber');
        } else if ($status_transaction == 5) {
            $this->db->where('POrdNumber', $POrdNumber);
        } else if ($status_transaction == 6) {
            $this->db->where('at_pordetaildp.POrdNumber', $POrdNumber);
            $this->db->where_in('at_purchaseinvoice.TransStatus', array(4));
        }

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

        return $query->result();
    }

    function get_saldo_detail_dp_update($id) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.POrdNumber, at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed as PaymentAmount_SUM, at_pordetaildp.POrdDetailDPID,at_pordetaildp.TransactionNumber,
							at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed as Payment_Used, at_pordetaildp.VendorCode, 'No' as Status");
        //$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_pordetaildp.POrdDetailDPID', 'LEFT');

        $this->db->from('at_pordetaildp');
        $this->db->where('at_pordetaildp.VendorCode', $id);
        $this->db->where('at_pordetaildp.StatusDPFor', 1);
        $this->db->where("(((at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed) > 0) OR (at_pordetaildp.IsEdit = 1))");
        //$this->db->where('at_pordetaildp.IsEdit', 1);
        //$this->db->group_by('at_pordetaildp.POrdNumber');

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

        return $query->result();
    }

    function get_saldo_detail_dp_new($id) {

        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.POrdNumber, sum(at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed) as PaymentAmount_SUM, at_pordetaildp.POrdDetailDPID,at_pordetaildp.TransactionNumber,
							at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed as Payment_Used, at_pordetaildp.VendorCode, 'No' as Status");
        //$this->db->join('at_ppaydetail', 'at_ppaydetail.POrdDetailDPID = at_pordetaildp.POrdDetailDPID', 'LEFT');

        $this->db->from('at_pordetaildp');
        $this->db->where('at_pordetaildp.VendorCode', $id);
        $this->db->where('at_pordetaildp.StatusDPFor', 1);
        $this->db->where_in('at_pordetaildp.IsEdit', array(1, 0));
        $this->db->where('(at_pordetaildp.SaldoDPBalance - at_pordetaildp.DPUsed) > ', 0);
        $this->db->group_by('at_pordetaildp.POrdNumber');

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

        return $query->result();
    }

    function get_payment_detail_dp_suspend($id, $POrdNumber, $akun_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.SOrdStatus, at_pordetaildp.JVoucherBalance, at_pordetaildp.POrdTotalDP, at_pordetaildp.Owing, 
							at_pordetaildp.PaymentAmount, at_pordetaildp.VendorCode, at_pordetaildp.SaldoDPBalance, at_pordetaildp.POrdNumber, 
							at_pordetaildp.CurrencyRate, at_pordetaildp.DPUsedBook, at_pordetaildp.IsEdit, at_pordetaildp.POrdDetailDPID, 
							at_pordetaildp.DPUsed, at_pordetaildp.PaymentBefore, at_ppayjournal.AmountCurrency, at_pordetaildp.DPTransaction");
        $this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppayjournal.PPayNumber', 'INNER');
        $this->db->join('at_pordetaildp', 'at_pordetaildp.POrdDetailDPID = at_ppayjournal.POrdDetailDPID', 'INNER');

        $this->db->from('at_ppayjournal');
        $this->db->where('at_pordetaildp.VendorCode', $id);

        $this->db->where('at_pordetaildp.POrdNumber', $POrdNumber);
        $this->db->where('at_ppayjournal.PPayAccountNumber', $akun_number);
        $this->db->where_in('at_purchasepayment.TransStatus', array(5));

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

        return $query->result();
    }

    function get_payment_detail_dp_update($id, $akun_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.SOrdStatus, at_pordetaildp.JVoucherBalance, at_pordetaildp.POrdTotalDP, at_pordetaildp.Owing, 
							at_pordetaildp.PaymentAmount, at_pordetaildp.VendorCode, at_pordetaildp.SaldoDPBalance, at_pordetaildp.POrdNumber, 
							at_pordetaildp.CurrencyRate, at_pordetaildp.DPUsedBook, at_pordetaildp.IsEdit, at_pordetaildp.POrdDetailDPID, 
							at_pordetaildp.DPUsed, at_pordetaildp.PaymentBefore, at_ppayjournal.AmountCurrency, at_pordetaildp.DPTransaction, at_ppayjournal.PPaySaldoCredit");
        $this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppayjournal.PPayNumber', 'INNER');
        $this->db->join('at_pordetaildp', 'at_pordetaildp.POrdDetailDPID = at_ppayjournal.POrdDetailDPID', 'INNER');

        $this->db->from('at_ppayjournal');
        $this->db->where('at_pordetaildp.VendorCode', $id);

        $this->db->where('at_ppayjournal.PPayAccountNumber', $akun_number);
        $this->db->where_in('at_purchasepayment.TransStatus', array(5));

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

        return $query->result();
    }

    function get_saldo_detail_dp_suspend($id, $POrdNumber, $akun_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.SOrdStatus, at_pordetaildp.JVoucherBalance, at_pordetaildp.POrdTotalDP, at_pordetaildp.Owing, 
							at_pordetaildp.PaymentAmount, at_pordetaildp.VendorCode, at_pordetaildp.SaldoDPBalance, at_pordetaildp.POrdNumber, 
							at_pordetaildp.CurrencyRate, at_pordetaildp.DPUsedBook, at_pordetaildp.IsEdit, at_pordetaildp.POrdDetailDPID, 
							at_pordetaildp.DPUsed, at_pordetaildp.PaymentBefore, at_pinvjournal.AmountCurrency");
        $this->db->join('at_purchaseinvoice', 'at_purchaseinvoice.PInvNumber = at_pinvjournal.PInvNumber', 'INNER');
        $this->db->join('at_pordetaildp', 'at_pordetaildp.POrdDetailDPID = at_pinvjournal.POrdDetailDPID', 'INNER');

        $this->db->from('at_pinvjournal');
        $this->db->where('at_pordetaildp.VendorCode', $id);

        $this->db->where('at_pordetaildp.POrdNumber', $POrdNumber);
        $this->db->where('at_pinvjournal.PInvAccountNumber', $akun_number);
        $this->db->where_in('at_purchaseinvoice.TransStatus', array(4));

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

        return $query->result();
    }

    function get_saldo_detail_dp_group($id, $POrdNumber) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pordetaildp.DPUsed");

        $this->db->from('at_pordetaildp');
        $this->db->where('at_pordetaildp.VendorCode', $id);

        $this->db->where('at_pordetaildp.POrdNumber', $POrdNumber);
        $this->db->group_by('at_pordetaildp.POrdNumber');

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

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

            return $DPUsed;
        } else {
            return 0;
        }
    }

    function get_saldo_detail_dp_for_invoice_group($id) {
        $this->db->select('sum(at_ppaydetail.PPayAmount), sum(at_ppaydetail.PPayRounded), sum(at_ppaydetail.PPayDiscount), sum(at_ppaydetail.PPayDPUsed), at_ppaydetail.PPayCurrRate, 
							at_ppaydetail.PInvCurrRate');
        $this->db->from('at_ppaydetail');

        $this->db->where('at_ppaydetail.PInvNumber', $id);
        $this->db->group_by('at_ppaydetail.PInvNumber');

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

        return $query->result();
    }

    function get_saldo_detail_dp_for_pj($id) {
        $this->db->select('POrdTotalDP, Owing, PaymentAmount, VendorCode, SaldoDPBalance, CurrencyRate, DPUsedBook, IsEdit, POrdDetailDPID, DPUsed, SOrdStatus, JVoucherBalance');
        $this->db->from('at_pordetaildp');
        $this->db->where('POrdNumber', $id);

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

        return $query->result();
    }

    function get_vendor_for_lock_status($vendor_code) {
        $this->db->select('VendorCode, VendorName, LockStatus');
        $this->db->from('am_vendor');
        $this->db->where('VendorCode', $vendor_code);
        $this->db->where('TransStatus', 1);

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

        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return FALSE;
        }
    }
	
	function get_giro_check_to_purchase_payment($PGirNumber) {
        $this->db->select('PGirNumber');
        $this->db->from('at_purchasepayment');
        $this->db->where('PGirNumber', $PGirNumber);
        $this->db->where_in('TransStatus', array(1,2));

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

        if ($query->num_rows() > 0) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
	
    function get_journal_purchase_payment($PPayAccountNumber, $ppay_number, $invoice_number) {
        $this->db->select('at_ppayjournal.PPaySaldoCredit, at_ppayjournal.PPaySaldoDebet, at_ppayjournal.PPayAccountNumber, at_ppayjournal.PInvNumber, 
							at_ppayjournal.AmountCurrency, at_ppaydetail.PInvNumber');
        $this->db->from($this->journal);
        $this->db->join('at_ppaydetail', 'at_ppaydetail.PPayNumber = at_ppayjournal.PPayNumber', 'INNER');

        $this->db->where('at_ppayjournal.PPayNumber', $ppay_number);
        $this->db->where('at_ppayjournal.PPayAccountNumber', $PPayAccountNumber);
        $this->db->where('at_ppayjournal.PInvNumber', $invoice_number);

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

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

    function get_journal_purchase_payment_no_invoice($PPayAccountNumber, $ppay_number) {
        $this->db->select('at_ppayjournal.PPaySaldoCredit, at_ppayjournal.PPaySaldoDebet, at_ppayjournal.PPayAccountNumber, 
							at_ppayjournal.AmountCurrency');
        $this->db->from($this->journal);

        $this->db->where('at_ppayjournal.PPayNumber', $ppay_number);
        $this->db->where('at_ppayjournal.PPayAccountNumber', $PPayAccountNumber);

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

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

    function get_pordetail_dp_return($vendor_code) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(SaldoDPBalance - DPUsedBook) as DownPayment");
        $this->db->from('at_pordetaildp');
        $this->db->where('VendorCode', $vendor_code);
        $this->db->where('StatusDPFor', 1);
        //$this->db->where('(SaldoDPBalance - DPUsedBook) >', 0);
        $this->db->group_by('POrdNumber');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

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

            return $DownPayment;
        } else {
            return 0;
        }
    }

    function get_pordetail_dp_balance($vendor_code) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(SaldoDPBalance) as SaldoDPBalance, sum(SaldoDPBalance - DPUsed) as DownPayment");
        $this->db->from('at_pordetaildp');
        $this->db->where('VendorCode', $vendor_code);
        $this->db->where('StatusDPFor', 1);
        //$this->db->where('(SaldoDPBalance - DPUsed) >', 0);
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

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

    function get_pordetail_dp_balance_invoice($vendor_code) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(SaldoDPBalance - DPUsed) as DownPayment");
        $this->db->from('at_pordetaildp');
        $this->db->where('VendorCode', $vendor_code);
        $this->db->where('StatusDPFor', 0);
        //$this->db->where('(SaldoDPBalance - DPUsed) >', 0);
        $this->db->group_by('VendorCode');

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

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

    function get_saldo_detail($POrdDetailDPID, $VendorCode, $PPayNumber) {
        $this->db->select("at_ppayjournal.AmountCurrency, at_ppayjournal.PPaySaldoCredit");
        $this->db->from('at_ppayjournal');
        $this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppayjournal.PPayNumber', 'INNER');

        $this->db->where('at_purchasepayment.VendorCode', $VendorCode);
        $this->db->where('at_ppayjournal.POrdDetailDPID', $POrdDetailDPID);
        $this->db->where('at_purchasepayment.PPayNumber', $PPayNumber);
		$this->db->where('at_purchasepayment.TransStatus', 5);
        //$this->db->where_in('at_ppayjournal.PPayAccountNumber', array('1-4-04-001-00','1-4-04-002-00'));

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

    function get_detail_dp($id, $POrdNumber) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("POrdDetailDPID");

        $this->db->from('at_pordetaildp');
        $this->db->where('at_pordetaildp.VendorCode', $id);
        $this->db->where('POrdNumber', $POrdNumber);
        $this->db->where('(SaldoDPBalance - DPUsed) >', 0);

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

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

    function set_finish_invoice($id) {
        $this->db->select('sum(InvoiceOwing) as InvoiceOwing');
        $this->db->from($this->payment);
        $this->db->where('InvoiceNumber', $id);
        $query = $this->db->get();

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

    function get_purchase_payment_for_dp($POrdNumber, $VendorCode) {
        $this->db->select('at_ppaydetail.PInvNumber');
        $this->db->from('at_ppaydetail');
        $this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppaydetail.PPayNumber', 'INNER');

        $this->db->where('at_ppaydetail.PInvNumber', $POrdNumber);
        $this->db->where('at_purchasepayment.VendorCode', $VendorCode);
        $this->db->where_in('at_purchasepayment.TransStatus', array(5));
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }
	
	function get_purchase_order_dp_detail($PInvNumber){
        $this->db->select('at_ppaydetail.PPayDate,at_ppaydetail.PPayTime,at_ppaydetail.PPayNumber');
        $this->db->from('at_ppaydetail');
		$this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppaydetail.PPayNumber', 'INNER');
		
        $this->db->where('at_ppaydetail.PInvNumber', $PInvNumber);
		$this->db->where('at_purchasepayment.TransStatus', 2);
		$this->db->group_by('at_ppaydetail.PPayNumber');
		$this->db->order_by('at_ppaydetail.PPayTime', 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->result();
        }
        else{
            return false;
        }	
    }
	
	function get_purchase_payment_dp_used($POrdNumber){
        $this->db->select('at_ppaydetail.PPayNumber');
        $this->db->from('at_ppaydetail');
		$this->db->join('at_purchasepayment', 'at_purchasepayment.PPayNumber = at_ppaydetail.PPayNumber', 'INNER');
        $this->db->where('at_ppaydetail.POrdNumber', $POrdNumber);
		$this->db->where('at_purchasepayment.TransStatus !=', 3);
		$this->db->group_by('at_ppaydetail.PInvNumber');
		$this->db->order_by('at_ppaydetail.PInvNumber', 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    }
	
	function get_purchase_dp_useddp($InvoiceNumber,$table, $PDpayNumber,$POrdNumber){
        $this->db->select($table.'.'.$PDpayNumber);
        $this->db->from($table);
		
        $this->db->where($table.'.'.$POrdNumber, $InvoiceNumber);
		$this->db->where($table.'.TransStatus !=', 3);
		$this->db->order_by($table.'.'.$POrdNumber, 'ASC');
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return $query->row();
        }
        else{
            return false;
        }	
    }
	
	function get_detail_item_for_pgir($vendor_code, $ppn_fiscal, $PGirNumber) {
        $this->db->_protect_identifiers = false;
        $this->db->select("at_invoicepayment.InvoicePaymentID, at_invoicepayment.InvoiceNumber as Invoice_Number, at_invoicepayment.InvoiceDate as Invoice_Date, sum(at_invoicepayment.InvoiceAmount) as Invoice_Amount, sum(at_invoicepayment.InvoiceOwing) as InvoiceAmountCopy, sum(at_invoicepayment.InvoiceOwing) as InvoiceOwingHidden, sum(at_invoicepayment.InvoiceOwing) as InvoiceOwingHiddenNew, sum(at_pgirdetail.PGirAmount) as Payment_Amount, sum(at_pgirdetail.PGirCurrency) as Payment_Currency, sum(at_pgirdetail.PGirRounded) as Load_Rounding, 
							'0' as Payment_DP, '0' as Payment_Discount, ' ' as Select_DP,
                           sum(at_invoicepayment.InvoiceOwing) as Invoice_Owing, at_invoicepayment.InvoiceCurrCode, at_invoicepayment.InvoiceCurrRate, at_invoicepayment.InvoiceFiscalRate, 'Yes' as Paid, at_invoicepayment.ItemCategoryID, at_invoicepayment.ItemCategoryRatio,
                          (case when at_invoicepayment.InvoiceType = 0 and at_invoicepayment.PPnFiscalStatus = 0 then 'Invoice' 
                                when at_invoicepayment.InvoiceType = 0 and at_invoicepayment.PPnFiscalStatus = 1 then 'PPn Fiscal'
                                else 'Down Payment' end) as ItemCategoryCode,
                          (case when at_invoicepayment.InvoiceType = 0 then 'PI' else 'PO' end) as Invoice_Type");
        $this->db->from($this->payment);
		$this->db->join('at_pgirdetail', 'at_pgirdetail.InvoicePaymentID = at_invoicepayment.InvoicePaymentID', 'INNER');
        $this->db->where('at_invoicepayment.VendorCode', $vendor_code);
        $this->db->where('at_invoicepayment.PPnFiscalStatus', $ppn_fiscal);
		$this->db->where('at_pgirdetail.PGirNumber', $PGirNumber);
        $this->db->where('ROUND(at_invoicepayment.InvoiceOwing, 2) > ', 0);
        $this->db->where('at_invoicepayment.LockedStatus', 0);
        $this->db->where('at_invoicepayment.TransStatus', 0);
        $this->db->group_by('at_invoicepayment.InvoiceNumber');
        $this->db->order_by('at_invoicepayment.InvoiceNumber', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = true;

        return $query->result();
    }
	
	function get_pgir_number_to_payment($PgirNumber){
		$this->db->select('at_purchasepayment.PGirNumber');
        $this->db->from('at_purchasepayment');
        $this->db->where('at_purchasepayment.PGirNumber', $PgirNumber);
		$this->db->where('at_purchasepayment.TransStatus', 5);
		
        $query = $this->db->get();
        
        if($query->num_rows() > 0){
            return true;
        }
        else{
            return false;
        }	
	}
}

/* End of file m_receive_item.php */
/* Location: ./application/models/m_receive_item.php */