<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*	
 *	Author 	: Fachri / 13-10-2015	
 */

class Delivery_order_direct extends CI_Controller {
    // inisialisasi manual
    public $menu_id = 317;
    public $code 	= "Delivery Order Number";
    public $name 	= "Delivery Order Direct";
	
    public function __construct() {
        parent::__construct();
		$this->load->helper('message');	
		$this->load->helper('status');			
		$this->load->helper('convert_date');
		$this->load->helper('approval');
		
		$this->load->model('m_account_journal');
		$this->load->model('m_delivery_order');	
		$this->load->model('m_sales_order');	
		$this->load->model('m_sales_quotation');
		$this->load->model('m_sales_invoice');
		$this->load->model('m_inventories');
		$this->load->model('m_purchase_order');
    }
	
    //Function Index tidak dipakai karena ditak ada list untuk do direct
    public function index()	{
		
    }
	
    //Function Form Edit
    public function add() {
		if ($this->session->userdata("login") == TRUE) { 
            $group_menu             = $this->session->userdata('group_menu');
			/*
				untuk di index/list = get_menu_by_group, 
				untuk di add = get_menu_by_group_add
				untuk di edit = get_menu_by_group_edit
			*/
            $arr_group_id           = $this->m_menu->get_menu_by_group_add($group_menu, $this->menu_id);
			//--------------------------end-----------------------------------------------------------
            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{
					/*
						modul untuk akses add masing masing modul berebda 
						jangan lupa copy $data nya (jika dia bener langsung ke add)
					*/
					$group_menu 		= $this->session->userdata('group_menu');
					// set data
					$data['menu_id'] 	=  $this->menu_id;

					// get link from tbl_menu 
					$data['menu_label'] =  $this->m_menu->get_menulabel($this->menu_id);
					$data['menu_link'] 	= $this->m_menu->get_menulink($this->menu_id);
					
					$data['do_date'] 	= date('d-m-Y');
					
					//panggil model hak akses untuk autoriti
					$data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
					
					// set for view
					$this->load->view('v_header');
					$this->load->view('sales/delivery_order_direct/v_new_deliveryorder_direct', $data);
					$this->load->view('v_footer');
				}
			}
			else{
				redirect(base_url() . 'error', 'refresh');
			}
        }
        else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
	public function insert() {
		/*===========================deklar variabel============================================*/
        $branchcode			= $this->session->userdata('branch');
        $cmb_customer		= $this->input->post('cmb_customer');
		$currency_code		= $this->input->post('txt_currency_code');
		$currency_rate		= $this->input->post('txt_rate');
		$txa_ship_to		= $this->input->post('txa_ship_to');
        $txa_address		= $this->input->post('txa_address');
        $txt_do_date		= $this->input->post('txt_do_date');
		
		/*=====================================do number==========================================*/
		$txt_do_no  		= $this->m_delivery_order->create_do_number($txt_do_date);
		/*==========================================================================================*/
		
        $cmb_ship_via		= $this->input->post('cmb_ship_via');
		$txt_so_no			= $this->input->post('txt_so_no');
        $txt_ship_date		= $this->input->post('txt_ship_date');
        $txt_driver			= $this->input->post('txt_driver');
        $txt_po_no			= $this->input->post('txt_po_no');
		$txt_car_number		= $this->input->post('txt_car_number');
        $txa_description	= $this->input->post('txa_description');
		$cmb_comp_po		= $this->input->post('cmb_comp_po');
		/*============================end====================================================*/
		$detail				= json_decode($this->input->post('detail'));
		
		if(count($detail)>0){
            $this->db->trans_begin();
			
			/*
				get data po, cek apakah no po ini ada di purchase order
				jika ada lakukan proses ini
				jika tidak transaksi tidak bisa dibuat
			*/
			$get_cek_purchase_order = $this->m_purchase_order->check_approved_by_transstatus($cmb_comp_po);
			if($get_cek_purchase_order != 1){
				$result['status'] 		= FALSE;
				$result['message']  	= msg_confirmation_blok('msg_do_direct', $this->name, $cmb_comp_po);
				echo json_encode($result);
				$this->db->trans_rollback();
				die();
			}
			/*=====================end==========================*/
			
			/*
				Cek data detail pordetail by item code
				apakah qtypo-qtyspd-qtyri > qty do direct
			*/
			foreach($detail as $row_detail){
				$get_po_detail_by_do_direct = $this->m_purchase_order->get_detail_sum_pord($cmb_comp_po, $row_detail->ItemCode);
				if(empty($get_po_detail_by_do_direct->ItemCode)){
					$result['status'] 		= FALSE;
					$result['message']  	= 'Maaf transaksi Do Direct gagal, Item Code '.$row_detail->ItemCode.' Tidak ada di Transaksi Purchase Order';
					echo json_encode($result);
					$this->db->trans_rollback();
					die();
				}
				else{
					if($row_detail->ItemQty > $get_po_detail_by_do_direct->ItemQtyAllPo){
						$result['status'] 		= FALSE;
						$result['message']  	= 'Maaf transaksi Do Direct gagal, Item Code '.$row_detail->ItemCode.' melebihi Qty Purchases Order';
						echo json_encode($result);
						$this->db->trans_rollback();
						die();
					}
				}
			}
			/*===============End====================================*/
			
            /*======================insert group==============================*/
			$insert_group 	= $this->insert_group($txt_do_no, $branchcode, $cmb_customer, $txt_do_date, $txt_so_no, $txt_po_no, $txa_address, $txa_ship_to, $txt_ship_date, $cmb_ship_via, $txt_driver, $txt_car_number, $txa_description, $currency_code, $currency_rate, $cmb_comp_po);
			/*==============end===============================================*/
			
			/*===================insert detail====================================*/
            $insert_detail 	= $this->insert_detail($cmb_comp_po, $detail, $currency_code, $currency_rate, $txt_do_no, $branchcode, $txt_do_date, $txa_description);
			/*=====================end=============================================*/
        	
			/*=============================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, $txt_do_no);
			}
			else {
				$this->db->trans_commit();
				$result['status'] 		= TRUE;
				$result['message']  	= get_notification_transaksi($this->name, 'insert', 1, $txt_do_no);
				$result['menu_link']    = $this->m_menu->get_menulink($this->menu_id);
				$result['number']       = $txt_do_no;
			}
			/*==================================end======================================================*/
		
		}
		else{
			$result['status']   = false;
            $result['message']  = get_notification('no_count', 0);
		}
        echo json_encode($result);
	}
	
	function insert_group($txt_do_no, $branchcode, $cmb_customer, $txt_do_date, $txt_so_no, $txt_po_no, $txa_address, $txa_ship_to, $txt_ship_date, $cmb_ship_via, $txt_driver, $txt_car_number, $txa_description, $currency_code, $currency_rate, $cmb_comp_po){
		$data = array (
			'BranchCode'		=> $branchcode,
			'CustomerCode'		=> $cmb_customer,
			'DOrdDate'			=> date("Y-m-d", strtotime($txt_do_date)),	
			'DOrdNumber'		=> $txt_do_no,
			'SOrdDate'			=> date("Y-m-d", strtotime($this->m_sales_order->get_so_date($txt_so_no))),
			'SOrdNumber'		=> $txt_so_no,
			'CustPODate'		=> date("Y-m-d", strtotime($this->m_sales_order->get_po_date($txt_so_no))),			
			'CustPONumber'		=> $txt_po_no,
			'CompPONumber' 		=> $cmb_comp_po,
			'BillingAddress'	=> $txa_address,
			'ShipAddress' 		=> $txa_ship_to,
			'ShipDate'			=> date("Y-m-d", strtotime($txt_ship_date)),	
			'ShipmentID'		=> $cmb_ship_via,
			'DriverName'		=> $txt_driver,
			'LicencePlate'		=> $txt_car_number,
			'DOrdDesc'			=> $txa_description,
			'CurrencyCode'		=> $currency_code,
			'CurrencyRate'		=> $currency_rate,
			'DirectStatus' 		=> 1,
			'CreatedBy' 		=> $this->session->userdata("username"),
			'CreatedAt' 		=> date('Y-m-d'),
			'TransStatus'		=> 4,
			'LastUser'			=> $this->session->userdata("username")
		);
		
		//1. Inset into Delivery Order Table
		$this->m_delivery_order->insert($data);
		//----------------------------------------------------------------------------------------------------------//
	}
	
	function insert_detail($cmb_comp_po, $detail, $currency_code, $currency_rate, $txt_do_no, $branchcode, $txt_do_date, $txa_description){
		foreach($detail as $row){
			/*
				ItemCategory ID = 0 Inventory
				ItemCategory ID = 2 Service
			*/
			if($row->ItemCategoryID != 0){
				$item_qty_inventori 	= $this->m_inventories->get_item_qty($row->ItemCode, $branchcode);
				$item_qty 				= $row->ItemQty;
				
				$data_detail = array(
					'SOrdDetailID'		=> $row->SOrdDetailID,
					'SOrdNumber'		=> $row->SOrdNumber,
					'DOrdNumber'		=> $txt_do_no,
					'POrdNumber'	 	=> $cmb_comp_po,
					'ItemCode'			=> $row->ItemCode,
					'ItemDesc'			=> $row->ItemDesc,
					'ItemQty'			=> $row->ItemQty,
					'ItemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemDiscPcnt'		=> $row->ItemDiscPcnt,
					'ItemPriceCogs'		=> $row->ItemAverage,
					'ItemAmount'		=> $row->TotalAmount, 
					'ItemTax'			=> $row->ItemTax,
					'ItemCategoryID'	=> $row->ItemCategoryID,
					'ItemCategoryCode'	=> $row->ItemCategoryCode,
					'ItemType' 			=> $row->ItemStatus,
					'LastUser'			=> $this->session->userdata('username')
				);
				
				//2. Insert into DOrdDetail
				$this->m_delivery_order->insert_detail($data_detail);
				//------------------------------------------------------------------------------------------------------//
				
				/*
					update qty do di sales order detail
				*/
				$data_detail_so	= array(
					'SOrdDetailID'  => $row->SOrdDetailID, 
					'ItemQtyDO'     => ($row->ItemQtyDO + $row->ItemQty), 
					'LastUser'      => $this->session->userdata('username')
				);
				
				$this->m_sales_order->update_detail($data_detail_so, $row->SOrdDetailID);
				
				//summing jurnal
				if($currency_code != 'IDR'){
					$convert_item_curr 	= $row->ItemAverage / $currency_rate;
					$hasil_amount_qty 	= $row->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty 	= $row->ItemQty * $row->ItemAverage;
				}
				
				@$CategoryAmount[$row->ItemCategoryID] += $hasil_amount_qty;
				@$CategoryType[$row->ItemCategoryID] += $row->ItemStatus;
			}
			else{
				$data_detail = array(
					'SOrdDetailID'		=> $row->SOrdDetailID,
					'SOrdNumber'		=> $row->SOrdNumber,
					'DOrdNumber'		=> $txt_do_no,
					'ItemCode'			=> $row->ItemCode,
					'ItemDesc'			=> $row->ItemDesc,
					'ItemQty'			=> $row->ItemQty,
					'ItemUnit'			=> $row->ItemUnit,
					'ItemPrice'			=> $row->ItemPrice,
					'ItemPriceCogs'		=> 0,
					'ItemAmount'		=> $row->TotalAmount, 
					'ItemTax'			=> $row->ItemTax,
					'ItemCategoryID'	=> $row->ItemCategoryID,
					'ItemCategoryCode'	=> $row->ItemCategoryCode,
					'ItemType' 			=> $row->ItemStatus,
					'LastUser'			=> $this->session->userdata('username')
				);
				
				//2. Insert into DOrdDetail
				$this->m_delivery_order->insert_detail($data_detail);
				//------------------------------------------------------------------------------------------------------//
			
				$data_detail_so	= array(
					'SOrdDetailID'  => $row->SOrdDetailID, 
					'ItemQtyDO'     => ($row->ItemQtyDO + $row->ItemQty), 
					'LastUser'      => $this->session->userdata('username')
				);
				
				$this->m_sales_order->update_detail($data_detail_so, $row->SOrdDetailID);
				//summing jurnal
				if($currency_code != 'IDR'){
					$convert_item_curr = $row->ItemAverage / $currency_rate;
					$hasil_amount_qty = $row->ItemQty * $convert_item_curr;
				}
				else{
					$hasil_amount_qty = $row->ItemQty * $row->ItemAverage;
				}
				
				@$CategoryAmount[$row->ItemCategoryID] += $hasil_amount_qty;
				@$CategoryType[$row->ItemCategoryID] += $row->ItemStatus;
			}
		}
		/*===============insert journal==========================*/
		$insert_journal = $this->insert_journal($CategoryType,$CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no);
		/*===================end=================================*/
	}
	
	function insert_journal($CategoryType, $CategoryAmount, $currency_code, $currency_rate, $txt_do_date, $txa_description, $txt_do_no){
		foreach ($CategoryAmount as $key => $value) {
			if($CategoryType[$key] == 0) {
				//cogs akun
				$COGSAccount   = $this->m_account_journal->get_cat_item_account('COGS', $key, 'IDR');									
				if($COGSAccount == false) {$this->trans_rollback('journal');}

				$cogs_journal  = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
				$cogs_currency = doubleval($value);
				
				$journal_cogs = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $COGSAccount->AccountNumber,
					'DOrdSaldoDebet'    => $cogs_journal,
					'DOrdSaldoCredit'   => 0,
					'AmountCurrency' 	=> $cogs_currency,
					'DOrdSignStatus' 	=> 0,
					'LastUser'          => $this->session->userdata("username")	
				);
				
				$this->m_delivery_order->insert_journal($journal_cogs);
				//end cogs
				
				//inventori akun
				$InventoryAccount   = $this->m_account_journal->get_cat_item_account('Inventory', $key, 'IDR');
				if($InventoryAccount == false) {$this->trans_rollback('journal');}

				$inventory_journal  = $currency_code == 'IDR' ? doubleval($value) : doubleval($value) * $currency_rate;
				$inventory_currency = doubleval($value);

				$journal_inventory = array(
					'DOrdDate'          => date("Y-m-d", strtotime($txt_do_date)),
					'DordDesc' 			=> $txa_description,
					'DOrdNumber'        => $txt_do_no,
					'DOrdAccountNumber' => $InventoryAccount->AccountNumber,
					'DOrdSaldoDebet'    => 0,
					'DOrdSaldoCredit'   => $inventory_journal,
					'AmountCurrency' 	=> $inventory_currency,
					'DOrdSignStatus' 	=> 1,
					'LastUser'          => $this->session->userdata("username")	
				);
				//end inventori
				
				//insert jurnal do
				$this->m_delivery_order->insert_journal($journal_inventory);
			}
		}
	}
	
	public function ajax_item(){
        $id = $this->input->post('so_number');
		
        if(!empty($id)){
            echo json_encode($this->m_sales_order->get_detail_item_for_do($id));
        }
        else{
            echo '[]';
        }
		//echo $this->db->last_query();
    } 
}