<?php

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

class M_purchase_order extends CI_Model {

    public $table = "at_purchaseorder";
    public $detail = "at_porddetail";
    public $table_ri = "at_receiveitem";
    public $table_payment = "at_invoicepayment";
    public $vendor = "am_vendor";
    public $item = "am_item";
    public $item_category = "am_itemcategory";
    public $branch = "am_branch";
    public $shipment = "am_shipment";
    public $payment = "am_termspayment";
    public $employee = "am_employee";
    public $PInvoice = 'at_purchaseinvoice';
    public $PInvDetail = 'at_pinvdetail';
    public $PReceipt = 'at_receiveitem';
    public $PRecDetail = 'at_precdetail';
    public $company = "am_company";

    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'] : '';
        /* ============================================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_purchaseorder.*, am_branch.BranchName, am_vendor.VendorName, am_vendor.VendorCode, am_employee.EmployeeName as CreatedBy");
        $this->db->from($this->table);
        $this->db->join($this->vendor, $this->vendor . '.VendorCode = ' . $this->table . '.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchaseorder.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee', 'at_purchaseorder.CreatedBy=am_employee.EmployeeCode', 'INNER');

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

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

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

        /* =====================================================find by status================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('at_purchaseorder.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_purchaseorder.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 . '.POrdNumber', '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'];
        /* ============================================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_purchaseorder.*, am_branch.BranchName, am_vendor.VendorName, am_vendor.VendorCode, am_employee.EmployeeName as CreatedBy"
                . ",
                          (case 
                            when at_purchaseorder.TransStatus = 0 then 'Need DP'
                            when at_purchaseorder.TransStatus = 1 then 'On Progress'
                            when at_purchaseorder.TransStatus = 2 then 'Finished'
                            when at_purchaseorder.TransStatus = 3 then 'Suspend'
                            when at_purchaseorder.TransStatus = 4 then 'Need App. Mgr.'
                            when at_purchaseorder.TransStatus = 5 then 'Need App. Dir.'
                            when at_purchaseorder.TransStatus = 6 then 'Need App. Dir. & Mgr.'
                            when at_purchaseorder.TransStatus = 9 then 'Canceled by Dir.'
                            else 'Unknown' end) as Status");
        $this->db->from($this->table);
        $this->db->join($this->vendor, $this->vendor . '.VendorCode = ' . $this->table . '.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchaseorder.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee', 'at_purchaseorder.CreatedBy=am_employee.EmployeeCode', 'INNER');

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

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

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

        /* =====================================================find by status================================================== */
        if (!empty($TransStatus)) {
            $this->db->where_in('at_purchaseorder.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_purchaseorder.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 . '.POrdNumber', 'ASC');
        /* ===============================end================================================================================= */
        $query = $this->db->get();
        return $query->result();
    }

    function get_po_by_precnumber($id) {
        $this->db->where('AppLevel1Status !=', 1);
        $this->db->where('AppLevel2Status !=', 1);
        $this->db->where('TransStatus !=', 2);
        $this->db->where('PReqNumber', $id);
        $query = $this->db->get($this->table);

        return $query->result();
    }

    function get_detail($pord_number) {
        $this->db->select('po.*, pd.ItemType, vd.VendorStatus, vd.VendorTaxNumber, emp.DepartmentCode');
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pd', 'pd.POrdNumber = po.POrdNumber', 'INNER');
        $this->db->join($this->vendor . ' as vd', 'vd.VendorCode = po.VendorCode', 'INNER');
        $this->db->join($this->employee . ' as emp', 'emp.EmployeeCode = po.CreatedBy', 'INNER');

        $this->db->where('po.POrdNumber', $pord_number);
        $this->db->order_by('pd.POrdDetailID', 'ASC');
        $query = $this->db->get();

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

    function get_table_group($pord_number) {
        $this->db->select('po.*, vd.VendorStatus, vd.VendorTaxNumber, emp.DepartmentCode');
        $this->db->from($this->table . ' as po');
        $this->db->join($this->vendor . ' as vd', 'vd.VendorCode = po.VendorCode', 'INNER');
        $this->db->join($this->employee . ' as emp', 'emp.EmployeeCode = po.CreatedBy', 'INNER');

        $this->db->where('po.POrdNumber', $pord_number);
        $query = $this->db->get();

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

    //Daswan get detail to print
    function get_detail_print($pord_number) {
        $this->db->select("po.*, pd.ItemType, vd.VendorStatus, vd.VendorTaxNumber, vd.VendorName, vd.VendorAddress, vd.PhoneNumber,br.BranchName, sm.ShipmentName,cm.CompanyName,cm.CompanyAddress,cm.PhoneNumber as tlp_kantor,
                        (case when po.FOBID = 1 then 'Shiping Point' when po.FOBID = 2 then 'Destination' else 'No' end) as FOB, pay.TermDesc, emp_created.EmployeeName as created_by, emp_manager.EmployeeName as nm_manager, emp_direksi.EmployeeName as nm_direksi");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pd', 'pd.POrdNumber = po.POrdNumber', 'INNER');
        $this->db->join($this->vendor . ' as vd', 'vd.VendorCode = po.VendorCode', 'INNER');
        
        $this->db->join($this->branch . ' as br', 'br.BranchCode = po.BranchCode', 'INNER');
        $this->db->join($this->company . ' as cm', 'br.CompanyCode = cm.CompanyCode', 'INNER');

        $this->db->join($this->shipment . ' as sm', 'sm.ShipmentID = po.ShipmentID', 'LEFT');
        $this->db->join($this->payment . ' as pay', 'pay.TermspaymentID = po.TermspaymentID', 'INNER');
        $this->db->join($this->employee . ' as emp_created', 'emp_created.EmployeeCode = po.CreatedBy', 'LEFT');
        $this->db->join($this->employee . ' as emp_manager', 'emp_manager.EmployeeCode = po.AppLevel1Code', 'LEFT');
        $this->db->join($this->employee . ' as emp_direksi', 'emp_direksi.EmployeeCode = po.AppLevel2Code', 'LEFT');
        $this->db->where('po.POrdNumber', $pord_number);
        $this->db->order_by('pd.POrdDetailID', 'ASC');
        $query = $this->db->get();

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

    function get_detail_item($pord_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("pod.*, pod.ItemAmount as ItemAmount_Hide, pod.ItemQty as ItemQty_Old, it.ItemTypeID, prd.PReqDetailID, pr.PReqDate,pr.PReqDesc, po.POrdNumber, po.POrdPPn10Pcnt,po.POrdTaxesStatus, po.POrdInTaxStatus,
                           pod.ItemPriceNTax, prd.ItemQtyPO, '0' as IntaxStatus, 0 as ItemModusType, 0 as AmountDisc, prd.ItemQty as ItemQtyPR, po.CurrencyRate as CurrencyRatePo,
                         (case 
                              when prd.ItemType = 0 or 1 
                              then ((prd.ItemQty - prd.ItemQtyPO - prd.ItemQtySPD) + pod.ItemQty)
                              else 1 end) as ItemMax,
                         (case when pod.ItemSpdStatus = 0 then 'No' else 'Yes' end) as ItemSpdStatus");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pod', "pod.POrdNumber = po.POrdNumber", "INNER");
        $this->db->join("at_preqdetail as prd", "prd.PreqDetailID = pod.PreqDetailID", "INNER");
        $this->db->join("at_purchaserequisition as pr", "prd.PReqNumber = pr.PReqNumber", "INNER");

        $this->db->join("am_item as it", "it.ItemCode = pod.ItemCode", "LEFT");
        $this->db->where('po.POrdNumber', $pord_number);
        $this->db->order_by('pod.POrdDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function get_detail_item_do_direct($pord_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("pod.*, pod.ItemAmount as ItemAmount_Hide, pod.ItemQty as ItemQty_Old, it.ItemTypeID, prd.PReqDetailID, pr.PReqDate,pr.PReqDesc, po.POrdNumber,dod.ItemQty as ItemQty_DO,
                           pod.ItemPriceNTax, prd.ItemQtyPO, '0' as IntaxStatus, 0 as ItemModusType, 0 as AmountDisc, prd.ItemQty as ItemQtyPR, po.CurrencyRate as CurrencyRatePo,
                         (case 
                              when prd.ItemType = 0 or 1 
                              then ((prd.ItemQty - prd.ItemQtyPO - prd.ItemQtySPD) + pod.ItemQty)
                              else 1 end) as ItemMax,
                         (case when pod.ItemSpdStatus = 0 then 'No' else 'Yes' end) as ItemSpdStatus");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pod', "pod.POrdNumber = po.POrdNumber", "INNER");
        $this->db->join("at_deliveryorder as do", "do.CustPONumber = po.POrdNumber", "INNER");
        $this->db->join("at_dorddetail as dod", "dod.DOrdNumber = do.DOrdNumber", "INNER");

        $this->db->join("at_preqdetail as prd", "prd.PreqDetailID = pod.PreqDetailID", "INNER");
        $this->db->join("at_purchaserequisition as pr", "prd.PReqNumber = pr.PReqNumber", "INNER");

        $this->db->join("am_item as it", "it.ItemCode = pod.ItemCode", "LEFT");
        $this->db->where('po.POrdNumber', $pord_number);
        $this->db->order_by('pod.POrdDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    //Daswan get detail item to print
    function get_detail_item_print($pord_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("pod.*, pod.ItemQty as ItemQty_Old, it.ItemTypeID, prd.PReqDetailID, 
                           pod.ItemPriceNTax, prd.ItemQtyPO, '0' as IntaxStatus, 0 as ItemModusType,
                         (case 
                              when prd.ItemType = 0 or 1 
                              then ((prd.ItemQty - prd.ItemQtyPO - prd.ItemQtySPD) + pod.ItemQty)
                              else 1 end) as ItemMax,
                         (case when pod.ItemSpdStatus = 0 then 'No' else 'Yes' end) as ItemSpdStatus");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pod', "pod.POrdNumber = po.POrdNumber", "INNER");
        $this->db->join("at_preqdetail as prd", "prd.PreqDetailID = pod.PreqDetailID", "INNER");
        $this->db->join("am_item as it", "it.ItemCode = pod.ItemCode", "LEFT");
        $this->db->where('po.POrdNumber', $pord_number);
        $this->db->order_by('pod.POrdDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result_array();
    }

    function get_detail_distinct($pord_number) {
        $this->db->distinct();
        $this->db->select('pod.PReqNumber, po.PReqDate');
        $this->db->from($this->detail . ' as pod');
        $this->db->join($this->table . ' as po', 'po.POrdNumber = pod.POrdNumber', 'INNER');
        $this->db->where('pod.POrdNumber', $pord_number);
        $this->db->order_by('pod.PReqNumber', 'Asc');
        $query = $this->db->get();

        return $query->result();
    }

    function get_detail_item_group_by_category($id) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("sum(at_porddetail.ItemAmount)as CategoryAmount,am_item.ItemCategoryID");
        $this->db->join("am_item", "am_item.ItemCode = at_porddetail.ItemCode", "INNER");
        $query = $this->db->get_where($this->detail, array('POrdNumber' => $id));
        $this->db->group_by('ItemCategoryID');
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function get_for_ri($VendorCode) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("DATE_FORMAT(POrdDate,'%d-%m-%Y') as PODate,at_purchaseorder.*");
        $query = $this->db->get_where($this->table, array('VendorCode' => $VendorCode,
            'AppLevel1Status' => 1,
            'AppLevel2Status' => 1,
            'TransStatus' => 1,
            'BranchCode' => $this->session->userdata('branch'),
            '(POrdTotalDP-PPayTotalDP)' => 0)
        );

        $this->db->_protect_identifiers = TRUE;

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

    function get_for_ri2($VendorCode) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("DISTINCT DATE_FORMAT(at_purchaseorder.POrdDate,'%d-%m-%Y') as PODate, at_purchaseorder.*");
        $this->db->from($this->table);
        $this->db->join($this->detail, "at_porddetail.POrdNumber = at_purchaseorder.POrdNumber", "INNER");
        $this->db->where(array('at_purchaseorder.VendorCode' => $VendorCode,
            'at_purchaseorder.TransStatus' => 1,
            'at_purchaseorder.BranchCode' => $this->session->userdata('branch'),
            '(at_purchaseorder.POrdTotalDP - at_purchaseorder.PPayTotalDP) = ' => 0,
            '(at_porddetail.ItemQty - at_porddetail.ItemQtySpd - at_porddetail.ItemQtyRI) > ' => 0));
        $query = $this->db->get();

        $this->db->_protect_identifiers = TRUE;

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

    function check_item_po_approved_by_preqnumber($PReq_number) {
        $this->db->select('at_purchaseorder.TransStatus, at_porddetail.ItemQty');
        $this->db->from($this->detail);
        $this->db->join($this->table, "at_porddetail.POrdNumber = at_purchaseorder.POrdNumber", "INNER");

        $this->db->where($this->detail . '.PReqNumber', $PReq_number);
        $this->db->where_in($this->table . '.TransStatus', array(4, 5, 6));
        $this->db->group_by($this->detail . '.PReqNumber');

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

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

//    function get_total_item_po_by_preqnumber($preq_number, $item_code){
//        $this->db->select('sum(pd.ItemQty) as Total_Qty');
//        $this->db->from($this->table . ' po');
//        $this->db->join($this->detail . ' pd', 'pd.POrdNumber = po.POrdNumber', 'INNER');
//        $this->db->where('po.PReqNumber', $preq_number);
//        $this->db->where('pd.ItemCode', $item_code);
//        $this->db->where_in('po.TransStatus', array(1,2));
//        $query = $this->db->get();
//        
//        if ($query->row()->Total_Qty != NULL){
//            return $query->row()->Total_Qty;            
//        }
//        else{
//            return 0;
//        }
//    }
    //pake at ReceiveItem
    function get_detail_item_for_ri($pord_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("po.POrdNumber, po.POrdPPn10Pcnt as PPn10_Pcnt, pd.POrdDetailID, pd.ItemCode, pd.ItemUnit, pd.ItemDisc,pd.ItemCodeVendor, 
                           pd.ItemPrice, pd.ItemQtyRI, pd.ItemDesc, pd.ItemCategoryID, pd.ItemCategoryCode, pd.ItemType, pd.ItemStatus, pd.ItemAmount, pd.ItemTaxPPn10,pd.ItemTotalAmount, 
                          (pd.ItemQty - pd.ItemQtyRI) as ItemQty, (pd.ItemQty - pd.ItemQtyRI) as ItemMax");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pd', 'pd.POrdNumber = po.POrdnumber', 'INNER');
        $this->db->join($this->item . ' as it', 'it.ItemCode = pd.ItemCode', 'LEFT');
        $this->db->join($this->item_category . ' as ic', 'ic.ItemCategoryID = it.ItemCategoryID', 'LEFT');
        $this->db->where_in('po.POrdNumber', $pord_number);
        $this->db->where('(pd.ItemQty - pd.ItemQtySpd - pd.ItemQtyRI) > ', 0);
        $this->db->order_by('pd.POrdDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function get_detail_item_by_id($id) {
        $query = $this->db->get_where($this->detail, array('POrdDetailID' => $id));

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

    function get_all_vendor() {
        $branch_code = $this->session->userdata('branch');

        $this->db->select('*');
        $this->db->from($this->vendor);
        $this->db->where('BranchCode', $branch_code);
        $this->db->where_in('TransStatus', '0,1');
        $this->db->order_by('VendorCode', 'ASC');
        $query = $this->db->get();

        return $query->result();
    }

    function get_branch_address($BranchCode) {
        $query = $this->db->get_where('am_branch', array('BranchCode' => $BranchCode));

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

    function get_ppay_total_dp($pord_number) {
        $this->db->select('PPayTotalDP');
        $this->db->from($this->table);
        $this->db->where('POrdNumber', $pord_number);
        $query = $this->db->get();

        return $query->result();
    }

    function insert_all_table_new($data, $detail, $pord_number) {
        $this->db->trans_start();
        $this->insert($data);
        /*
          Insert Detail PO
         */
        foreach ($detail as $row) {
            $detail_data_po = array(
                'PReqDetailID' => $row->PReqDetailID,
                'PReqNumber' => $row->PReqNumber,
                'POrdNumber' => $pord_number,
                'ItemCode' => $row->ItemCode,
                'ItemDesc' => $row->ItemDesc,
                'itemUnit' => $row->ItemUnit,
                'itemQty' => $row->ItemQty,
                'ItemPrice' => $row->ItemPrice,
                'ItemDisc' => $row->ItemDisc,
                'ItemAmount' => $row->ItemAmount_Hide,
                'ItemTaxPPn10' => $row->Item_PPn10,
                'ItemTaxPPh22' => $row->Item_PPh22,
                'ItemTaxPPh23' => $row->Item_PPh23,
                'ItemTotalAmount' => $row->ItemTotalAmount,
                'ItemCategoryID' => $row->ItemCategoryID,
                'ItemCategoryCode' => $row->ItemCategoryCode,
                'ItemType' => $row->ItemType,
                'ItemStatus' => $row->ItemStatus,
                'ItemPPh22Status' => $row->ItemPPh22Status,
                'ItemPPh23Status' => $row->ItemPPh23Status,
                'ItemAdvNetDueIn' => $row->ItemAdvNetDueIn,
                'ItemPriceNTax' => $row->ItemPriceNTax,
				'ItemCodeVendor' => $row->ItemCodeVendor,
                'LastUser' => $this->session->userdata("username")
            );

            //2. insert PO Detail item data
            $this->insert_detail($detail_data_po);
            //-------------------------------------------------------------------------------------------------//

            $preqdetail = $this->m_purchase_requisition->get_detail_item_by_id($row->PReqDetailID);
            $newItemQtyPO = $preqdetail->ItemQtyPO + $row->ItemQty;

            $detail_data_pr = array(
                'ItemQtyPO' => $newItemQtyPO,
                'LastUser' => $this->session->userdata("username")
            );

            //3. update PReqDetail => item quantity PO
            $this->m_purchase_requisition->update_detail($detail_data_pr, $row->PReqDetailID);
        }

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

    function update_all_new_table($data, $detail_data_arr, $detail_data_preq, $pord_number, $calculate_po_arr, $calculate_pr_arr, $detail_id) {
        $this->db->trans_start();
        $this->update($data, $pord_number);
        for ($i = 0; $i < count($detail_data_arr); $i++) {
            $POrdDetailID = $detail_data_arr[$i]['POrdDetailID'];
            $detail_data = array(
                'ItemQty' => $detail_data_arr[$i]['ItemQty'],
                'ItemPrice' => $detail_data_arr[$i]['ItemPrice'],
                'ItemDisc' => $detail_data_arr[$i]['ItemDisc'],
                'ItemAmount' => $detail_data_arr[$i]['ItemAmount'],
                'ItemTaxPPn10' => $detail_data_arr[$i]['ItemTaxPPn10'],
                'ItemTaxPPh22' => $detail_data_arr[$i]['ItemTaxPPh22'],
                'ItemTaxPPh23' => $detail_data_arr[$i]['ItemTaxPPh23'],
                'ItemTotalAmount' => $detail_data_arr[$i]['ItemTotalAmount'],
                'ItemPriceNTax' => $detail_data_arr[$i]['ItemPriceNTax'],
				'ItemCodeVendor' => $detail_data_arr[$i]['ItemCodeVendor'],
                'LastUser' => $detail_data_arr[$i]['LastUser']
            );
            $this->update_detail($detail_data, $POrdDetailID);
        }

        for ($pr = 0; $pr < count($detail_data_preq); $pr++) {
            $PReqDetailID = $detail_data_preq[$pr]['PReqDetailID'];
            $detail_data_pr = array(
                'ItemQtyPO' => $detail_data_preq[$pr]['ItemQtyPO'],
                'LastUser' => $detail_data_preq[$pr]['LastUser']
            );
            $this->m_purchase_requisition->update_detail($detail_data_pr, $PReqDetailID);
        }

        if (count($detail_id) > 0) {
            for ($calculate_po = 0; $calculate_po < count($calculate_po_arr); $calculate_po++) {
                $detail_data_po = array(
                    'PReqNumber' => $calculate_po_arr[$calculate_po]['PReqNumber'],
                    'PReqDate' => $calculate_po_arr[$calculate_po]['PReqDate'],
                    'LastUser' => $calculate_po_arr[$calculate_po]['LastUser']
                );
                $this->update($detail_data_po, $pord_number);
            }

            for ($calculate_pr = 0; $calculate_pr < count($calculate_pr_arr); $calculate_pr++) {
                $PreqDetailID = $calculate_pr_arr[$calculate_pr]['PreqDetailID'];
                $data_preq_detail = array(
                    'ItemQtyPO' => $calculate_pr_arr[$calculate_pr]['ItemQtyPO'],
                    'LastUser' => $calculate_pr_arr[$calculate_pr]['LastUser']
                );
                $this->m_purchase_requisition->update_detail($data_preq_detail, $PreqDetailID);
            }
        }
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function approval_update_table($arr_data_preq, $arr_data_po, $arr_data_payment, $status, $pord_number) {
        $this->db->trans_start();
        for ($data_preq = 0; $data_preq < count($arr_data_preq); $data_preq++) {
            $PReqNumber = $arr_data_preq[$data_preq]['PReqNumber'];
            $data_preq = array(
                'TransStatus' => $arr_data_preq[$data_preq]['TransStatus'],
                'LastUser' => $arr_data_preq[$data_preq]['LastUser']
            );
            $this->m_purchase_requisition->update($data_preq, $PReqNumber);
        }

        for ($data_dp = 0; $data_dp < count($arr_data_payment); $data_dp++) {
            $data_payment = array(
                'BranchCode' => $arr_data_payment[$data_dp]['BranchCode'],
                'VendorCode' => $arr_data_payment[$data_dp]['VendorCode'],
                'InvoiceNumber' => $arr_data_payment[$data_dp]['InvoiceNumber'],
                'InvoiceDate' => $arr_data_payment[$data_dp]['InvoiceDate'],
                'InvoiceCurrCode' => $arr_data_payment[$data_dp]['InvoiceCurrCode'],
                'InvoiceCurrRate' => $arr_data_payment[$data_dp]['InvoiceCurrRate'],
                'InvoiceFiscalRate' => $arr_data_payment[$data_dp]['InvoiceFiscalRate'],
                'InvoicePurchase' => $arr_data_payment[$data_dp]['InvoicePurchase'],
                'InvoiceTotalDP' => $arr_data_payment[$data_dp]['InvoiceTotalDP'],
                'InvoiceAmount' => $arr_data_payment[$data_dp]['InvoiceAmount'],
                'InvoiceOwing' => $arr_data_payment[$data_dp]['InvoiceOwing'],
                'ItemCategoryRatio' => $arr_data_payment[$data_dp]['ItemCategoryRatio'],
                'ItemCategoryID' => $arr_data_payment[$data_dp]['ItemCategoryID'],
                'ItemCategoryCode' => $arr_data_payment[$data_dp]['ItemCategoryCode'],
                'ItemType' => $arr_data_payment[$data_dp]['ItemType'],
                'ItemStatus' => $arr_data_payment[$data_dp]['ItemStatus'],
                'InvoiceType' => $arr_data_payment[$data_dp]['InvoiceType'],
                'PPnFiscalStatus' => $arr_data_payment[$data_dp]['PPnFiscalStatus'],
                'LastUser' => $arr_data_payment[$data_dp]['LastUser'],
            );
            $this->insert_payment($data_payment);
        }

        if ($status == 1) {
            for ($data_po = 0; $data_po < count($arr_data_po); $data_po++) {
                $data_trans_po = array(
                    'TransStatus' => $arr_data_po[$data_po]['TransStatus'],
                    'AppLevel1Status' => $arr_data_po[$data_po]['AppLevel1Status'],
                    'AppLevel1Code' => $arr_data_po[$data_po]['AppLevel1Code'],
                    'AppLevel1Date' => $arr_data_po[$data_po]['AppLevel1Date'],
                    'LastUser' => $arr_data_po[$data_po]['LastUser'],
                );
                $this->update($data_trans_po, $pord_number);
            }
        } else {
            for ($data_po = 0; $data_po < count($arr_data_po); $data_po++) {
                $data_trans_po = array(
                    'TransStatus' => $arr_data_po[$data_po]['TransStatus'],
                    'AppLevel2Status' => $arr_data_po[$data_po]['AppLevel2Status'],
                    'AppLevel2Code' => $arr_data_po[$data_po]['AppLevel2Code'],
                    'AppLevel2Date' => $arr_data_po[$data_po]['AppLevel2Date'],
                    'LastUser' => $arr_data_po[$data_po]['LastUser'],
                );
                $this->update($data_trans_po, $pord_number);
            }
        }
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function suspend_data($data_update, $arr_detail_pr, $pord_number) {
        $this->db->trans_start();
        $this->update($data_update, $pord_number);
        for ($data_preq = 0; $data_preq < count($arr_detail_pr); $data_preq++) {
            $PReqDetailID = $arr_detail_pr[$data_preq]['PReqDetailID'];
			$PReqNumber = $arr_detail_pr[$data_preq]['PReqNumber'];
			
            $detail_preq = array(
                'ItemQtyPO' => $arr_detail_pr[$data_preq]['ItemQtyPO'],
                'LastUser' => $arr_detail_pr[$data_preq]['LastUser']
            );

            $this->m_purchase_requisition->update_detail($detail_preq, $PReqDetailID);
        }
		
		$this->update($data_update, $pord_number);
		
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function update_group_new($arr_update_qty_suspend, $arr_update_trans_status, $pord_number) {
        $this->db->trans_start();
        for ($data_item = 0; $data_item < count($arr_update_qty_suspend); $data_item++) {
            $POrdDetailID = $arr_update_qty_suspend[$data_item]['POrdDetailID'];

            $data_preq = array(
                'ItemQtySpd' => $arr_update_qty_suspend[$data_item]['ItemQtySpd'],
                'ItemSpdStatus' => $arr_update_qty_suspend[$data_item]['ItemSpdStatus'],
                'LastUser' => $arr_update_qty_suspend[$data_item]['LastUser']
            );
            $this->update_detail($data_preq, $POrdDetailID);
        }

        for ($data_group = 0; $data_group < count($arr_update_trans_status); $data_group++) {
            $data = array(
                'TransStatus' => $arr_update_trans_status[$data_group]['TransStatus'],
                'LastUser' => $arr_update_trans_status[$data_group]['LastUser']
            );
            $this->update($data, $pord_number);
        }

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

    function approved_by_pass($trans_data) {
        $this->db->trans_start();
        for ($x = 0; $x < count($trans_data['update_payment']['data']); $x++) {
            $this->update_invoice_payment($trans_data['update_payment']['data'][$x], $trans_data['update_payment']['POrdNumber'][$x]);
        }

        $this->update($trans_data['update_group']['data'], $trans_data['update_group']['POrdNumber']);
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function approved_reverse($trans_data) {
        $this->db->trans_start();
        $this->update($trans_data['reverse_po']['data'], $trans_data['reverse_po']['POrdNumber']);
		for ($x = 0; $x < count($trans_data['update_group']['data']); $x++) {
            $this->m_purchase_requisition->update($trans_data['update_group']['data'][$x], $trans_data['update_group']['PReqNumber'][$x]);
        }
		
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function update_detail_new($data, $POrdDetailID) {
        $this->update_detail($data, $POrdDetailID);
    }

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

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

    function insert_payment($data) {
        $this->db->insert($this->table_payment, $data);
    }

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

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

    function update_detail_recur($data, $id) {
        $this->db->update($this->detailrecur, $data, array('POrdDetailRecurID' => $id));
    }

    function delete($id) {
        $this->db->delete($this->table, array('POrdNumber' => $id));
    }

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

    function update_invoice_payment($data, $id) {
        $this->db->update($this->table_payment, $data, array('InvoiceNumber' => $id));
    }

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

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

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

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

        $pord_number = $branch_code . "/" . $month . $year . "PO/";

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

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

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

            $new_po_number = $pord_number . $number;
        }
        return $new_po_number;
    }

    function get_qty_receive_item($id, $prec_number) {
        $this->db->select('sum(at_precdetail.ItemQty) as TotalQtyRI_All');
        $this->db->from('at_precdetail');
        $this->db->where('at_precdetail.POrdNumber', $id);
        $this->db->where('at_precdetail.PRecNumber', $prec_number);

        $this->db->group_by('at_precdetail.POrdNumber');

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

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

    function set_finish($id) {

        $this->db->select('sum(at_precdetail.ItemQty) as TotalQtyRI');
        $this->db->from('at_precdetail');
        $this->db->join('at_receiveitem', 'at_receiveitem.PRecNumber = at_precdetail.PRecNumber', 'INNER');
        $this->db->where('at_precdetail.POrdNumber', $id);
        $this->db->where_in('at_receiveitem.TransStatus', array(0, 1, 2));
        //$this->db->group_by('at_precdetail.PRecNumber');

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

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

    function get_total_qty_po_spd($id) {

        $this->db->select('sum(at_porddetail.ItemQtySpd) as TotalQtySpd');
        $this->db->from('at_purchaseorder');
        $this->db->join('at_porddetail', 'at_porddetail.POrdNumber = at_porddetail.POrdNumber', 'INNER');
        $this->db->where('at_purchaseorder.POrdNumber', $id);
		$this->db->where('at_porddetail.POrdNumber', $id);
        $this->db->where_in('at_purchaseorder.TransStatus', array(0, 1, 2));
        //$this->db->group_by('at_porddetail.POrdNumber');

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

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

    function set_finish_po($id) {
        $this->db->select('sum(at_porddetail.ItemQty) as TotalQtyPO, at_purchaseorder.TransStatus, sum(at_porddetail.ItemQtyRI + at_porddetail.ItemQtySpd) as TotalQtyRI, at_porddetail.ItemQty as TotalQtyPONew');
        $this->db->from('at_porddetail');
        $this->db->join('at_purchaseorder', 'at_purchaseorder.POrdNumber = at_porddetail.POrdNumber', 'INNER');
        $this->db->where('at_purchaseorder.POrdNumber', $id);
        $this->db->where_in('at_purchaseorder.TransStatus', array(1, 2));
        $query_pr = $this->db->get();
        if ($query_pr->num_rows() > 0) {
            return $query_pr->row();
        } else {
            return false;
        }
    }

    /* function set_finish($id) {
      $this->db->select('at_porddetail.ItemQty - (at_porddetail.ItemQtyRI + at_porddetail.ItemQtySpd) as TotalQty');
      $this->db->from('at_porddetail');
      $this->db->where('at_porddetail.POrdNumber', $id);
      $query = $this->db->get();

      if($query->num_rows() > 0){
      $data = $query->row();

      if($data->TotalQty == 0){
      $tran_status = 2;
      }
      else{
      $tran_status = 1;
      }

      $data_po = array (
      'TransStatus'   => $tran_status,
      'LastUser'      => $this->session->userdata("username")
      );

      $this->db->update($this->table, $data_po, array('POrdNumber'=>$id));

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

    function set_on_progress_dp_paid($id) {
        $this->db->select('(POrdTotalDP - PPayTotalDP) as TotalDP');
        $this->db->from('at_purchaseorder');
        $this->db->where('at_purchaseorder.POrdNumber', $id);
        $query = $this->db->get();

        if ($query->num_rows() > 0) {
            $data = $query->row();

            if ($data->TotalDP == 0) {
                $data_po = array(
                    'TransStatus' => 1,
                    'LastUser' => $this->session->userdata("username")
                );

                $this->db->update($this->table, $data_po, array('POrdNumber' => $id));
            } else {
                return 1;
            }
        } else {
            return 1;
        }
    }

    public function check_pord_app_status($PReqNumber) {
        $finish_preq = 0;

        $this->db->select('at_purchaseorder.TransStatus');
        $this->db->from($this->table);
        $this->db->join($this->detail, 'at_porddetail.POrdNumber=at_purchaseorder.POrdNumber', 'INNER');
        $this->db->where('at_porddetail.PReqNumber', $PReqNumber);

        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            $result = $query->result();
            foreach ($result as $row) {
                if (in_array($row->TransStatus, array(0, 1, 2))) {
                    $finish_preq = 1;
                }
            }

            if ($finish_preq == 0) {
                return 0;
            } else {
                return 1;
            }
        } else {
            return 0;
        }
    }

    /* ======================lemparan dari modul item master saat suspen data============================== */

    function get_pord_detail_by_item($item_code) {
        $this->db->select('at_porddetail.ItemCode');
        $this->db->from('at_porddetail');
        $this->db->join('at_purchaseorder', 'at_purchaseorder.POrdNumber = at_porddetail.POrdNumber', 'INNER');

        $this->db->where('at_porddetail.ItemCode', $item_code);
        $this->db->where_in('at_purchaseorder.TransStatus', array(1, 4, 5, 6));
        $query = $this->db->get();

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

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

    function check_approved_by_transstatus($POrdNumber) {
        $this->db->select('POrdNumber');
        $this->db->from($this->table);
        $this->db->where('POrdNumber', $POrdNumber);
        $this->db->where('TransStatus', 1);
        $query = $this->db->get();

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

    function get_purchase_order_by_transtatus($po_number = '') {
        $this->db->distinct();
        $this->db->select('at_purchaseorder.POrdNumber');
        $this->db->from($this->table);
        $this->db->join('at_porddetail', 'at_porddetail.POrdNumber = at_purchaseorder.POrdNumber', 'INNER');

        if ($po_number != "") {
            $this->db->where('at_purchaseorder.POrdNumber', $po_number);
        }
        $this->db->where('at_purchaseorder.TransStatus', 1);
        $this->db->where('(at_porddetail.ItemQty - at_porddetail.ItemQtyRI) >', 0);
        $this->db->where('at_purchaseorder.BranchCode', $this->session->userdata("branch"));
        $query = $this->db->get();

        return $query->result();
    }

    function get_purchase_order_by_do($po_number = '') {
        $this->db->select('POrdNumber, VendorCode, POrdDate, POrdNumber, ShipmentID, 
							TermsPaymentID, FOBID, CurrencyCode, CurrencyRate, POrdSubTotal, POrdPPn10Pcnt, POrdPPn10, POrdTaxesStatus, POrdInTaxStatus, POrdTotalAmount');
        $this->db->from($this->table);
        if ($po_number != "") {
            $this->db->where('POrdNumber', $po_number);
        }
        $this->db->where('TransStatus', 1);
        $this->db->where('BranchCode', $this->session->userdata("branch"));
        $query = $this->db->get();

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

    function get_detail_sum_pord($POrdDetailID, $ItemCode) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("(pod.ItemQty) as ItemQtyPO, (pod.ItemQtyRI + pod.ItemQtySpd) as ItemQtyRI, pod.ItemCode, (pod.ItemQty-(pod.ItemQtyRI + pod.ItemQtySpd)) as ItemQtyAllPo, (pod.ItemQtyRI) as ItemQty_RI, pod.ItemQtySpd");
        $this->db->from($this->table . ' as po');
        $this->db->join($this->detail . ' as pod', "pod.POrdNumber = po.POrdNumber", "INNER");
        $this->db->where('pod.POrdDetailID', $POrdDetailID);
		$this->db->where('pod.ItemCode', $ItemCode);

        $this->db->where_in('po.TransStatus', array(1, 2));

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

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

    function get_detail_item_po($id) {
        $query = $this->db->get_where($this->detail, array('POrdDetailID' => $id));

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

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

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

    function get_invoice_payment($POrdNumber) {
        $this->db->select('tp.ItemCategoryRatio, tp.InvoiceOwing, tp.PaymentAmount, tp.PaymentRounded, tp.InvoiceAmount');
        $this->db->from($this->table_payment . ' as tp');

        $this->db->where('tp.InvoiceNumber', $POrdNumber);
        $query = $this->db->get();

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

    function get_list_price_by_itemcode($ItemCode,$limit) {
        $this->db->select('gr.PInvNumber,gr.PInvDate,dt.ItemCode,dt.ItemDesc,dt.ItemPrice,dt.ItemUnit,gr.TransStatus');
        $this->db->from($this->PInvDetail . ' as dt');
        $this->db->join($this->PInvoice . ' as gr', 'dt.PInvNumber=gr.PInvNumber', 'left');
        $this->db->where('dt.ItemCode', $ItemCode);
        $this->db->where_in('gr.TransStatus', array(1, 2, 4, 5, 6));
        $this->db->order_by('gr.CreatedAt', 'ASC');
        $this->db->limit($limit, 0);

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

    function get_list_receipt_by_itemcode($ItemCode, $POrdNumber) {
        $this->db->select('gr.PRecNumber,gr.PRecDate,dt.ItemCode,dt.ItemDesc,dt.ItemQty,dt.ItemUnit,gr.TransStatus');
        $this->db->from($this->PRecDetail . ' as dt');
        $this->db->join($this->PReceipt . ' as gr', 'dt.PRecNumber=gr.PRecNumber', 'left');
        $this->db->where('dt.ItemCode', $ItemCode);
        $this->db->where('gr.POrdNumber', $POrdNumber);
        $this->db->where_in('gr.TransStatus', array(1, 2, 4, 5, 6));
        $this->db->order_by('gr.CreatedAt', 'ASC');

        $query = $this->db->get()->result_array();
        return $query;
    }
	
	function get_old_no_transaaction($id){
		$this->db->select('OldPOrdNumber');
        $this->db->from('at_purchaseorder');
        
        $this->db->where('at_purchaseorder.POrdNumber', $id);
        $query_pr = $this->db->get();
        if ($query_pr->num_rows() > 0) {
            return $query_pr->row();
        } else {
            return false;
        }
	}

}

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