<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Supplier_Payment_Process extends CI_Controller
{
    var $main_menu_name = "supplier_payment_process";
    var $sub_menu_name = "supplier_payment_process";
    public function __construct()
    {
        parent::__construct();
       $this->load->model('Common_Model');
		$this->load->model('In_Type_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('Warehouse_Model');
		$this->load->model('Bank_Model');
		$this->load->model('User_Model');
		$this->load->model('Supplier_Payment_Process_Model');
    }
    public function index()
    {
        
        $data['main_menu_name'] = 'purchases';
		$data['sub_menu_name'] = 'Supplier_payment';
		$data['supplier'] = $this->Purchases_Model->get_supplier_list();
		$data['supplier_id'] = $this->input->get('sup_id');
		$data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
		$data['bank_list'] = $this->Bank_Model->get_all_bank_account();
        $data['user_list'] = $this->User_Model->get_all_cash_collector_users();
		$data['sales_list']=$this->Supplier_Payment_Process_Model->get_grn_complete_info_by_customer_id($this->input->get('sup_id'));
		$this->load->view('suppier_payment/suppier_payment',$data);
    }
    
    
    
    public function save_sale_multiple_payment()
    {	
        $this->load->library('form_validation'); //form validation lib
        $sale_pymnt_paying_by       = $this->input->post('sale_pymnt_paying_by');
       // $this->form_validation->set_rules('collector_id', 'Collector', '');        
        $this->form_validation->set_rules('suppier_id', 'Suppier', 'required');
        $this->form_validation->set_rules('warehouse_id', 'Warehouse', 'required');
        //$this->form_validation->set_rules('customer_id', 'Customer', 'required');
        $this->form_validation->set_rules('sale_pymnt_paying_by', 'Payment Type', 'required');
        $this->form_validation->set_rules('sale_pymnt_amount', 'Payment Amount', 'required');
        
        if($sale_pymnt_paying_by=="Cheque"){
            $this->form_validation->set_rules('sale_pymnt_cheque_no', 'Cheque No', 'required|is_unique[payment_given_master.payment_system_ref_no]');   
            //$this->form_validation->set_rules('bank_id', 'Bank', 'required');              
        }
        if($sale_pymnt_paying_by=="Credit Card"){
            $this->form_validation->set_rules('sale_pymnt_crdt_card_no', 'Credit Card Number', 'required');   
            $this->form_validation->set_rules('sale_pymnt_crdt_card_holder_name', 'Card Holder Name', 'required');  
            $this->form_validation->set_rules('sale_pymnt_crdt_card_month', 'Expire Month', 'required');  
            $this->form_validation->set_rules('sale_pymnt_crdt_card_year', 'Expire Year', 'required');   
            $this->form_validation->set_rules('sale_pymnt_crdt_card_type', 'Payment Methord', 'required');  
        }       
       
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'sale_id' => 0,
                'error' => 1,
                'disMsg' => validation_errors()
            );
            echo json_encode($st);
        } else {
        //--------------------------------------------------------------------------
        $total_val					= $this->input->post('sale_pymnt_amount');
        $customer_id                = intval($this->input->post('suppier_id'));
        $warehouse_id               = $this->input->post('warehouse_id');
		$bank_id                    = $this->input->post('bank_id');
        $cash_collector_id          = $this->input->post('collector_id');
        $warehouse_id               = $this->input->post('warehouse_id');
        $ref_no               = $this->input->post('ref_no');
                
        $sale_pymnt_date_time       = date('Y-m-d', strtotime($this->input->post('sale_pymnt_date_time')));
        $row                        = $this->input->post('row_c');
        $rowCount                   = $this->input->post('rowCount');
		$sale_note                = $this->input->post('sale_note');
		$sale_note_two                = $this->input->post('sale_note_two');
        $user_id                    = $this->session->userdata('ss_user_id');
        $sale_pymnt_added_date_time = date("Y-m-d");
        $data_item                  = array();
        $this->db->trans_start();
        $smp_last_id        = '0';
        $smp_id             = 0;
        $smp_no             = $this->Common_Model->gen_ref_number('pay_g_id','payment_given_master','PAY');;
        $sale_pymnt_cheque_no             = $this->input->post('sale_pymnt_cheque_no');
        $sale_pymnt_crdt_card_no          = $this->input->post('sale_pymnt_crdt_card_no');
        $sale_pymnt_crdt_card_holder_name = $this->input->post('sale_pymnt_crdt_card_holder_name');
        $sale_pymnt_crdt_card_month       = $this->input->post('sale_pymnt_crdt_card_month');
        $sale_pymnt_crdt_card_year        = $this->input->post('sale_pymnt_crdt_card_year');
        $sale_pymnt_crdt_card_type        = $this->input->post('sale_pymnt_crdt_card_type');
       
        $expiredate = date('Y-m-d', strtotime("+6 months", strtotime($this->input->post('sale_pymnt_date_time'))));
        $payment_ref_number="";
        $payment_method=$sale_pymnt_crdt_card_type ;
        $payment_type=0;
        $payee_name="";
        $payment_status=1;

        if($sale_pymnt_paying_by=="Cheque"){
            $payment_ref_number=$sale_pymnt_cheque_no;
            $payment_type=2;   
            $payment_status=1;         
        }
        if($sale_pymnt_paying_by=="Credit Card"){
            $payment_ref_number=$sale_pymnt_crdt_card_no;
            $payment_type=3;  
            $payee_name=$sale_pymnt_crdt_card_holder_name; 
            $payment_status=3;         
        }
        if($sale_pymnt_paying_by=="Cash"){
            $payment_type=1;
        }  
        
         if($sale_pymnt_paying_by=="credit_note"){
            $payment_type=5;
        } 
        $sp_data_item       = array(
            'payment_system_ref_no' => $smp_no,
            'pay_amount' => floatval($total_val),
            'user_id' => $user_id,
			'bank_id' => $bank_id,
            'account_id' => $customer_id,
            'system_date_time' => date("Y-m-d h:i:s") ,
            'warehouse_id' => $warehouse_id,
            'payment_method' => $payment_method,
            'payment_type' => $payment_type,
            'credit_card_expire_month' => $sale_pymnt_crdt_card_month,
            'credit_card_expire_year' => $sale_pymnt_crdt_card_year, 
            'ref_no' => $payment_ref_number,     
            'pay_g_date_time' => $sale_pymnt_date_time ,  
            'ref_no' => $ref_no ,
            'cheque_no' => $sale_pymnt_cheque_no ,
            'note' => $sale_note ,
           
        );
        $smp_id=$this->Supplier_Payment_Process_Model->save_grn_multiple_payment_header($sp_data_item);
        for ($i = 1; $i <= $rowCount; $i++) {
            if (isset($row[$i]['sale_id'][0])) {
                $collection = '';
                if (isset($row[$i]['collection'][0])) {
                    $collection = $row[$i]['collection'][0];
                }
                $data_item = array(
                    'invoice_id' => $row[$i]['sale_id'][0],
                    'allocation_amount' => floatval($row[$i]['amount'][0]),
                    'payment_type' => $payment_type,
                    'pgm_id' => $smp_id,

                );
                if ($collection) {
                    $this->Supplier_Payment_Process_Model->save_grn_multiple_payment_items($data_item);
                }
                $disMsg = "";
            }
        }
        $disMsg = '';
        $this->db->trans_complete();
        $trans_status = $this->db->trans_status();
        if ($trans_status == FALSE) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }       
        echo json_encode(array(
            'sale_id' => 1,
            'error' => 0,
            'disMsg' => $disMsg
        ));
         //-------------------------------------------------------------------------------------
    }
    }
    
    
    public function list_supplier_payment()
    {
        
        $data['main_menu_name'] = 'purchases';
		$data['sub_menu_name'] = 'list_supplier_payment';
		$this->load->view('suppier_payment/suppier_payment_list',$data);
    }
    
    public function get_list_supplier_payment($value='')
    {
           	$requestData= $_REQUEST;	
        	$start=$this->input->get('start');
        	$length=$this->input->get('length');
	        $search=$this->input->get('search');	
           $totalData =$this->Supplier_Payment_Process_Model->get_all_suplier_payment("","",$search);
	       $values = $this->Supplier_Payment_Process_Model->get_all_suplier_payment($start,$length,$search);
	       $totalFiltered=$totalData;
            $data = array();
            $pay_st;
            if (!empty($values)) {
                foreach ($values as $purchases) {
    
                $row = array();
                    $y_des=0;
                    $print_url=base_url("cheque_process")."?d=".date('Y-m-d', strtotime($purchases->pay_g_date_time))."&n=".$purchases->supp_company_name."&a=".$purchases->pay_amount."&y=$y_des";
                    $date=date_create($purchases->pay_g_date_time);
                    $date_only= date_format($date,"Y-m-d");
                    $row[] = $date_only;
                    $row[] = $purchases->payment_system_ref_no;
                    $row[] = $purchases->supp_company_name;
					$row[] = $purchases->ref_no." / ".$purchases->cheque_no;
					$row[] = $purchases->p_type_name;
					$row[] = $purchases->bank_name;
					$row[] = $purchases->note;
                    $row[] = number_format($purchases->pay_amount,2,'.',',');
                    $row[] = '<div class="text-center"><div class="btn-group text-left">
                    <button data-toggle="dropdown" class="btn btn-default btn-xs btn-primary dropdown-toggle" type="button">Actions <span class="caret"></span></button>
                    <ul role="menu" class="dropdown-menu pull-right">
                    <!--<li><a href="#" onclick="cheque_print('.$purchases->pay_g_id.','.$purchases->pay_g_id.','.$purchases->pay_g_id.');return false;"><i class="fa fa-print"></i> Cheque Print</a></li>-->
                    
                    <li style="cursor:pointer"><a target="_blank" href="'.$print_url.'"  ><i class="fa fa-print"></i> Print Cheque</a></li>
                    <li><a href="'.base_url("supplier_payment_process/supplier_multiple_payment_details").'?id='.$purchases->pay_g_id.'"> <i class="fa fa-file-text-o"></i> Payment Details </a></li>
                    <li><a href="#" onclick="fbs_click('.$purchases->pay_g_id.');return false;"><i class="fa fa-print"></i> Recipt Print</a></li>
                    </ul></div>
                    </div>';
                    $data[] = $row;
                }
                $output = array('data' =>$data,	"recordsTotal"    => intval( $totalData ), 	"recordsFiltered" => intval( $totalFiltered ),);
                echo json_encode($output);
            }else{
                $output = array('data' =>'');
                echo json_encode($output);
            }
       }
       
    public function supplier_multiple_payment_print()
    {
        $smp_id                    = $this->input->get('id');
        $data['mp_details']        = $this->Supplier_Payment_Process_Model->get_suplier_payment_details_by_id($smp_id);
        $this->load->model('Cheque_Process_Model');
        $mp_details                = array();
        $data['mp_itm_list']       = $this->Supplier_Payment_Process_Model->get_suplier_payment_item_list_by_id($smp_id);
        $data['mp_itm_grn_return_list']       = array();
        $data['mp_itm_sup_ajes_list']       = array();
        $data['mp_sales_list']       = array();
        $data['warehouse_details'] = array();
        $this->load->view('suppier_payment/supplier_multiple_payment_print', $data);
    }
    
     public function supplier_multiple_payment_details()
    {
        $smp_id                    = $this->input->get('id');
        $data['main_menu_name'] = 'purchases';
		$data['sub_menu_name'] = 'list_supplier_payment';
        $data['mp_details']        = $this->Supplier_Payment_Process_Model->get_suplier_payment_details_by_id($smp_id);
        $this->load->model('Cheque_Process_Model');
        $mp_details                = array();
        $data['mp_itm_list']       = $this->Supplier_Payment_Process_Model->get_suplier_payment_item_list_by_id($smp_id);
        $data['mp_itm_grn_return_list']       = array();
        $data['mp_itm_sup_ajes_list']       = array();
        $data['mp_sales_list']       = array();
        $data['warehouse_details'] = array();
        $this->load->view('suppier_payment/supp_pay_details', $data);
    }
    public function close_paid_grn_invoices()
    {
        $suppier_list=$this->Supplier_Payment_Process_Model->get_pending_grn_supplier();
        foreach($suppier_list as $row){
          $grn_list= $this->Supplier_Payment_Process_Model->get_grn_complete_info_by_customer_id($row['supplier_id']);
           $count=0;
           foreach($grn_list as $grn){
               $grn_value=$grn->total;
               $paid_and_return_amount=$this->Supplier_Payment_Process_Model->get_grn_payment_balance($grn->id);
               $balance=round($grn_value-$paid_and_return_amount, 2)        ;
               
               echo $balance."---".$paid_and_return_amount."---<br>";
               if($balance!=0){
                   continue;
               }else{
                   $data=array(
                        'payment_status'=>1,
                        'closed_date'=>date("Y-m-d h:i:s") ,
                       );
                       $this->Supplier_Payment_Process_Model->update_purcheses_table($grn->id,$data);
               }
               $count++;
           }
        }
        
        echo $count;
    }
   
	
	
	
	

}