<?php

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

class M_purchase_requisition extends CI_Model {

    public $table = "at_purchaserequisition";
    public $detail = "at_preqdetail";
    public $item = "am_item";
    public $item_category = "am_itemcategory";
    public $department = "am_department";
    public $employee = "am_employee";
    public $branch = "am_branch";
    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'] : '';
        /* ============================================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_purchaserequisition.*, 
							(case 
								when at_purchaserequisition.TransStatus = 0 then 'Waiting' 
								when at_purchaserequisition.TransStatus = 1 then 'On Progress' 
								when at_purchaserequisition.TransStatus = 2 then 'Finished' 
								when at_purchaserequisition.TransStatus = 3 then 'Suspended'
								when at_purchaserequisition.TransStatus = 4 then 'Need App. Mgr.'  
								when at_purchaserequisition.TransStatus = 5 then 'Need App. Dir.' 
								when at_purchaserequisition.TransStatus = 6 then 'App. Dir & Mgr' end) as Status,
							am_department.DepartmentName, am_branch.BranchName, am_employee.EmployeeName as CreatedBy");
        $this->db->from($this->table);
        $this->db->join('am_department', 'at_purchaserequisition.DepartmentCode=am_department.DepartmentCode', 'INNER');
        $this->db->join('am_employee', 'am_employee.EmployeeCode=at_purchaserequisition.CreatedBy', 'INNER');
        $this->db->join('am_branch', 'at_purchaserequisition.BranchCode=am_branch.BranchCode', 'INNER');

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

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

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

        /* =====================================================find by status================================================== */
        if ($TransStatus != '') {
            $this->db->where_in('at_purchaserequisition.TransStatus', $TransStatus);
        } else {
            /*
              trans status 0,1 adalah aktif
             */
            $this->db->where_in('at_purchaserequisition.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 . '.PReqNumber', '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'];
        /* ============================================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_purchaserequisition.*, 
							(case 
								when at_purchaserequisition.TransStatus = 0 then 'Waiting' 
								when at_purchaserequisition.TransStatus = 1 then 'On Progress' 
								when at_purchaserequisition.TransStatus = 2 then 'Finished' 
								when at_purchaserequisition.TransStatus = 3 then 'Suspended'
								when at_purchaserequisition.TransStatus = 4 then 'Need App. Mgr.'  
								when at_purchaserequisition.TransStatus = 5 then 'Need App. Dir.' 
								when at_purchaserequisition.TransStatus = 6 then 'App. Dir & Mgr' end) as TransStatus,
							am_department.DepartmentName, am_branch.BranchName, am_employee.EmployeeName as CreatedBy");
        $this->db->from($this->table);
        $this->db->join('am_department', 'at_purchaserequisition.DepartmentCode=am_department.DepartmentCode', 'INNER');
        $this->db->join('am_employee', 'am_employee.EmployeeCode=at_purchaserequisition.CreatedBy', 'INNER');
        $this->db->join('am_branch', 'at_purchaserequisition.BranchCode=am_branch.BranchCode', 'INNER');

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

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

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

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

//  cancel to use, due to was already appears in cutom/get data/search item    
//    function search_item($item_category_id, $item_code, $item_name){
//        $this->db->_protect_identifiers = true;
//        $this->db->select("it.*, ItemPPhType as ItemPPh22Status, '0' ItemPPh23Status, '0' as ItemAdvNetDueIn, 
//                           ic.ItemCategoryName as ItemCategoryCode, ic.AssetStatus as ItemStatus");
//        $this->db->from($this->item . ' it');
//        $this->db->join($this->item_category . ' ic', 'ic.ItemCategoryID = it.ItemCategoryID', 'INNER');
//
//        if($item_category_id != ''){
//            $this->db->where('it.ItemCategoryID', $item_category_id);
//        }
//
//        if($item_code != ''){
//            $this->db->like('it.ItemCode', $item_code);
//        }
//
//        if($item_name != ''){
//            $this->db->like('it.ItemDesc', $item_name);
//        }
//
//        $this->db->where_in('it.TransStatus', array(0, 1));
//        $this->db->order_by('it.ItemCode', 'ASC');
//        $this->db->_protect_identifiers = false;
//
//        return $this->db->get()->result();
//    }

    function get_detail($id) {
        $this->db->select($this->table . ".*," . $this->department . ".DepartmentName," . $this->employee . ".EmployeeName," . $this->branch . ".BranchName");
        $this->db->join($this->branch, $this->branch . ".BranchCode=" . $this->table . ".BranchCode", "INNER");
        $this->db->join($this->department, $this->department . ".DepartmentCode=" . $this->table . ".DepartmentCode", "INNER");
        $this->db->join($this->employee, $this->employee . ".EmployeeCode=" . $this->table . ".AppLevel1Code", "LEFT");
        $query = $this->db->get_where($this->table, array('at_purchaserequisition.PReqNumber' => $id));

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

    //Daswan get detail to print
    function get_detail_print($id) {
        $this->db->select($this->table . ".*," . $this->department . ".DepartmentName," . $this->employee . ".EmployeeName as approved_by," . $this->branch . ".BranchName," . $this->company . ".CompanyName," . $this->company . ".CompanyAddress," . $this->company . ".PhoneNumber,em.EmployeeName as nm_prepared");
        $this->db->join($this->branch, $this->branch . ".BranchCode=" . $this->table . ".BranchCode", "INNER");
        $this->db->join($this->department, $this->department . ".DepartmentCode=" . $this->table . ".DepartmentCode", "INNER");
        $this->db->join($this->employee, $this->employee . ".EmployeeCode=" . $this->table . ".AppLevel1Code", "LEFT");
        $this->db->join($this->employee.' as em',"em.EmployeeCode=" . $this->table . ".CreatedBy", "LEFT");
        $this->db->join($this->company, $this->company . ".CompanyCode=" . $this->department . ".CompanyCode", "INNER");
        $query = $this->db->get_where($this->table, array('at_purchaserequisition.PReqNumber' => $id));

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

    function get_detail_item($PReqNumber) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("(case when ItemSpdStatus = 9 then 'Yes' else 'No' end) as Status, 
                          ItemCode, ItemDesc, ItemUnit, ItemQty, DATE_FORMAT(RequiredDate,'%d-%m-%Y') as RequiredDate");
        $query = $this->db->get_where($this->detail, array('PReqNumber' => $PReqNumber));
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    //Daswan get detail item to print
    function get_detail_item_print($PReqNumber) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("(case when ItemSpdStatus = 9 then 'Yes' else 'No' end) as Status,ItemStatus, 
                          ItemCode, ItemDesc, ItemUnit, ItemQty, DATE_FORMAT(RequiredDate,'%d-%m-%Y') as RequiredDate");
        $query = $this->db->get_where($this->detail, array('PReqNumber' => $PReqNumber));
        $this->db->_protect_identifiers = TRUE;

        return $query->result_array();
    }

    function get_detail_item_for_edit($PReqNumber) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("(case when ItemSpdStatus = 0 then 'No' else 'Yes' end) as Status, at_preqdetail.ItemCode, at_preqdetail.ItemDesc,at_preqdetail.ItemStatus, at_preqdetail.ItemType, 
                            at_preqdetail.ItemUnit, ItemQty, ItemQtyPO, ItemQtySpd,ItemQtyRI, ItemCategoryID, ItemCategoryCode, RequiredDate, 
                            concat(ItemQtySpd, ' item suspend') as ItemQtySpdInfo, PreqDetailID, ItemQty as ItemQty_Old, 0 as Modus_Type");
        $this->db->from($this->detail);
        $this->db->where(array('PReqNumber' => $PReqNumber));
        $this->db->order_by('PReqDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = TRUE;

        return $query->result();
    }

    function get_for_po() {
        $query = $this->db->get_where($this->table, array('AppLevel1Status' => 1, 'TransStatus' => 1, 'BranchCode' => $this->session->userdata('branch')));

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

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

        $this->db->distinct();
        $this->db->select("pr.PReqNumber, pr.PReqDate, pr.PReqDesc");
        $this->db->from($this->table . ' as pr');
        $this->db->join($this->detail . ' as pd', 'pd.PReqNumber = pr.PReqNumber');
        $this->db->where('pr.BranchCode', $branch_code);
        $this->db->where('pr.TransStatus', 1);
        $this->db->where('(pd.ItemQty - pd.ItemQtyPO - pd.ItemQtySpd) > ', 0);

        $this->db->where_in('pd.ItemType', array(0, 1));

        $this->db->order_by('pr.PReqNumber', 'Asc');
        $query = $this->db->get();

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

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

        $this->db->distinct();
        $this->db->select("pr.PReqNumber, pr.PReqDate, pr.PReqDesc");
        $this->db->from($this->table . ' as pr');
        $this->db->join($this->detail . ' as pd', 'pd.PReqNumber = pr.PReqNumber');
        $this->db->where('pr.BranchCode', $branch_code);
        $this->db->where('pr.TransStatus', 1);
        $this->db->where('(pd.ItemQty - pd.ItemQtyPO - pd.ItemQtySpd) > ', 0);

        $this->db->where('pd.ItemType', 2);

        $this->db->order_by('pr.PReqNumber', 'Asc');
        $query = $this->db->get();

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

    function get_detail_item_for_po($PReqNumber) {
        $this->db->_protect_identifiers = false;
        $this->db->select("prd.PReqNumber, pr.PReqDate, pr.PReqDesc, prd.PReqDetailID, prd.ItemCode, prd.ItemDesc, prd.ItemUnit, prd.ItemQtyPO,  
                           prd.ItemCategoryCode,  prd.ItemType, prd.ItemPPh22Status, prd.ItemPPh23Status, prd.ItemAdvNetDueIn, prd.ItemStatus,
                           '0' as ItemPrice, '0' as ItemAmount, '0' as Item_PPn10, '0' as Item_PPh22, '0' as Item_PPh23, '0' as ItemTotalAmount, '0' as ItemDisc, '0' as AmountDisc, '0' as ItemAmount_Hide,                           
                          (case when ItemType = 0 or 1 then (ItemQty - ItemQtyPO - ItemQtySpd) else 1 end) as ItemQty, 
                          (case when ItemType = 0 or 1 then (ItemQty - ItemQtyPO - ItemQtySpd) else 1 end) as ItemMax,
                          prd.ItemCategoryID as ItemCategoryID");
        $this->db->from($this->detail . ' prd');
        $this->db->join($this->table . ' pr', 'prd.PReqNumber = pr.PReqNumber', 'INNER');
        $this->db->join($this->item . ' it', 'it.ItemCode = prd.ItemCode', 'LEFT');
        $this->db->join($this->item_category . ' ic', 'ic.ItemCategoryID = it.ItemCategoryID', 'LEFT');
        $this->db->where_in('prd.PReqNumber', $PReqNumber);
        $this->db->where('(ItemQty - ItemQtyPO - ItemQtySpd) > ', 0);
        $this->db->order_by('prd.PReqDetailID', 'ASC');
        $query = $this->db->get();
        $this->db->_protect_identifiers = true;

        return $query->result();
    }

    function get_item() {
        $item_catcode = isset($_POST['item_categori']) ? mysql_real_escape_string($_POST['item_categori']) : '';
        $item_desc = isset($_POST['item_desc']) ? mysql_real_escape_string($_POST['item_desc']) : '';

        if ($item_catcode != '' || $item_desc != '') {
            $this->db->select('*');
            $this->db->from('am_item');
            $this->db->like('ItemCategoryID', $item_catcode);
            $this->db->like('ItemDesc', $item_desc);

            return $this->db->get()->result();
        } else {
            $this->db->select('*');
            $this->db->from('am_item');

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

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

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

    function get_item_suspend($id) {
        $query = $this->db->get_where($this->detail, array('PReqNumber' => $id, 'ItemSpdStatus' => 1));
        return $query->result();
    }

    function insert_new($data, $detail, $preq_number) {
        $this->db->trans_start();
        $this->insert($data);
        foreach ($detail as $row) {
            $detail_data = array(
                'PReqNumber' => $preq_number,
                'ItemCode' => $row->ItemCode,
                'ItemDesc' => $row->ItemDesc,
                'itemUnit' => $row->ItemUnit,
                'itemQty' => $row->ItemQty,
                'RequiredDate' => date("Y-m-d", strtotime($row->RequiredDate)),
                'ItemCategoryID' => $row->ItemCategoryID,
                'ItemCategoryCode' => $row->ItemCategoryCode,
                'ItemType' => $row->ItemType,
                'ItemStatus' => $row->ItemStatus,
                'ItemPPh22Status' => $row->ItemPPh22Status,
                'ItemPPh23Status' => $row->ItemPPh23Status,
                'ItemAdvNetDueIn' => $row->ItemAdvNetDueIn,
                'LastUser' => $this->session->userdata("username")
            );
            $this->insert_detail($detail_data);
        }

        $this->db->trans_complete();

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

    function update_all_table_new($data, $detail, $preq_number) {
        $this->db->trans_start();
        $this->update($data, $preq_number);
        foreach ($detail as $row) {
            $detail_data = array(
                'RequiredDate' => date("Y-m-d", strtotime($row->RequiredDate)),
                'ItemQty' => $row->ItemQty,
                'LastUser' => $this->session->userdata("username")
            );
            $this->update_detail($detail_data, $row->PreqDetailID);
        }
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }
	
	function update_suspend_item($arr_qty_spd, $arr_transstatus, $preq_number){
		$this->db->trans_start();
		for($x=0; $x<count($arr_qty_spd); $x++){
			$PreqDetailID = $arr_qty_spd[$x]['PreqDetailID'];
			
			$data_preq = array(
				'ItemQtySpd' 	=> $arr_qty_spd[$x]['ItemQtySpd'],
				'ItemSpdStatus' => $arr_qty_spd[$x]['ItemSpdStatus'],
				'LastUser' 		=> $arr_qty_spd[$x]['LastUser']
			);
			$this->update_detail($data_preq, $PreqDetailID);
		}
		
		for($i=0; $i<count($arr_transstatus); $i++){
			$data = array(
				'TransStatus' 	=> $arr_transstatus[$i]['TransStatus'],
				'LastUser' 		=> $arr_transstatus[$i]['LastUser']
			);
			$this->update($data, $preq_number);
		}
		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE) {
			return 0;
		}else{
			return 1;
		}
	}
	
    function update_group_single($data, $id) {
        $this->update($data, $id);
    }

    function update_detail_single($data, $id) {
        $this->db->trans_start();
        $this->update_detail($data, $id);
        $this->db->trans_complete();
        if ($this->db->trans_status() === FALSE) {
            return 0;
        } else {
            return 1;
        }
    }

    function delete_detail_new($PreqDetailID) {
        $this->db->trans_start();
        $this->delete_detail_by_id($PreqDetailID);
        $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_detail) {
        $this->db->insert($this->detail, $data_detail);
    }

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

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

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

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

    function delete_detail_by_id($preg_detail_id) {
        $this->db->delete($this->detail, array('PReqDetailID' => $preg_detail_id));
    }

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

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

    function create_pr_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');
        }

        $pr_number = $branch . "/" . $month . $year . "PR/";

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

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

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

            $new_pr_number = $pr_number . $number;
        }

        return $new_pr_number;
    }

    function get_qty_purchase_order($id, $pord_number) {

        $this->db->select('sum(at_porddetail.ItemQty) as TotalQtyPO');
        $this->db->from('at_porddetail');
        $this->db->join('at_purchaseorder', 'at_purchaseorder.POrdNumber = at_porddetail.POrdNumber', 'INNER');
        $this->db->where('at_porddetail.PReqNumber', $id);
        $this->db->where('at_porddetail.POrdNumber', $pord_number);

        $this->db->group_by('at_porddetail.PReqNumber');

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

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

            return $TotalQtyPO;
        } else {
            return 0;
        }
    }

    function set_finish($id) {

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

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

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

            return $TotalQtyPO;
        } else {
            return 0;
        }
    }

    function get_total_qty_pr_spd($id) {

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

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

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

            return $TotalQtySpd;
        } else {
            return 0;
        }
    }

    function set_finish_pr($id) {
        $this->db->select('sum(at_preqdetail.ItemQty) as TotalQtyPR, at_preqdetail.ItemQtySpd as ItemQtySpd, at_purchaserequisition.TransStatus');
        $this->db->from('at_preqdetail');
        $this->db->join('at_purchaserequisition', 'at_purchaserequisition.PReqNumber = at_preqdetail.PReqNumber', 'INNER');
        $this->db->where('at_purchaserequisition.PReqNumber', $id);
        $this->db->where_in('at_purchaserequisition.TransStatus', array(1, 2));
        $query_pr = $this->db->get();
        if ($query_pr->num_rows() > 0) {
            return $query_pr->row();
        } else {
            return false;
        }
    }

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

    function get_preq_detail_by_item($item_code) {
        $this->db->select('at_preqdetail.ItemCode');
        $this->db->from('at_preqdetail');
        $this->db->join('at_purchaserequisition', 'at_purchaserequisition.PReqNumber = at_preqdetail.PReqNumber', 'INNER');

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

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

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

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

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

    function get_detail_sum_preq($PReqNumber, $ItemCode) {
        $this->db->_protect_identifiers = FALSE;
        $this->db->select("(prd.ItemQtyPO + prd.ItemQtySpd) as TotalItemQtyPO, (prd.ItemQty) as TotalItemQtyPR, prd.ItemQtySpd, prd.ItemQtyPO");
        $this->db->from('at_purchaserequisition as pr');
        $this->db->join("at_preqdetail as prd", "prd.PReqNumber = pr.PReqNumber", "INNER");

        $this->db->where('prd.PReqNumber', $PReqNumber);
        $this->db->where('prd.ItemCode', $ItemCode);

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

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

        return $query->row();
    }

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

        $this->db->where('at_porddetail.PReqNumber', $PReq_number);
        $this->db->where_in('at_purchaseorder.TransStatus', array(1, 2, 4, 5, 6, 8, 0));
        $this->db->group_by('at_porddetail.PReqNumber');

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

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

	function get_old_no_transaaction($id){
		$this->db->select('OldPReqNumber');
        $this->db->from('at_purchaserequisition');
        
        $this->db->where('at_purchaserequisition.PReqNumber', $id);
        $query_pr = $this->db->get();
        if ($query_pr->num_rows() > 0) {
            return $query_pr->row();
        } else {
            return false;
        }
	}
	
}

/* End of file m_purchase_requisition.php */
/* Location: ./application/moduls_core/list/models/m_purchase_requisition.php */