<?php

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

/* 	
 * 	Author 	: Tagor
 * 	Tanggal : 07-08-2014	
 * 	Revisi 	: Fachri
 */

class Import_ri extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 405;
   
    public $name = "Import Receive Items";
	public $menu_model = 'm_import_recur';
    public $trans_data = array();
    // inisialisasi otomatis
    
	
	
	 public function __construct() {
        parent::__construct();
        //$this->load->model('m_adjustment');
        $this->load->helper('message_helper');
        $this->load->helper('status');
        $this->load->helper('custom_string_helper');
		
        $this->load->model('m_import_ri');
        //$this->load->model('m_account_journal');
		$this->load->model('custom/m_custom');
		$this->load->model('list/m_account_journal');
		$this->load->model('list/m_receive_item');
		$this->load->model('list/m_purchase_requisition');
		$this->load->model('list/m_purchase_order');
		
		$this->load->model('login/m_login');
	
		$is_login = $this->m_login->get_session_id($this->session->userdata('session_id'),$this->session->userdata('username'));
		if($is_login){

		}else{
			$username       = $this->session->userdata('username');
			$session_id     = $this->session->userdata('session_id');
			$this->m_login->delete_session($username,$session_id);
			$this->session->sess_destroy();

			$uri_func = $this->uri->segment(3);
			if(($uri_func === FALSE) || ($uri_func =='add') || ($uri_func =='edit')){
				redirect(base_url() . 'login', 'refresh');
			}else if(in_array($uri_func,array('approve_data','approved_mgr','approved_dir','approve','approve_transsaction','reverse_data','reversed_data','reverse_transsaction','save','save_data','insert','update','update_data','suspend','suspend_data','suspend_transsaction','suspend_mgr','suspend_dir'))){
				$result['status']   = 'session';
				$result['message']  = get_notification('session_destroy',0);
				echo json_encode($result);
				die();
			}
		}
    }
	
    public function index() {
        if ($this->session->userdata("login") == TRUE) {
			$group_menu = $this->session->userdata('group_menu');
            $arr_group_id = $this->m_menu->get_menu_by_group($group_menu, $this->menu_id);
            if (!empty($arr_group_id)) {
                $data['available_menu'] = array_unique($arr_group_id);
                if (!in_array($this->menu_id, $data['available_menu'])) {
                    redirect(base_url() . 'error', 'refresh');
                } else {
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_model'] = $this->menu_model;
					$data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					$data['date_now'] = date('d-m-Y');
					
                   // $data['menu_link'] = $this->m_adjustment->get_menulink($this->menu_id);
                    $this->load->view('v_header');
                    $this->load->view('exim_receive_item/v_import_ri', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
	}
	
	public function ajax(){
		$page	= ($this->input->post('page')) ? intval($this->input->post('page')) : 1;
		$rows	= ($this->input->post('rows')) ? intval($this->input->post('rows')) : 150;
		
		$hasil = array();
		/*===========rows*page tidak boleh melebihi dari jumlah data======= */
		
		/*=================================post dari find di kiri====================================================*/
		$param 				= $this->input->post('param');
		$Number				= $this->input->post('NoTransaction');
		$VendorName				= $this->input->post('VendorName');
		
		/*$DateFrom			= isset($param['txt_DateFrom']) ? $param['txt_DateFrom'] : '';
		$DateTo				= isset($param['txt_DateTo']) ? $param['txt_DateTo'] : '';*/
		
		
		
		/*============================================end============================================================*/
		if($Number != ""){$this->db->like('NoTransaction', $Number);} 
		if($VendorName != ""){$this->db->like('VendorName', $VendorName);} 
		
		/*if((($DateFrom != '') && ($DateTo != ''))){
            if($DateFrom <= $DateTo){
				$this->db->where('ah_importrecur.DateTransaction >=', date("Y-m-d", strtotime($DateFrom)));
            	$this->db->where('ah_importrecur.DateTransaction <=', date("Y-m-d", strtotime($DateTo))); 
			}
        }*/
		/*==========================end=================================================================*/
		$this->db->join('at_receiveitem as ar','ar.PRecNumber=ah_importreceiveitem.NoTransaction','inner');
		$this->db->join('am_vendor as av','av.VendorCode=ar.VendorCode','inner');
		$count_data = $this->db->count_all_results('ah_importreceiveitem');
		
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_import_ri->get_all(); 
		
		for($i=0; $i<=($rows-1); $i++){
			$hasil[] = array(
				
				'NoTransaction' 	=>	$result[$i]->NoTransaction,
				'OldNoTransaction' 	=>	$result[$i]->OldNoTransaction,
				'DateTransaction' 	=>	$result[$i]->DateTransaction,
				'TotalInvoice' 	=>	$result[$i]->TotalInvoice,
				'VendorName' 	=>	$result[$i]->VendorName,
				'CurrencyRate' 	=>	$result[$i]->CurrencyRate,
			);
		}
		
		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }
	
	public function insert(){
		try{
			$txt_transaction_no	= $this->input->post('txt_transaction_no');
			$txt_date			= $this->input->post('txt_date');
			$cbg_vendor			= $this->input->post('cbg_vendor');
			$txt_currencyrate			= $this->input->post('txt_currencyrate');
			$txt_total_invoice			= $this->input->post('txt_total_invoice');
			$txt_terms			= $this->input->post('txt_terms');
			$txt_vendro_addres			= $this->input->post('txt_vendro_addres');
			$txt_currencycode			= $this->input->post('txt_currencycode');
			$branch_code = $this->session->userdata('branch');
			$prec_no = $this->m_receive_item->create_ri_number($txt_date);
			$preq_no = $this->m_purchase_requisition->create_pr_number($txt_date);
			$pord_number = $this->m_purchase_order->create_po_number($txt_date);
			
			$detail_post = $this->input->post('detail');
        	$detail = json_decode($detail_post);
		 
		 	$this->db->trans_begin();
			
			$data = array(
				'NoTransaction' 	=> $prec_no,
				'OldNoTransaction' 	=> $txt_transaction_no,
				'DateTransaction' 	=> date("Y-m-d", strtotime($txt_date)),
				'TotalInvoice' 		=> $txt_total_invoice,
				'CurrencyRate' 		=> $txt_currencyrate,
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_import_ri->insert($data);
			
			$data_preq = array(
				'BranchCode' 		=> $branch_code,
				'DepartmentCode' 	=> $this->session->userdata('department'),
				'PReqDate' 			=> date("Y-m-d", strtotime($txt_date)),
				'PReqNumber' 		=> $preq_no,
				'AppLevel1Status' 	=> 1,
				'PReqDesc' 			=> "Import ,PR,PO,Receive Item",
				'AppLevel1Code' 	=> $this->session->userdata("username"),
				'AppLevel1Date' 	=> date("Y-m-d", strtotime($txt_date)),
				'TransStatus' 		=> 2,
				'CreatedBy' 		=> $this->session->userdata("username"),
				'CreatedAt' 		=> date('Y-m-d'),
				'OldPReqNumber' 	=> $txt_transaction_no,
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_purchase_requisition->insert($data_preq);
			
			$data_po = array(
                'BranchCode' => $branch_code,
                'VendorCode' => $cbg_vendor,
                'POrdDate' => date("Y-m-d", strtotime($txt_date)),
                'POrdNumber' => $pord_number,
                'PReqDate' => date("Y-m-d", strtotime($txt_date)),
                'PReqNumber' => $preq_no,
                'ExpectedDate' => date("Y-m-d", strtotime($txt_date)),
                'ShipmentID' => 1,
                'TermsPaymentID' => $txt_terms,
                'FOBID' => 1,
				'CurrencyCode' => $txt_currencycode,
				'CurrencyRate' => $txt_currencyrate,
                'BillingAddress' => $txt_vendro_addres,
                'ShippingAddress' => $txt_vendro_addres,
                'OldPOrdNumber' => $txt_transaction_no,
                'POrdDesc' => "Import ,PR,PO,Receive Item",
                'POrdSubTotal' => $txt_total_invoice,
                'POrdDiscount' => 0,
                'POrdPPn10Pcnt' => 0,
                'POrdPPh22Pcnt' => 0,
                'POrdPPh23Pcnt' => 0,
                'POrdPPn10' => 0,
                'POrdPPh22' => 0,
                'POrdPPh23' => 0,
                'POrdEstFreight' => 0,
                'POrdTotalAmount' => $txt_total_invoice,
                'POrdDPStatus' => 0,
                'POrdTotalDP' => 0,
                'POrdTaxesStatus' => 0,
                'POrdInTaxStatus' => 0,
                'TransStatus' => 2,
				'AppLevel1Status' => 1,
                'AppLevel1Code' => $this->session->userdata("username"),
                'AppLevel1Date' => date("Y-m-d"),
				'AppLevel2Status' => 1,
                'AppLevel2Code' => $this->session->userdata("username"),
                'AppLevel2Date' => date("Y-m-d"),
				'CreatedBy' => $this->session->userdata("username"),
                'CreatedAt' => date('Y-m-d'),
                'LastUser' => $this->session->userdata("username")
            );
			$this->m_purchase_order->insert($data_po);
			
			$data = array(
				'BranchCode' => $branch_code,
				'VendorCode' => $cbg_vendor,
				'PRecNumber' => $prec_no,
				'PRecDate' => date("Y-m-d", strtotime($txt_date)),
				'POrdDate' => date("Y-m-d", strtotime($txt_date)),
				'POrdNumber' => $pord_number,
				'VendorDONumber' => "",
				'ShipmentDate' => date("Y-m-d", strtotime($txt_date)),
				'ShipmentID' => 1,
				'TermsPaymentID' => $txt_terms,
				'FOBID' => 1,
				'CurrencyCode' => $txt_currencycode,
				'CurrencyRate' => $txt_currencyrate,
				'PRecDesc' => "Import ,PR,PO,Receive Item",
				'PRecSubTotal' => $txt_total_invoice,
				'PRecPPn10Pcnt' => 0,
				'PRecPPn10' => 0,
				'PRecTotalAmount' => $txt_total_invoice,
				'PRecTaxesStatus' => 0,
				'PRecInTaxStatus' => 0,
				'TransStatus' => 1,
				'AppLevel1Status' => 1,
				'AppLevel1Code' => $this->session->userdata("username"),
				'AppLevel1Date' => date("Y-m-d", strtotime($txt_date)),
				'CreatedBy' => $this->session->userdata("username"),
				'CreatedAt' => date('Y-m-d'),
				'LastUser' => $this->session->userdata("username")
			);
	
			//'1. Input Receive Item >> at_receiveitem ' . '<br/>';
			$this->m_receive_item->insert($data);
			
			foreach($detail as $row_detail){
				$detail_data_preq = array(
					'PReqNumber' => $preq_no,
					'ItemCode' => $row_detail->ItemCode,
					'ItemDesc' => $row_detail->ItemDesc,
					'itemUnit' => $row_detail->ItemUnit,
					'itemQty' => $row_detail->ItemQty,
					'ItemQtyPO' => $row_detail->ItemQty,
					'ItemQtyRI' => $row_detail->ItemQty,
					'ItemQtySpd' => 0,
					'RequiredDate' => date("Y-m-d", strtotime($txt_date)),
					'ItemCategoryID' => $row_detail->ItemCategoryID,
					'ItemCategoryCode' => $row_detail->ItemCategoryCode,
					'ItemType' => $row_detail->ItemType,
					'ItemStatus' => $row_detail->ItemStatus,
					'ItemPPh22Status' => 0,
					'ItemPPh23Status' => 0,
					'ItemAdvNetDueIn' => 0,
					'LastUser' => $this->session->userdata("username")
				);
				$this->m_purchase_requisition->insert_detail($detail_data_preq);
				
				$get_purchase_req = $this->m_import_ri->get_purchase_req($preq_no, $row_detail->ItemCode);
				
				$detail_data_po = array(
					'PReqDetailID' 	=> $get_purchase_req->PReqDetailID,
					'PReqNumber' 	=> $get_purchase_req->PReqNumber,
					'POrdNumber' 	=> $pord_number,
					'ItemCode' 		=> $row_detail->ItemCode,
					'ItemDesc' 		=> $row_detail->ItemDesc,
					'itemUnit' 		=> $row_detail->ItemUnit,
					'itemQty' 		=> $row_detail->ItemQty,
					'ItemQtyRI' 	=> $row_detail->ItemQty,
					'ItemPrice' 	=> $row_detail->Price,
					'ItemDisc' 		=> 0,
					'ItemAmount' 	=> $row_detail->Amount,
					'ItemTaxPPn10' 	=> 0,
					'ItemTaxPPh22' 	=> 0,
					'ItemTaxPPh23' 	=> 0,
					'ItemTotalAmount' 	=> $row_detail->TotalAmount,
					'ItemCategoryID' 	=> $row_detail->ItemCategoryID,
					'ItemCategoryCode' 	=> $row_detail->ItemCategoryCode,
					'ItemType' 			=> $row_detail->ItemType,
					'ItemStatus' 		=> $row_detail->ItemStatus,
					'ItemPPh22Status' 	=> 0,
					'ItemPPh23Status' 	=> 0,
					'ItemAdvNetDueIn' 	=> 0,
					'ItemPriceNTax' 	=> 0,
					'ItemCodeVendor' 	=> " ",
					'LastUser' 			=> $this->session->userdata("username")
				);
				
				$this->m_purchase_order->insert_detail($detail_data_po);
				
				$get_purchase_ord = $this->m_import_ri->get_purchase_ord($pord_number, $row_detail->ItemCode);
				
				$detail_data = array(
					'POrdDetailID' 	=> $get_purchase_ord->POrdDetailID,
					'POrdNumber' 	=> $get_purchase_ord->POrdNumber,
					'PRecNumber' 	=> $prec_no,
					'ItemCode' 		=> $row_detail->ItemCode,
					'ItemDesc' 		=> $row_detail->ItemDesc,
					'itemUnit' 		=> $row_detail->ItemUnit,
					'ItemQty' 		=> $row_detail->ItemQty,
					'ItemDisc' 		=> 0,
					'ItemPrice' 	=> $row_detail->Price,
					'ItemAmount' 	=> $row_detail->Amount,
					'ItemTaxPPn10' 		=> 0,
					'ItemTotalAmount' 	=> $row_detail->TotalAmount,
					'ItemCategoryID' 	=> $row_detail->ItemCategoryID,
					'ItemCategoryCode' 	=> $row_detail->ItemCategoryCode,
					'ItemType' 			=> $row_detail->ItemType,
					'ItemCodeVendor' 	=> " ",
					'ItemStatus' 		=> $row_detail->ItemStatus,
					'LastUser' 			=> $this->session->userdata("username")
				);
	
				$this->m_receive_item->insert_detail($detail_data);
				
				@$TotalAmount += $row_detail->Amount;
			}
			
			$OpeningBalance = $this->m_account_journal->get_account_name('Opening Balance');
			if($OpeningBalance == false) {
				throw new Exception('Journal Opening Balance belum tersedia di COA silahkan lihat kembali COA');
			}
			
			$HutangAccount = $this->m_account_journal->get_sys_item_account('Unbilled');
			if($HutangAccount == false) {
				throw new Exception('Journal Hutang yang belum ditagih belum tersedia di COA silahkan lihat kembali COA');
			}
			
			$journal_debet = array(
				'PRecDate' => date("Y-m-d", strtotime($txt_date)),
				'PRecNumber' => $prec_no,
				'PRecDesc' => "Import Receive Item",
				'PRecAccountNumber' => $OpeningBalance->AccountNumber,
				'PRecSaldoDebet' => $txt_currencycode == 'IDR' ? $TotalAmount : doubleval($TotalAmount) * $txt_currencyrate,
				'PRecSaldoCredit' => 0,
				'AmountCurrency' => $TotalAmount,
				'PRecSignStatus' => 1,
				'LastUser' => $this->session->userdata("username")
			);

			$this->m_receive_item->insert_journal($journal_debet);
			
			$journal_kredit = array(
				'PRecDate' => date("Y-m-d", strtotime($txt_date)),
				'PRecNumber' => $prec_no,
				'PRecDesc' => "Import Receive Item",
				'PRecAccountNumber' => $HutangAccount->AccountNumber,
				'PRecSaldoDebet' => 0,
				'PRecSaldoCredit' => $txt_currencycode == 'IDR' ? $TotalAmount : doubleval($TotalAmount) * $txt_currencyrate,
				'AmountCurrency' => $TotalAmount,
				'PRecSignStatus' => 0,
				'LastUser' => $this->session->userdata("username")
			);

			$this->m_receive_item->insert_journal($journal_kredit);
			
			$data_app_finish_ri = array(
				'AppFinished' => 1
			);
			 $this->m_receive_item->update($data_app_finish_ri, $prec_no);
				
			/* =============================trans roll back dan trans commit============================/ */
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, $prec_no);

                $result['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                $result['number'] = $pinv_number;
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, $prec_no);
            }
            /* ==================================end====================================================== */
			
			echo json_encode($result);
		}
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
	}
}
