<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/* 	
 * 	Author 	: Ferry / Tanggal : 15-01-2015
  Revisi 	: Fachri Nugraha
 */

class Purchase_giro extends CI_Controller {

    public $menu_id = 402;
    public $menu_model = array('m_purchase_giro',
        'm_vendors', 'm_taxes', 'm_account_journal', 'm_currency', 'm_employee');
    public $name = "Purchase Giro";
    public $jobtitle_status = array('0', '1');
    public $branch = "";
    public $ho;

    public function __construct() {
        parent::__construct();
        $this->load->model('custom/m_custom');
        $data_branch = $this->m_custom->get_branch_detail();
        $this->branch = $this->session->userdata('branch');

        if ($data_branch->BranchStatus == 0) {
            $this->ho = true;
        } else {
            $this->ho = false;
        }

        $this->load->model($this->menu_model);
        $this->load->helper('regex');
        $this->load->helper('message');
        $this->load->helper('status');
        $this->load->helper('lables');
        $this->load->helper('convert_date');
        $this->load->helper('custom_string_helper');
		$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_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);
                    //$data['list_vendor'] = $this->m_purchase_order->get_all_vendor();
                    $data['lables'] = get_lables_eng(); //tambah dhidhik, 050022016, untuk labelisasi, penamaan biar seperti ini saja biar enak copy-paste

                    $this->load->view('v_header');
                    $this->load->view('purchase/purchase_giro/v_purchase_giro', $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 = 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============================================================ */
        /* ========================jika kondisi tidak sama dengan kosong di find lakukan proses di if================= */
        if ($BranchCode != "") {
            $this->db->where('BranchCode', $BranchCode);
        } else {
            $this->db->where('BranchCode', $this->session->userdata('branch'));
        }

        if ($Number != "") {
            $this->db->like('PGirNumber', $Number);
        }
        if ($Desc != "") {
            $this->db->like('PGirDesc', $Desc);
        }
        if ($VendorCode != "") {
            $this->db->like('VendorCode', $VendorCode);
        }
        if ($TransStatus != '') {
            $this->db->where_in('TransStatus', $TransStatus);
        } else {
            /*
              default adalah 2,6. Finished dan Need Approval
             */
            $this->db->where_in('TransStatus', array(0, 1, 4, 5, 6, 7));
        }

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

        $count_data = $this->db->count_all_results('at_purchasegiro');
        $offset = $count_data - ($rows * $page);
        if ($offset > 0) {
            $rows = $rows;
        } else {
            $rows = $count_data - ($rows * ($page - 1));
        }
        /* ========================end======================================= */
        $result = $this->m_purchase_giro->get_all();

        for ($i = 0; $i <= ($rows - 1); $i++) {
            // kalau master ambil dari get_status_master(), kalau transaksi get_status()
            $TransStatus = get_status($result[$i]->TransStatus);

            $hasil[] = array(//change
                'BranchName' => $result[$i]->BranchName,
                'VendorName' => $result[$i]->VendorName,
                'TransNumber' => $result[$i]->PGirNumber,
                'PGirDate' => $result[$i]->PGirDate,
                'PGirTotalAmount' => $result[$i]->PGirTotalAmount,
                'PGirDesc' => $result[$i]->PGirDesc,
				'CreatedBy' => $result[$i]->CreatedBy,
                'TransStatus' => $TransStatus
            );
        }

        $result['total'] = $count_data;
        $result['rows'] = $hasil;
        echo json_encode($result);
    }
	
	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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);
                    

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $data['pgir_date'] = date('d-m-Y');

                    $this->load->view('v_header');
                    $this->load->view('purchase/purchase_giro/v_new_purchase_giro', $data);
                    $this->load->view('v_footer');
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
	public function ajax_item() {
        $vendor_code = $this->input->post('VendorCode');
		
        if (!empty($vendor_code)) {
            $result = $this->m_purchase_giro->get_detail_item_for_pgiro($vendor_code);
            echo json_encode($result);
        } else {
            echo '[]';
        }
        //echo $this->db->last_query();
    }
	
	public function edit() {
        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_edit($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)
                     */
                    //untuk ambil data dari session dan hak akses
                    $group_menu = $this->session->userdata('group_menu');

                    $data['menu_id'] = $this->menu_id;
                    $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
                    $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

                    //panggil model hak akses untuk autoriti
                    $data['group_user'] = $this->m_menu->group_user_autority($this->menu_id, $group_menu);

                    $id = str_replace($data['menu_link'] . '/edit/', "", $this->uri->uri_string());
                    $data['detail'] = $this->m_purchase_giro->get_detail($id);

                    if ($data['detail'] != false) {
                        $this->load->view('v_header');
                        $this->load->view('purchase/purchase_giro/v_edit_purchase_giro', $data);
                        $this->load->view('v_footer');
                    }
                }
            } else {
                redirect(base_url() . 'error', 'refresh');
            }
        } else {
            redirect(base_url() . 'login', 'refresh');
        }
    }
	
	public function insert() {
		$BranchCode = $this->session->userdata('branch');
		$VendorCode = $this->input->post('cbg_vendor');
		$Branch_PaidFor = $this->input->post('cbg_branch');
		$Currency_Code = $this->input->post('hdn_vend_curr_code');
		$BankPayment = $this->input->post('cbg_bank');
		$PGirDate = date("Y-m-d", strtotime($this->input->post('txt_pgir_date')));
		$PGirNumber = $this->m_purchase_giro->create_pi_number($PGirDate);
		$txa_description = $this->input->post('txa_description');
		$DateGiro = date("Y-m-d", strtotime($this->input->post('txt_date_giro')));
		$hdn_vend_curr_code = $this->input->post('hdn_vend_curr_code');
		$hdn_bank_curr_code = $this->input->post('hdn_bank_curr_code');
		$txt_vendor_rate = $this->input->post('txt_vendor_rate');
		$txt_bank_curr_rate = $this->input->post('txt_bank_curr_rate');
		$txt_cheque_no = $this->input->post('txt_cheque_no');
		$txt_total_amount = $this->input->post('txt_total_amount');
		$hdn_total_currency = $this->input->post('hdn_total_currency');
		
		$detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
		
		$this->db->trans_begin();
		if(count($detail) > 0){
			$data = array(
				'BranchCode' 		=> $BranchCode,
				'BranchPaidFor' 	=> $Branch_PaidFor,
				'VendorCode' 		=> $VendorCode,
				'PGirDate' 			=> $PGirDate,
				'PGirNumber' 		=> $PGirNumber,
				'PGirDesc' 			=> $txa_description,
				'DateGiro' 			=> $DateGiro,
				'CurrencyCode' 		=> $hdn_vend_curr_code,
				'BankCurrCode' 		=> $hdn_bank_curr_code,
				'BankCurrRate' 		=> $txt_bank_curr_rate,
				'ChequeNumber' 		=> $txt_cheque_no,
				'PGirTotalAmount' 	=> $txt_total_amount,
				'PGirTotalCurrency' => $hdn_total_currency,
				'TransStatus' 		=> 5,
				'BankPayment' 		=> $BankPayment,
				'CreatedBy' 		=> $this->session->userdata("username"),
            	'CreatedAt' 		=> date('Y-m-d'),
				'LastUser' 			=> $this->session->userdata("username")
			);
			
			$this->m_purchase_giro->insert($data);
			
			foreach($detail as $row_detail){
				if ($row_detail->Paid == 'Yes') {
					$invoice_number = $row_detail->Invoice_Number;
					$Invoice_Date = $row_detail->Invoice_Date;
					$Invoice_amount = $row_detail->Invoice_Amount;
					$Invoice_owing = $row_detail->Invoice_Owing;
					$Load_Rounding = $row_detail->Load_Rounding;
					$Payment_Amount = $row_detail->Payment_Amount;
					$Invoice_Type = $row_detail->Invoice_Type;
					$Payment_Currency = $row_detail->Payment_Currency;
					
					if($Invoice_Type == "PO"){
						$invoice_type = 1;
					}
					else{
						$invoice_type = 0;	
					}
					
					$data_payment = $this->m_purchase_giro->get_payment($invoice_number, $invoice_type, 0);
					foreach($data_payment as $row_payment){
						$ipay_category_ratio = $row_payment->ItemCategoryRatio;
						
						$amount_invoice_ratio = $Invoice_amount * ($ipay_category_ratio / 100);
						$amount_invoice_owing = $Invoice_owing * ($ipay_category_ratio / 100);
						$amount_round = $Load_Rounding * ($ipay_category_ratio / 100);
						$amount_round = $Load_Rounding * ($ipay_category_ratio / 100);
						$Payment_Amount_ratio = $Payment_Amount * ($ipay_category_ratio / 100);
						$currency_payable = $Payment_Currency * ($ipay_category_ratio / 100);
						
						$data_detail = array(
							'InvoicePaymentID'  => $row_payment->InvoicePaymentID,
							'PGirNumber' 		=> $PGirNumber,
							'PInvNumber' 		=> $invoice_number,
							'PInvDate' 			=> $Invoice_Date,
							'PInvAmount' 		=> $amount_invoice_ratio,
							'PInvOwing' 		=> $amount_invoice_owing,
							'PGirRounded' 		=> $amount_round,
							'PGirAmount' 		=> $Payment_Amount_ratio,
							'PGirCurrency' 		=> $currency_payable,
							'PGirTotalAmnt' 	=> ($amount_round + $Payment_Amount_ratio),
							'PGirPaidStatus' 	=> 1,
							'PGirInvoiceType' 	=> $Invoice_Type, 
							'LastUser' 			=> $this->session->userdata("username")
						);
						
						$this->m_purchase_giro->insert_detail($data_detail);
					}
				}
			}
			
			
			if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 0, "$PGirNumber");
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'insert', 1, "$PGirNumber");
            }
		}
		else{
			$result['status'] = false;
            $result['message'] = "Transaksi gagal di simpan, transaksi tidak memounya Detail Pembayaran";
		}
		
		echo json_encode($result);
	}
	
	public function update() {
		$txt_pgir_no = $this->input->post('txt_pgir_no');
		
		$txt_bank_curr_rate = $this->input->post('txt_bank_curr_rate');
		$txt_cheque_no = $this->input->post('txt_cheque_no');
		$txa_description = $this->input->post('txa_description');
		$DateGiro = date("Y-m-d", strtotime($this->input->post('txt_date_giro')));
		$txt_total_amount = $this->input->post('txt_total_amount');
		$hdn_total_currency = $this->input->post('hdn_total_currency');
		
		$detail_post = $this->input->post('detail');
        $detail = json_decode($detail_post);
		
		$this->db->trans_begin();
		if(count($detail) > 0){
			$data = array(
				'PGirDesc' 			=> $txa_description,
				'DateGiro' 			=> $DateGiro,
				'BankCurrRate' 		=> $txt_bank_curr_rate,
				'ChequeNumber' 		=> $txt_cheque_no,
				'PGirTotalAmount' 	=> $txt_total_amount,
				'PGirTotalCurrency' => $hdn_total_currency,
				'LastUser' 			=> $this->session->userdata("username")
			);
			$this->m_purchase_giro->update($data, $txt_pgir_no);
			
			foreach($detail as $row_detail){
				if($row_detail->Paid == 'Yes'){
					$invoice_number = $row_detail->Invoice_Number;
					$Invoice_Date = $row_detail->Invoice_Date;
					$Invoice_amount = $row_detail->Invoice_Amount;
					$Invoice_owing = $row_detail->Invoice_Owing;
					$Load_Rounding = $row_detail->Load_Rounding;
					$Payment_Amount = $row_detail->Payment_Amount;
					$Invoice_Type = $row_detail->Invoice_Type;
					$Payment_Currency = $row_detail->Payment_Currency;
					
					$data_ppay_detail = $this->m_purchase_giro->get_pgir_detail($invoice_number, $txt_pgir_no);
					foreach($data_ppay_detail as $row_payment){
						$payament_ratio = $this->m_purchase_giro->get_payment_by_id($row_payment->InvoicePaymentID);
                        $ipay_category_ratio = $payament_ratio[0]->ItemCategoryRatio;
						
						$amount_invoice_ratio = $Invoice_amount * ($ipay_category_ratio / 100);
						$amount_invoice_owing = $Invoice_owing * ($ipay_category_ratio / 100);
						$amount_round = $Load_Rounding * ($ipay_category_ratio / 100);
						$amount_round = $Load_Rounding * ($ipay_category_ratio / 100);
						$Payment_Amount_ratio = $Payment_Amount * ($ipay_category_ratio / 100);
						$currency_payable = $Payment_Currency * ($ipay_category_ratio / 100);
						
						$data_detail = array(
							'PGirRounded' 		=> $amount_round,
							'PGirAmount' 		=> $Payment_Amount_ratio,
							'PGirCurrency' 		=> $currency_payable,
							'PGirTotalAmnt' 	=> ($amount_round + $Payment_Amount_ratio),
							'LastUser' 			=> $this->session->userdata("username")
						);
						
						$this->m_purchase_giro->update_detail($data_detail, $row_payment->PGirDetailID);
					}
				}
				else{
					
				}
			}
			
			if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $result['status'] = FALSE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 0, "$txt_pgir_no");
            } else {
                $this->db->trans_commit();
                $result['status'] = TRUE;
                $result['message'] = get_notification_transaksi($this->name, 'update', 1, "$txt_pgir_no");
            }
		}
		else{
			$result['status'] = false;
            $result['message'] = "Transaksi gagal di simpan, transaksi tidak memounya Detail Pembayaran";
		}
		
		echo json_encode($result);
	}
	
	public function suspend_data() {
		$ppay_number = $this->input->post('id');
		$this->db->trans_begin();
		$data_pp = array(
            'TransStatus' => 3,
            'LastUser' => $this->session->userdata("username")
        );

        $this->m_purchase_giro->update($data_pp, $ppay_number);
		
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('suspend', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('suspend', 1);
        }
        echo json_encode($result);
	}
	
	function outstanding_invoice(){
		$detail_post = $this->input->post('Detail');
        $detail = json_decode($detail_post);
		
		foreach($detail as $row_detail){
			$InvoiceAmount 	= $row_detail->Invoice_Amount;
			$Invoice_Number = $row_detail->Invoice_Number;
			$Payment_Amount 	= $row_detail->Payment_Amount;
			
			/*
				Trans Status 1 Purchase Giro
			*/
			$get_purchase_giro_status_on_progres = $this->m_purchase_giro->get_purchase_giro_status_on_progres($Invoice_Number);
			$PGInvTotalAmount 		= empty($get_purchase_giro_status_on_progres->PaymentAmount) ? 0 : $get_purchase_giro_status_on_progres->PaymentAmount;
			
			
			$get_purchase_payment = $this->m_purchase_giro->get_purchase_payment($Invoice_Number);
			$PPTotalAmount 		= empty($get_purchase_payment->PaymentAmount) ? 0 : $get_purchase_payment->PaymentAmount;
			
			$get_purchase_journal = $this->m_purchase_giro->get_purchase_journal($Invoice_Number);
			$PJTotalAmount 		= empty($get_purchase_journal->PaymentAmount) ? 0 : $get_purchase_journal->PaymentAmount;
			
			$Outstanding = $InvoiceAmount - ($PGInvTotalAmount + $PPTotalAmount + $PJTotalAmount + $Payment_Amount);
			
			if($Outstanding < 0){
				$this->db->trans_rollback();
				$result['status'] = FALSE;
				$result['message'] = "Transaksi gagal di Approve Pembayaran sudah melebihi Invoice Amount dengan no Transaksi ".$Invoice_Number."";
				
				echo json_encode($result);
                die();
			}
			else{
				$result['status'] = true;
			}
		}
	}
	
	public function approval() {
		$this->db->trans_begin();
		$PGirNumber = $this->input->post('PGirNumber');
		$detail_post = $this->input->post('Detail');
        $detail = json_decode($detail_post);
		
		foreach($detail as $row_detail){
			$InvoiceAmount 	= $row_detail->Invoice_Amount;
			$Invoice_Number = $row_detail->Invoice_Number;
			$Payment_Amount 	= $row_detail->Payment_Amount;
			$Invoice_Type 	= $row_detail->Invoice_Type;
			
			/*
				Trans Status 1 Purchase Giro
			*/
			if($Invoice_Type == 'PO'){
				$get_purchase_giro_status_on_progres = $this->m_purchase_giro->get_purchase_giro_status_on_progres($Invoice_Number);
				$PGInvTotalAmount 		= empty($get_purchase_giro_status_on_progres->PaymentAmount) ? 0 : $get_purchase_giro_status_on_progres->PaymentAmount;
				
				$get_purchase_payment_finish = $this->m_purchase_giro->get_purchase_payment_finish($Invoice_Number);
				$PPTotalAmount_Finish 		= empty($get_purchase_payment_finish->PaymentAmount) ? 0 : $get_purchase_payment_finish->PaymentAmount;
				
				$get_purchase_payment = $this->m_purchase_giro->get_purchase_payment($Invoice_Number);
				$PPTotalAmount 		= empty($get_purchase_payment->PaymentAmount) ? 0 : $get_purchase_payment->PaymentAmount;
				
				$get_purchase_invoice = $this->m_purchase_giro->get_purchase_invoice($Invoice_Number);
				$PInvTotalDP 		= empty($get_purchase_invoice->PInvTotalDP) ? 0 : $get_purchase_invoice->PInvTotalDP;
				
				$Outstanding = ($InvoiceAmount - $PInvTotalDP) - ($PGInvTotalAmount + $PPTotalAmount + $PPTotalAmount_Finish);
				if($Outstanding < 0){
					$this->db->trans_rollback();
					$result['status'] = FALSE;
					$result['message'] = "Transaksi gagal di Approve Pembayaran sudah melebihi Invoice Amount dengan no Transaksi ".$Invoice_Number."";
					
					echo json_encode($result);
					die();
				}
			}
			else{
				$get_purchase_giro_status_on_progres = $this->m_purchase_giro->get_purchase_giro_status_on_progres($Invoice_Number);
				$PGInvTotalAmount 		= empty($get_purchase_giro_status_on_progres->PaymentAmount) ? 0 : $get_purchase_giro_status_on_progres->PaymentAmount;
				
				$get_purchase_payment_finish = $this->m_purchase_giro->get_purchase_payment_finish($Invoice_Number);
				$PPTotalAmount_Finish 		= empty($get_purchase_payment_finish->PaymentAmount) ? 0 : $get_purchase_payment_finish->PaymentAmount;
				
				
				$get_purchase_payment = $this->m_purchase_giro->get_purchase_payment($Invoice_Number);
				$PPTotalAmount 		= empty($get_purchase_payment->PaymentAmount) ? 0 : $get_purchase_payment->PaymentAmount;
				
				$get_purchase_journal = $this->m_purchase_giro->get_purchase_journal($Invoice_Number);
				$PJTotalAmount 		= empty($get_purchase_journal->PaymentAmount) ? 0 : $get_purchase_journal->PaymentAmount;
				
				$get_purchase_invoice = $this->m_purchase_giro->get_purchase_invoice($Invoice_Number);
				$PInvTotalDP 		= empty($get_purchase_invoice->PInvTotalDP) ? 0 : $get_purchase_invoice->PInvTotalDP;
				
				$Outstanding = ($InvoiceAmount - $PInvTotalDP) - ($PGInvTotalAmount + $PPTotalAmount + $PJTotalAmount + $PPTotalAmount_Finish);
				if($Outstanding < 0){
					$this->db->trans_rollback();
					$result['status'] = FALSE;
					$result['message'] = "Transaksi gagal di Approve Pembayaran sudah melebihi Invoice Amount dengan no Transaksi ".$Invoice_Number."";
					
					echo json_encode($result);
					die();
				}
			}
		}
		
		$data_pp = array(
			'TransStatus' => 1,
			'LastUser' => $this->session->userdata("username")
		);

		$this->m_purchase_giro->update($data_pp, $PGirNumber);
		
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
            $result['message'] = get_notification('approval', 0);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification('approval', 1);
        }
        echo json_encode($result);
	}
	
	function reverse_data_detail() {
		$this->db->trans_begin();
		$txt_pgir_no = $this->input->post('txt_pgir_no');
		$txt_cheque_no = $this->input->post('txt_cheque_no');
		$hdn_transstatus = $this->input->post('hdn_transstatus');
		
		$get_detail_preq = $this->m_purchase_giro->get_purchase_payment_reverse($txt_pgir_no);
				
		if($get_detail_preq){
			$this->db->trans_rollback();
			$result['status'] = FALSE;
			$result['message'] = "Transaksi gagal di Reverse, Silahkan Reverse terlebih dahulu Purchase Payment dengan No Chek/Giro ".$txt_cheque_no."";
			
			echo json_encode($result);
			die();
		}
		else{
			$data_pp = array(
				'TransStatus' => 5,
				'LastUser' => $this->session->userdata("username")
			);
	
			$this->m_purchase_giro->update($data_pp, $txt_pgir_no);	
		}
		
		if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $result['status'] = FALSE;
			$result['message'] = get_notification_transaksi($this->name, 'reverse', 0, $txt_pgir_no);
        } else {
            $this->db->trans_commit();
            $result['status'] = TRUE;
            $result['message'] = get_notification_transaksi($this->name, 'reverse', 1, $txt_pgir_no);
        }
        echo json_encode($result);
	}
	
	public function ajax_item_for_edit() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $invoice_number = str_replace($data['menu_link'] . '/ajax_item_for_edit/', "", $this->uri->uri_string());

        if (!empty($invoice_number)) {
            $result = $this->m_purchase_giro->get_detail_invoice($invoice_number);
			
            echo json_encode($result);
        } else {
            echo '[]';
        }
    }
	
	function to_preview($obj_string = null) {
//        $data['list'] = $this->m_purchase_payment->get_all2($this->ho);
        $data['menu_id']        = $this->menu_id;
        $data['menu_label']     = $this->m_menu->get_menulabel($this->menu_id);
        $data['menu_link']      = $this->m_menu->get_menulink($this->menu_id);
        
        $data_filter            = arrayParamInUrlToStr($obj_string);
		$data['branch_code'] = $data_filter['cmb_branch'];
		$data['company_code'] = $data_filter['cmb_company'];
        $data['list']           = $this->m_purchase_giro->get_all_to_print($data_filter);
        
        $this->load->view('v_header');
        $this->load->view('purchase/purchase_giro/v_preview_purchase_giro', $data);
        $this->load->view('v_footer');
    }
	
	function to_print_detail() {
        $data['menu_link'] = $this->m_menu->get_menulink($this->menu_id);
        $data['menu_label'] = $this->m_menu->get_menulabel($this->menu_id);

        $id = str_replace($data['menu_link'] . '/to_print_detail/', "", $this->uri->uri_string());

        if ($id != "") {
            $data['detail'] = $this->m_purchase_giro->get_detail_print($id);

            $data['list'] = $this->m_purchase_giro->get_detail_invoice_print($data['detail']->PGirNumber);
            $this->load->view('v_header');
			$this->load->view('purchase/purchase_giro/v_print_detail_purchase_giro', $data);
            $this->load->view('v_footer');
        }
    }
}
