<?php

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

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

class Import_recur extends CI_Controller {

    // inisialisasi manual
    public $menu_id = 404;
   
    public $name = "Import Recur";
	 public $menu_model = 'm_import_recur';
    public $trans_data = array();
    // inisialisasi otomatis
    public $add = "add";
    public $edit = "edit";
    public $delete = "delete";
    public $to_preview = "to_preview";
    public $to_pdf = "to_pdf";
    public $to_excel = "to_excel";
	
	
	 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_recur');
        //$this->load->model('m_account_journal');
		$this->load->model('custom/m_custom');
		$this->load->model('list/m_purchase_invoice');
		$this->load->model('list/m_journalvoucher');
		$this->load->model('list/m_account_journal');
		
		$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_reccur/v_import_recur', $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');
		$Desc				= $this->input->post('ItemName');
		
		/*$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($Desc != ""){$this->db->like('ItemName', $Desc);} 
		
		/*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=================================================================*/
		
		$count_data = $this->db->count_all_results('ah_importrecur');
		
		$offset 	= $count_data - ($rows * $page);
		if($offset > 0){
			$rows = $rows;
		}
		else{
			$rows = $count_data - ($rows*($page-1));
		}
		/*========================end=======================================*/
		$result = $this->m_import_recur->get_all(); 
		
		for($i=0; $i<=($rows-1); $i++){
			// kalau master ambil dari get_status_master(), kalau transaksi get_status()
			$DepreciatedAMount = ($result[$i]->TotalInvoice / $result[$i]->AdvNetDueIn) * $result[$i]->PeriodUsed;
			
			$TotalOwing = $result[$i]->TotalInvoice - $DepreciatedAMount;
			
            $hasil[] = array(
				
				'NoTransaction' 	=>	$result[$i]->NoTransaction,
				'OldNoTransaction' 	=>	$result[$i]->OldNoTransaction,
				'DateTransaction' 	=>	$result[$i]->DateTransaction,
				'ItemName' 		=>	$result[$i]->ItemName,
				'TotalInvoice' 	=>	$result[$i]->TotalInvoice,
				'CurrencyRate' 	=>	$result[$i]->CurrencyRate,
				'PeriodUsed' 		=>	$result[$i]->PeriodUsed,
				'TotalOwing' 		=> $TotalOwing
			);
		}
		
		if(empty($hasil)){
			$emptyVar = array();
			echo json_encode($emptyVar);
		}
		else{
			$result = array();
			$result['total'] = $count_data;
			$result['rows'] = $hasil;
			echo json_encode($result);
		}
    }
	
	function get_data_adv(){
        $data = $this->m_import_recur->get_data_adv();
		
        echo json_encode($data);
    }
	
	function get_data_currency(){
        $data = $this->m_import_recur->get_data_currency();
		
        echo json_encode($data);
    }
	
	public function insert(){
		try{
			$txt_transaction_no	= $this->input->post('txt_transaction_no');
			$txt_date			= $this->input->post('txt_date');
			$cmb_ItemCode		= $this->input->post('cmb_ItemCode');
			$cmb_currency		= $this->input->post('cmb_currency');
			$cbg_vendor			= $this->input->post('cbg_vendor');
			$txt_vendro_addres			= $this->input->post('txt_vendro_addres');
			
			$txt_total_invoice	= $this->input->post('txt_total_invoice');
			$txt_currencyrate	= $this->input->post('txt_currencyrate');
			$txt_periodeuse		= $this->input->post('txt_periodeuse');
			$txt_category		= $this->input->post('txt_category');
			$txt_net_due		= $this->input->post('txt_net_due');
			$txt_terms			= $this->input->post('txt_terms');
			
			$pinv_number 		= $this->m_purchase_invoice->create_pi_number($txt_date);
			
			$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');
			}
			
			$PurchaseAccount = $this->m_account_journal->get_sys_advance_account('Advance','IDR', $txt_category);
			if($PurchaseAccount == false) {
				throw new Exception('Preferences Adv Payment untuk Purchase Account Belum Diseting Untuk Currency '.$cmb_currency.'');
			}
			
			/*=================End=============*/
			$this->db->trans_begin();
			
			$data = array(
				'NoTransaction' 	=> $pinv_number,
				'OldNoTransaction' 	=> $txt_transaction_no,
				'DateTransaction' 	=> date("Y-m-d", strtotime($txt_date)),
				'ItemName' 			=> $cmb_ItemCode,
				'TotalInvoice' 		=> $txt_total_invoice,
				'CurrencyRate' 		=> $txt_currencyrate,
				'PeriodUsed' 		=> $txt_periodeuse,
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_import_recur->insert($data);
			
			//$this->transaction['insert_group']['data'] = $data;
			
			/*
				Import Invoice
			*/
			$data_pi = array(
                'BranchCode' 	=> $this->session->userdata('branch'),
                'VendorCode' 	=> $cbg_vendor,
                'PInvDate' 		=> date("Y-m-d", strtotime($txt_date)),
                'PInvNumber' 	=> $pinv_number,
                'PRecDate' 		=> $txt_date,
                'PRecNumber' 	=> $pinv_number,
                'POrdNumber' 	=> $pinv_number,
                'VendInvNumber' => " ",
                'ShipmentDate' 	=> date("Y-m-d", strtotime($txt_date)),
                'ShipmentID' 	=> 1,
                'TermsPaymentID' => $txt_terms,
                'FOBID' 		=> 1,
                'VendorAddress' => $txt_vendro_addres,
                'CurrencyCode' 	=> $cmb_currency,
                'CurrencyRate' 	=> $txt_currencyrate,
                //'FiscalRate' 	=> $fiscal_rate,
                'PInvDesc' 		=> "Import Adv Payment",
                'PInvSubTotal' 	=> $txt_total_invoice,
                'PInvDiscount' 	=> 0,
                'PInvPPn10Pcnt' => 0,
                'PInvPPh22Pcnt' => 0,
                'PInvPPh23Pcnt' => 0,
                'PInvPPn10' 	=> 0,
                'PInvPPh22' 	=> 0,
                'PInvPPh23' 	=> 0,
                'PInvEstFreight' 	=> 0,
                'PInvTotalAmount' 	=> $txt_total_invoice,
                'PInvTotalDP' 		=> 0,
                'PInvTotalInvoice' 	=> $txt_total_invoice,
                'PPayTotalAmount' 	=> 0,
                'PInvTotalOwing' 	=> $txt_total_invoice,
                'PInvTaxesStatus' 	=> 0,
                'PInvInTaxStatus' 	=> 0,
                'TransStatus' 		=> 2,
                'CreatedBy' 		=> $this->session->userdata("username"),
                'CreatedAt' 		=> date('Y-m-d'),
                'LastUser' 			=> $this->session->userdata("username")
            );
			$this->m_import_recur->insert_pi_group($data_pi);
			
			//$this->transaction['insert_group_pi']['data'] = $data_pi;
			
			$detail_data_pi = array(
				'PRecNumber' 	=> $pinv_number,
				'PInvNumber' 	=> $pinv_number,
				'ItemCode' 		=> $cmb_ItemCode,
				'ItemDesc' 		=> $cmb_ItemCode,
				'itemUnit' 		=> "Unit",
				'itemQty' 		=> 1,
				'ItemPrice' 	=> $txt_total_invoice,
				'ItemDisc' 		=> 0,
				'ItemAmount' 	=> $txt_total_invoice,
				'ItemTaxPPn10' 	=> 0,
				'ItemTaxPPh22' 	=> 0,
				'ItemTaxPPh23' 	=> 0,
				'ItemTotalAmount' 	=> $txt_total_invoice,
				'ItemCategoryID' 	=> $txt_category,
				'ItemCategoryCode' 	=> $cmb_ItemCode,
				'ItemType' 			=> 2,
				'ItemStatus' 		=> 3,
				'ItemPPh22Status' 	=> 0,
				'ItemPPh23Status' 	=> 0,
				'ItemAdvNetDueIn' 	=> $txt_net_due,
				'ItemPriceNTax' 	=> $txt_total_invoice,
				'ItemCodeVendor' 	=> "",
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_import_recur->insert_pi_detail($detail_data_pi);
			
			//$this->transaction['insert_detail_pi']['data'] = $detail_data_pi;	
			//$this->transaction['insert_detail_pi']['PInvNumber'] = $pinv_number;	
			
			
			
			$txt_total_invoice_journal = $txt_total_invoice * $txt_currencyrate;
			
			/*
				Journal kedua
			*/
			$journal_debet_two = array(
                'PInvDate' 			=> date("Y-m-d", strtotime($txt_date)),
                'PInvNumber' 		=> $pinv_number,
                'PInvAccountNumber' => $PurchaseAccount->AccountNumber,
                'PInvSaldoDebet' 	=> $txt_total_invoice_journal,
                'PInvSaldoCredit' 	=> 0,
                'AmountCurrency' 	=> $txt_total_invoice,
                'PInvSignStatus' 	=> 0,
                'PInvDesc' 			=> "Import Adv Payment",
                'ItemCategoryCode' 	=> $txt_category,
                'LastUser' 			=> $this->session->userdata("username")
            );
			$this->m_import_recur->insert_pi_journal($journal_debet_two);
			//$this->transaction['insert_journal_pi_debet_two']['data'] = $journal_debet_two;
			
			$journal_kredit_two = array(
                'PInvDate' 			=> date("Y-m-d", strtotime($txt_date)),
                'PInvNumber' 		=> $pinv_number,
                'PInvAccountNumber' => $OpeningBalance->AccountNumber,
                'PInvSaldoDebet' 	=> 0,
                'PInvSaldoCredit' 	=> $txt_total_invoice_journal,
                'AmountCurrency' 	=> $txt_total_invoice,
                'PInvSignStatus' 	=> 0,
                'PInvDesc' 			=> "Import Adv Payment",
                'ItemCategoryCode' 	=> $txt_category,
                'LastUser' 			=> $this->session->userdata("username")
            );
			$this->m_import_recur->insert_pi_journal($journal_kredit_two);
			
			//$this->transaction['insert_journal_pi_kredit_two']['data'] = $journal_kredit_two;
			
			$data_app_finish = array(
				'AppFinished' => 1,
				'AppLevel1Status' => 1,
				'AppLevel1Code' => $this->session->userdata("username"),
				'AppLevel1Date' => date("Y-m-d")
			);
			$this->m_import_recur->update_pi_group($data_app_finish, $pinv_number);
			
			//$this->transaction['update_group_pi']['data'] = $data_app_finish;
			//$this->transaction['update_group_pi']['PInvNumber'] = $pinv_number;
			
			/*
				Masuk JV
			*/
			for($i=1; $i<=$txt_periodeuse; $i++){
				$DepreciatedAmount = ($txt_total_invoice / $txt_net_due);
				$DepreciatedAmount_Journal = ($txt_total_invoice / $txt_net_due) * $txt_currencyrate;
				
				$jv_number 			= $this->m_journalvoucher->create_jv_number($txt_date);
				
				$jv_group = array(
					'BranchCode' 		=> $this->session->userdata('branch'),
					'JVchDate' 			=> date("Y-m-d", strtotime($txt_date)),
					'JVchNumber' 		=> $jv_number,
					'JVchDesc' 			=> "Import Adv Payment / Recur",
					'JVchType' 			=> 0,
					'AppLevel1Status' 	=> 1,
					'AppLevel1Code' 	=> $this->session->userdata('username'),
					'AppLevel1Date' 	=> $txt_date,
					'AppLevel2Status' 	=> 1,
					'AppLevel2Code' 	=> $this->session->userdata('username'),
					'AppLevel2Date' 	=> $txt_date,
					'TransStatus' 		=> 2,
					
					'CreatedBy' 		=> $this->session->userdata('username'),
					'CreatedAt' 		=> date("YmdHis"),
					'LastUser' 			=> $this->session->userdata('username')
				);
				$this->m_import_recur->insert_jv_group($jv_group);
				
				//$this->transaction['insert_group_jv']['data'] = $jv_group;
				
				$jv_detail_debet = array(
					'JVchNumber' 		=> $jv_number,
					'JVchAccount' 		=> $OpeningBalance->AccountNumber,
					'JVchDebetSaldo' 	=> $DepreciatedAmount_Journal,
					'JVchCreditSaldo' 	=> 0,
					'JVchDetailMemo' 	=> "Import Adv Payment",
					'JVchDetailDept' 	=> " ",
					'JVchRate' 			=> 1,
					'CurrencyCode' 		=> $cmb_currency,
					'AssetCode' 		=> $cmb_ItemCode.'-'.$pinv_number,
					'LastUser' 			=> $this->session->userdata('username')
				);
				$this->m_import_recur->insert_jv_detail($jv_detail_debet);
				
				//$this->transaction['jv_detail_debet']['data'] = $jv_detail_debet;
				
				$jv_detail_credit = array(
					'JVchNumber' 		=> $jv_number,
					'JVchAccount' 		=> $PurchaseAccount->AccountNumber,
					'JVchDebetSaldo' 	=> 0,
					'JVchCreditSaldo' 	=> $DepreciatedAmount_Journal,
					'JVchDetailMemo' 	=> "Import Adv Payment",
					'JVchDetailDept' 	=> " ",
					'JVchRate' 			=> 1,
					'CurrencyCode' 		=> $cmb_currency,
					'AssetCode' 		=> $cmb_ItemCode.'-'.$pinv_number,
					'LastUser' 			=> $this->session->userdata('username')
				);
				$this->m_import_recur->insert_jv_detail($jv_detail_credit);
				
				//$this->transaction['jv_detail_credit']['data'] = $jv_detail_credit;
				/*====================END Detail JV==================================*/
				
				/*
					JV Journal 
				*/		
				$jv_journal_debet = array(
					'JVchDate' 			=> date("Y-m-d", strtotime($txt_date)),
					'JVchNumber' 		=> $jv_number,
					'JVchDesc' 			=> "Import Adv Payment",
					'JVchAccountNumber' => $OpeningBalance->AccountNumber,
					'JVchSaldoDebet' 	=> $DepreciatedAmount_Journal,
					'JVchSaldoCredit' 	=> 0,
					'JVchSignStatus' 	=> 1,
					'AmountCurrency' 	=> $DepreciatedAmount,
					'LastUser' 			=> $this->session->userdata('username')
				);
				$this->m_import_recur->insert_jv_journal($jv_journal_debet);
				
				//$this->transaction['jv_journal_debet']['data'] = $jv_journal_debet;
				
				$jv_journal_credit = array(
					'JVchDate' 			=> date("Y-m-d", strtotime($txt_date)),
					'JVchNumber' 		=> $jv_number,
					'JVchDesc' 			=> "Import Adv Payment",
					'JVchAccountNumber' => $PurchaseAccount->AccountNumber,
					'JVchSaldoDebet' 	=> 0,
					'JVchSaldoCredit' 	=> $DepreciatedAmount_Journal,
					'JVchSignStatus' 	=> 1,
					'AmountCurrency' 	=> $DepreciatedAmount,
					'LastUser' 			=> $this->session->userdata('username')
				);
				$this->m_import_recur->insert_jv_journal($jv_journal_credit);
				
				//$this->transaction['jv_journal_credit']['data'] = $jv_journal_credit;
				
				$data_app_finish_jv = array(
					'JVchTotalDebet' 	=> $DepreciatedAmount_Journal,
					'JVchTotalCredit' 	=> $DepreciatedAmount_Journal,
					'AppFinished' => 1
				);
				$this->m_import_recur->update_jv_group($data_app_finish_jv, $jv_number);
			}
			
			//$this->transaction['update_group_jv']['data'] = $data_app_finish_jv;
			//$this->transaction['update_group_jv']['JVNumber'] = $jv_number;
			
			
			$get_invoice_detail = $this->m_import_recur->get_invoice_recur($pinv_number);
			
			$data_detail_recur = array(
				'PInvDetailID' 	=> $get_invoice_detail->PInvDetailID,
				'PInvDate' 		=> date("Y-m-d", strtotime($txt_date)),
				'PInvNumber' 	=> $pinv_number,
				'PInvMemo' 		=> "Import Adv Payment",
				'ItemCode' 		=> $cmb_ItemCode,
				'ItemDesc'	 	=> $cmb_ItemCode,
				'ItemQty' 		=> 1,
				'ItemUnit' 		=> "Unit",
				'ItemAmount' 	=> $txt_total_invoice * $txt_currencyrate,
				'ItemTaxPPn10' 	=> 0,
				'ItemTaxPPh22' 	=> 0,
				'ItemTotalAmount' 	=> $txt_total_invoice * $txt_currencyrate,
				'ItemPPh22Status' 	=> 0,
				'ItemAdvNetDueIn' 	=> $txt_net_due,
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_import_recur->insert_detail_recur($data_detail_recur);
			
			//$this->transaction['insert_recur']['data'] = $data_detail_recur;
																						
			//$result_insert = $this->m_import_recur->insert_transaction($this->transaction);
			//$this->transaction 	= [];
			
			 /* =============================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, $pinv_number);

                $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, $pinv_number);
            }
            /* ==================================end====================================================== */
			
			echo json_encode($result);
		}
		
		catch (Exception $e){            
            $result['status']   = false;
            $result['message']  = $e->getMessage();
            echo json_encode($result);
        }
	}
}
