<?php

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

class M_purchase_return extends CI_Model {

    public $table = 'at_purchasereturn';
    public $detail = 'at_pretdetail';
    public $pinv_detail = 'at_pinvdetail';
    public $journal = 'at_pretjournal';
    public $branch = "am_branch";
    public $company = "am_company";
    public $account_gl = 'am_accountgl';
    public $vendor = 'am_vendor';
    public $employee = "am_employee";
    public $shipment = "am_shipment";
    public $termspayment = "am_termspayment";

    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_purchasereturn.*, am_branch.BranchName, 
							(case when at_purchasereturn.TransStatus=1 then 'On Progress'
                            when at_purchasereturn.TransStatus=2 then 'Finished'
                            when at_purchasereturn.TransStatus=3 then 'Susppend'
                            when at_purchasereturn.TransStatus=4 then 'Managerial App'
                            when at_purchasereturn.TransStatus=5 then 'Direksi APP'
                            when at_purchasereturn.TransStatus=6 then 'MGR & DIR App'
                            else 'Waiting' end) as Status,
							am_vendor.VendorName, am_employee.EmployeeName as CreatedBy");
        $this->db->from($this->table);
        $this->db->join('am_vendor', 'at_purchasereturn.VendorCode=am_vendor.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchasereturn.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee', 'am_employee.EmployeeCode=at_purchasereturn.CreatedBy', 'INNER');

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

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

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

        /* =====================================================find by status================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('at_purchasereturn.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_purchasereturn.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 . '.PRetNumber', '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'];
        $data_filter['cmb_VendorCode']!=null?$VendorCode = $data_filter['cmb_VendorCode']:$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_purchasereturn.*, am_branch.BranchName, 
							(case when at_purchasereturn.TransStatus=1 then 'On Progress'
                            when at_purchasereturn.TransStatus=2 then 'Finished'
                            when at_purchasereturn.TransStatus=3 then 'Susppend'
                            when at_purchasereturn.TransStatus=4 then 'Need Managerial App'
                            when at_purchasereturn.TransStatus=5 then 'Need Direksi App'
                            when at_purchasereturn.TransStatus=6 then 'Need MGR & DIR App'
                            else 'Waiting' end) as Status,
							am_vendor.VendorName, am_employee.EmployeeName as CreatedBy");
        $this->db->from($this->table);
        $this->db->join('am_vendor', 'at_purchasereturn.VendorCode=am_vendor.VendorCode', 'INNER');
        $this->db->join('am_branch', 'at_purchasereturn.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_employee', 'am_employee.EmployeeCode=at_purchasereturn.CreatedBy', 'INNER');

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

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

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

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

    function get_detail($pret_number) {
        $this->db->select('pret.*, vnd.VendorAddress, am_branch.BranchName, am_company.CompanyName');
        $this->db->from($this->table . ' pret');
        $this->db->join($this->vendor . ' vnd', 'vnd.VendorCode = pret.VendorCode', 'INNER');
        $this->db->join('am_branch', 'pret.BranchCode=am_branch.BranchCode', 'INNER');
        $this->db->join('am_company', 'am_company.CompanyCode=am_branch.CompanyCode', 'INNER');

        $this->db->where('pret.PRetNumber', $pret_number);
        $query = $this->db->get();

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

    //Daswan get detail print
    function get_detail_print($pret_number) {
        // $this->db->select('pret.*, vnd.VendorAddress');
        // $this->db->from($this->table . ' pret');
        // $this->db->join($this->vendor . ' vnd','vnd.VendorCode = pret.VendorCode', 'INNER');
        // $this->db->where('pret.PRetNumber', $pret_number);
        // $query = $this->db->get();
        // if($query->num_rows() > 0){
        //     return $query->row();
        // }
        // else{
        //     return false;
        // }   
        $this->db->select('pret.*, br.BranchName, cp.CompanyName, vd.VendorName, vd.PhoneNumber,vd.SaldoDPBalance, vd.SaldoDPUsed, cr.EmployeeName as nm_prepared, mng.EmployeeName as nm_manager');
        $this->db->from($this->table . ' as pret');
        $this->db->join($this->branch . ' as br', 'br.BranchCode = pret.BranchCode', 'INNER');
        $this->db->join($this->company . ' as cp', 'cp.CompanyCode = br.CompanyCode', 'INNER');
        $this->db->join($this->vendor . ' vd', 'vd.VendorCode = pret.VendorCode', 'INNER');
        $this->db->join($this->employee . ' as cr', 'cr.EmployeeCode = pret.CreatedBy', 'LEFT');
        $this->db->join($this->employee . ' as mng', 'mng.EmployeeCode = pret.AppLevel1Code', 'LEFT');
        // $this->db->join($this->employee . ' as dir', 'dir.EmployeeCode = pi.AppLevel2Code', 'LEFT');
        // $this->db->join($this->shipment . ' as ship', 'ship.ShipmentID = pret.ShipmentID', 'LEFT');
        // $this->db->join($this->termspayment . ' as payment', 'payment.TermspaymentID = pret.TermspaymentID', 'LEFT');
        $this->db->where('PRetNumber', $pret_number);
        $query = $this->db->get();

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

    /* function get_detail_item($pret_number, $pinv_number){
      $this->db->_protect_identifiers = FALSE;
      $query_select   = "SELECT 'Yes' as Paid, pret_det.PRecNumber, pret_det.ItemCode, pret_det.ItemDesc, pret_det.InvoiceQty, pret_det.ItemQty as Item_Qty,
      pret_det.ItemUnit, pret_det.ItemPrice, pret_det.ItemAmount as Item_Amount, pret_det.ItemTaxPPn10 as Item_TaxPPn10, pret_det.ItemTaxPPh22 as Item_TaxPPh22,
      pret_det.ItemTotalAmount as Item_TotalAmount, pret_det.ItemPPh22Status, pret_det.PRetDetailID, pret_det.PInvDetailID, pret_det.ItemCategoryID,
      pret_det.ItemCategoryCode, pinv_det.ReturnQty as PInvReturnQty, pret_det.ItemCode as Item_Code, pret_det.ItemAssetStatus, pret_det.ItemAssetCode
      FROM at_pretdetail as pret_det
      INNER JOIN at_pinvdetail as pinv_det ON pinv_det.PInvDetailID = pret_det.PInvDetailID
      WHERE pret_det.PRetNumber = '" . $pret_number . "'
      UNION
      SELECT 'No' as Paid, PRecNumber, ItemCode, ItemDesc, ItemQty as InvoiceQty, '0' as Item_Qty,
      ItemUnit, ItemPrice, '0' as Item_Amount, '0' as Item_TaxPPn10, '0' as Item_TaxPPh22,
      '0' as Item_TotalAmount, ItemPPh22Status, '0' as PRetDetailID, PInvDetailID, ItemCategoryID,
      ItemCategoryCode, ReturnQty as PInvReturnQty, ItemCode as Item_Code, ItemAssetStatus, '' as ItemAssetCode
      FROM at_pinvdetail pinv_det
      WHERE pinv_det.PInvNumber = '" . $pinv_number . "'
      AND NOT pinv_det.PInvDetailID IN (SELECT PInvDetailID FROM at_pretdetail where PRetNumber = '" . $pret_number . "')
      ORDER BY PInvDetailID ASC";

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

      return $query->result();
      } */

    function get_detail_item($pret_number, $pinv_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("pretd.PInvDetailID, pretd.PInvNumber, pretd.PRecNumber, pretd.PRecNumber as PRecNumber_Edit, pretd.PRetNumber,pretd.PRetDetailID, pinv_det.ItemStatus,pinv_det.ItemType, 
							pretd.ItemCode as Item_Code,pretd.ItemCode, pretd.ItemDesc,  pretd.InvoiceQty, pretd.ItemQty as Item_Qty, pretd.ItemUnit, pretd.ItemDiscPcnt as ItemDisc,
							pretd.ItemPrice, pretd.ItemAmount as Item_Amount, pretd.ItemTaxPPn10 as Item_TaxPPn10, pretd.ItemTaxPPh22 as Item_TaxPPh22, pretd.ItemTotalAmount as Item_TotalAmount, 
							pretd.ItemCategoryID, pretd.ItemCategoryCode, pretd.ItemAssetStatus, pretd.ItemAssetCode, pretd.ItemPPh22Status, 
							pinv_det.ReturnQty as PInvReturnQty, pretd.ItemPrice as ItemPrice_Hide, pretd.ItemAmount as ItemAmount_Hide, pretd.ItemTaxPPn10 as Item_TaxPPn10_Hide,
							pretd.ItemTaxPPh22 as Item_TaxPPh22_Hide, pretd.ItemTotalAmount as Item_TotalAmount_Hide");
        $this->db->from($this->detail . ' as pretd');
        $this->db->join('at_pinvdetail as pinv_det', 'pinv_det.PInvDetailID=pretd.PInvDetailID', 'INNER');
        $this->db->where('pretd.PRetNumber', $pret_number);
        $this->db->where('pretd.PInvNumber', $pinv_number);
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function get_detail_item_print($pret_number, $pinv_number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("pretd.PInvDetailID, pretd.PInvNumber, pretd.PRecNumber, pretd.PRetNumber,pretd.PRetDetailID, 
							pretd.ItemCode as Item_Code,pretd.ItemCode, pretd.ItemDesc,  pretd.InvoiceQty, pretd.ItemQty as Item_Qty, pretd.ItemUnit, pretd.ItemDiscPcnt,
							pretd.ItemPrice, pretd.ItemAmount as Item_Amount, pretd.ItemTaxPPn10 as Item_TaxPPn10, pretd.ItemTaxPPh22 as Item_TaxPPh22, pretd.ItemTotalAmount as Item_TotalAmount, 
							pretd.ItemCategoryID, pretd.ItemCategoryCode, pretd.ItemAssetStatus, pretd.ItemAssetCode, pretd.ItemPPh22Status, 
							pinv_det.ReturnQty as PInvReturnQty, pretd.ItemPrice as ItemPrice_Hide, pretd.ItemAmount as ItemAmount_Hide, pretd.ItemTaxPPn10 as Item_TaxPPn10_Hide,
							pretd.ItemTaxPPh22 as Item_TaxPPh22_Hide, pretd.ItemTotalAmount as Item_TotalAmount_Hide,pinv_det.ItemStatus");
        $this->db->from($this->detail . ' as pretd');
        $this->db->join('at_pinvdetail as pinv_det', 'pinv_det.PInvDetailID=pretd.PInvDetailID', 'INNER');
        $this->db->where('pretd.PRetNumber', $pret_number);
        $this->db->where('pretd.PInvNumber', $pinv_number);
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result_array();
    }

    // Daswan get detail item print
    /* function get_detail_item_print($pret_number, $pinv_number){
      $this->db->_protect_identifiers = FALSE;
      $query_select   = "SELECT 'Yes' as Paid, pret_det.PRecNumber, pret_det.ItemCode, pret_det.ItemDesc, pret_det.InvoiceQty, pret_det.ItemQty as Item_Qty,
      pret_det.ItemUnit, pret_det.ItemPrice, pret_det.ItemAmount as Item_Amount, pret_det.ItemTaxPPn10 as Item_TaxPPn10, pret_det.ItemTaxPPh22 as Item_TaxPPh22,
      pret_det.ItemTotalAmount as Item_TotalAmount, pret_det.ItemPPh22Status, pret_det.PRetDetailID, pret_det.PInvDetailID, pret_det.ItemCategoryID,
      pret_det.ItemCategoryCode, pinv_det.ReturnQty as PInvReturnQty, pret_det.ItemCode as Item_Code, pret_det.ItemAssetStatus, pret_det.ItemAssetCode
      FROM at_pretdetail as pret_det
      INNER JOIN at_pinvdetail as pinv_det ON pinv_det.PInvDetailID = pret_det.PInvDetailID
      WHERE pret_det.PRetNumber = '" . $pret_number . "'
      UNION
      SELECT 'No' as Paid, PRecNumber, ItemCode, ItemDesc, ItemQty as InvoiceQty, '0' as Item_Qty,
      ItemUnit, ItemPrice, '0' as Item_Amount, '0' as Item_TaxPPn10, '0' as Item_TaxPPh22,
      '0' as Item_TotalAmount, ItemPPh22Status, '0' as PRetDetailID, PInvDetailID, ItemCategoryID,
      ItemCategoryCode, ReturnQty as PInvReturnQty, ItemCode as Item_Code, ItemAssetStatus, '' as ItemAssetCode
      FROM at_pinvdetail pinv_det
      WHERE pinv_det.PInvNumber = '" . $pinv_number . "'
      AND NOT pinv_det.PInvDetailID IN (SELECT PInvDetailID FROM at_pretdetail where PRetNumber = '" . $pret_number . "')
      ORDER BY PInvDetailID ASC";

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

      return $query->result_array();
      } */

    function get_journal_by_number($Number) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("at_pretjournal.*,am_accountgl.AccountNumber,am_accountgl.AccountName");
        $this->db->join($this->account_gl, "am_accountgl.AccountNumber=at_pretjournal.PRetAccountNumber", "INNER");
        $this->db->order_by('at_pretjournal.PRetSaldoCredit', 'ASC');
        $query = $this->db->get_where($this->journal, array('PRetNumber' => $Number));

        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

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

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

    function check_detail_code_exist($pret_number, $item_code) {
        $this->db->select('*');
        $this->db->from($this->detail);
        $this->db->where('PRetNumber', $pret_number);
        $this->db->where('ItemCode', $item_code);
        $query = $this->db->get();

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

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

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

        $pu_number = $branch . "/" . $month . $year . "PU/";

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

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

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

            $new_pu_number = $pu_number . $number;
        }

        return $new_pu_number;
    }
	
	function reverse_trasaction($transaction_data) {
        $this->db->trans_start();
        if (!empty($transaction_data['update_inventory']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_inventory']['data']); $x++) {
                $this->m_inventories->update($transaction_data['update_inventory']['data'][$x], $transaction_data['update_inventory']['ItemCode'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_assset_code']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_assset_code']['data']); $x++) {
                $this->m_inventories->update_detail($transaction_data['update_assset_code']['data'][$x], $transaction_data['update_assset_code']['AssetCode'][$x]);
            }
        }
		
		if (!empty($transaction_data['update_data_recur']['data'])) {
            for ($x = 0; $x < count($transaction_data['update_data_recur']['data']); $x++) {
                $this->update_recur($transaction_data['update_data_recur']['data'][$x], $transaction_data['update_data_recur']['ItemDesc'][$x], $transaction_data['update_data_recur']['PInvNumber'][$x]);
            }
        }
				
		for ($x = 0; $x < count($transaction_data['update_qty_invoice']['data']); $x++) {
			$this->m_purchase_invoice->update_detail($transaction_data['update_qty_invoice']['data'][$x], $transaction_data['update_qty_invoice']['PInvDetailID'][$x]);
		}
		
		$this->delete_pordetaildp($transaction_data['delete_pordetaildp']['PPayNumber']);
		
		$this->update($transaction_data['update_group_return']['data'], $transaction_data['update_group_return']['PRetNumber']);
		
		$this->m_purchase_invoice->update($transaction_data['update_group_invoice']['data'], $transaction_data['update_group_invoice']['PInvNumber']);
			
        $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 update($data, $pret_number) {
        $this->db->update($this->table, $data, array('PRetNumber' => $pret_number));
    }

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

    function update_journal($data, $PRetNumber, $PRetAccountNumber) {
        $this->db->update($this->journal, $data, array('PRetNumber' => $PRetNumber, 'PRetAccountNumber' => $PRetAccountNumber));
    }

    function update_recur($data, $ItemDesc, $pinv_number) {
        $this->db->update('at_pinvdetailrecur', $data, array('ItemDesc' => $ItemDesc, 'PinvNumber' => $pinv_number));
    }

    function delete_detail($pret_number) {
        $this->db->delete($this->detail, array('PRetNumber' => $pret_number));
    }
	
	function delete_pordetaildp($PPayNumber) {
        $this->db->delete('at_pordetaildp', array('PPayNumber' => $PPayNumber));
    }
	
    function delete_detail_by_id($PRetDetailID) {
        $this->db->delete($this->detail, array('PRetDetailID' => $PRetDetailID));
    }

    function delete_detail_recur($ItemCode, $pinv_number) {
        $this->db->delete('at_pinvdetailrecur', array('ItemCode' => $ItemCode, 'PinvNumber' => $pinv_number));
    }

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

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

    function get_invoice_detail($pinv_detail_id) {
        $this->db->select('pinv_detail.ReturnQty, pinv_detail.ItemQty, pinv_detail.ItemCode');
        $this->db->from('at_pinvdetail as pinv_detail');
        $this->db->where('pinv_detail.PInvDetailID', $pinv_detail_id);
        $query = $this->db->get();

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

    function get_journal_hutang_dagang($AccountNumber, $TransNumber) {
        $this->db->select('PRetAccountNumber, PRetSaldoDebet,PRetSaldoCredit, AmountCurrency');
        $this->db->from('at_pretjournal as pretj');

        $this->db->where('pretj.PRetAccountNumber', $AccountNumber);
        $this->db->where('pretj.PRetNumber', $TransNumber);

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

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

    function get_recur_detail($PinvNumber, $ItemDesc) {
        $this->db->select('precur.PaymentAmount');
        $this->db->from('at_pinvdetailrecur as precur');

        $this->db->where('precur.PInvNumber', $PinvNumber);
        $this->db->where('precur.ItemDesc', $ItemDesc);

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

        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return FALSE;
        }
    }
	
	function get_detail_invoice($Pord_number){
        $this->db->_protect_identifiers = false;
        $this->db->select("ppd.PInvNumber as Invoice_Number, pp.PPayNumber as PPayNumber");
        $this->db->from('at_purchasepayment as pp');
        $this->db->join('at_ppaydetail as ppd', 'ppd.PPayNumber = pp.PPayNumber', 'LEFT');
        $this->db->where('ppd.POrdNumber', $Pord_number);
        $this->db->group_by('Invoice_Number');
        $this->db->order_by('PInvNumber', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = false;
        
        if ($query->num_rows() > 0) {
            return $query->row();
        }
        else {
            return false;
        }	
    }

}

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