<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Payment_Process extends CI_Controller
{
    var $main_menu_name = "sale_multiple_payment";
    var $sub_menu_name = "sale_multiple_payment";
    public function __construct()
    {
        parent::__construct();
        date_default_timezone_set("Asia/Colombo");
        $this->load->model('Sales_Model');
        $this->load->model('Supplier_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Common_Model');
        $this->load->model('Tax_Rates_Model');
        $this->load->model('Customer_Model');
        $this->load->model('Sequerty_Model');
        $this->load->model('Product_Models');
        $this->load->model('Expenses_Model');
        $this->load->model('category_models');
        $this->load->model('Unit_Model');
        $this->load->model('User_Model');
        $this->load->model('Payment_Process_Model');
        $this->load->model('Bank_Model');
        $this->load->model('Sale_Multiple_Payment_Model');
        
    }
    public function index()
    {
        $data['expenses']       = $this->Expenses_Model->get_all_expenses();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'payment_process';
        $this->load->view('payment/return_payment_list', $data);
    }
    public function itemlist()
    {
        $data['expenses']       = $this->Expenses_Model->get_all_expenses();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = $this->sub_menu_name;
        $this->load->view('expenses', $data);
    }
    public function manage()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'manage';
        $customer_id            = $this->uri->segment('3');
       $retun_cheque = $this->Payment_Process_Model->get_cheque_return_to_colse($customer_id);
       foreach($retun_cheque as $rc){
        $id          = $rc->ret_pay_id; 
        $total_amount=  $rc->total_return_amount;
        $paid_amount=$this->Payment_Process_Model->get_total_cheque_return_paid($id);
        $balance_amount=$total_amount- $paid_amount;
        if( $balance_amount==0){

            $data_array=array(
                "return_pay_status"=>2,
                "settlemet_date"=>date('Y-m-d'),
            );
            $this->Payment_Process_Model->close_settled_cheque($id,$data_array);
        }
       }
       $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
       $data['customer_list']  = $this->Customer_Model->get_all_customers();
       $data['ch_return_list']     = $this->Payment_Process_Model->get_cheque_return_list($customer_id);
       $data['bank_list'] = $this->Bank_Model->get_all_bank();
       $data['user_list'] = $this->User_Model->get_all_cash_collector_users();
       $data['cr_limit_list'] =array();        
       $data['customer_id']    = $customer_id;


        $this->load->view('payment/cheq_return_multiple_payment', $data);
    }
    public function save_cheq_re_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', 'required');        
        $this->form_validation->set_rules('customer_id', 'Customer', '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[sale_multiple_payment.payment_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('customer_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;
        $old_in_smp_last_id = $this->Sale_Multiple_Payment_Model->get_next_ref_no();
        $old_in_smp_last_id = $old_in_smp_last_id->smp_last_id;
        $smp_last_id        = $old_in_smp_last_id + 1;
        $smp_no             = 'MP/' . sprintf('%03d', $smp_last_id);
        $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;
        }       
        $sp_data_item       = array(
            'smp_no' => $smp_no,
            'smp_last_id' => $smp_last_id,
            'smp_amount' => floatval($this->input->post('smp_amount')),
            'smp_no' => $smp_no,
            'user_id' => $user_id,
			'bank_id' => $bank_id,
            'customer_id' => $customer_id,
            'smp_added_date' => date("Y-m-d h:i:s") ,
            'warehouse_id' => $warehouse_id,
            'payment_method' => $payment_method,
            'payment_type' => $payment_type,
            'payment_expire_date_cq' => $expiredate,
            'payment_status' => $payment_status,            
            'payee_name' => $payee_name,
            'credit_card_expire_month' => $sale_pymnt_crdt_card_month,
            'credit_card_expire_year' => $sale_pymnt_crdt_card_year, 
            'payment_ref_no' => $payment_ref_number,     
            'payment_date' => $sale_pymnt_date_time ,  
            'ref_no' => $ref_no ,   
            'collector_id' => $cash_collector_id ,    
            
        );
        $this->Payment_Process_Model->save_sale_multiple_payment_header($sp_data_item);
        $smp_id                           = $this->db->insert_id();        
        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];
                }
				//if($this->input->post('sale_pymnt_cheque_no'))
				//$sale_note.= '<br />Cheque Value:'.$total_val;
                $data_item = array(
                    'ch_return_id' => $row[$i]['sale_id'][0],
                    'paid_amount' => floatval($row[$i]['amount'][0]),                    
                    'smp_id' => $smp_id,
					
                );
                if ($collection) {
                    $this->Payment_Process_Model->save_cheq_return_multiple_payment($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
        ));
        //echo "efefe";
         //-------------------------------------------------------------------------------------
    }
    }
    public function expenses_add_row()
    {
        $product_id        = $this->input->post('id');
        $rowCount          = $this->input->post('rowCount');
        $pro_dlts          = $this->Product_Models->get_product_by_id($product_id);
        $supp_id           = $this->input->post('supp_id');
        $cat_id            = $this->input->post('cat_id');
        $exp_voucher_no    = $this->input->post('exp_voucher_no');
        $exp_datetime      = $this->input->post('exp_datetime');
        $row_details       = '';
        $msg               = '';
        $error             = false;
        $selbox            = '';
        $tmp_th_e          = $rowCount;
        $pymnt_cheque_date = '';
        $required_date     = date('m/d/Y');
        $this->load->library('form_validation');
        $this->form_validation->set_rules('supp_id', 'Supplier', 'required');
        if (!$exp_datetime) {
            $error = true;
            $msg .= "Voucher Date, ";
        }
        if (!$error) {
            $prodcut_name_fld_type = 'hidden';
            $prodcut_name_txt      = $pro_dlts->product_name;
            if ($pro_dlts->product_name == 'Other') {
                $prodcut_name_fld_type = 'text';
                $prodcut_name_txt      = '';
            }
            $unit_list    = $this->Unit_Model->get_all_unit_list();
            $unit_sel_box = '';
            $unit_sel_box .= "<select id=\"product_unit_$tmp_th_e\" class=\"\" name=\"row_e[$tmp_th_e][product_unit][]\">";
            $unit_sel_box .= "<option value=\"\">
                            -Select-
                            </option>";
            foreach ($unit_list as $row) {
                $sel = '';
                if ($pro_dlts->product_unit == $row->unit_id) {
                    $sel = " selected=\"selected\"";
                } else if ($prodcut_name_txt == '') {
                    if ($row->unit_id == 6) {
                        $sel = " selected=\"selected\"";
                    }
                }
                $unit_sel_box .= "<option value=\"$row->unit_id\" $sel>
                                $row->unit_name
                            </option>";
            }
            $unit_sel_box .= "
                        </select>";
            $row_details = "
            <tr id=\"row_e_$tmp_th_e\">
            <td class=\"text-left\">
             $prodcut_name_txt
            <input type=\"$prodcut_name_fld_type\" style=\"width:100%; text-align:left\" name=\"row_e[$tmp_th_e][product_name][]\" id=\"product_name_$tmp_th_e\" value=\"$pro_dlts->product_name\" class=\"pymnt_amount\">
            <input type=\"hidden\" style=\"width:100%; text-align:left\" name=\"row_e[$tmp_th_e][product_id][]\" id=\"product_id_$tmp_th_e\" value=\"$pro_dlts->product_id\" class=\"product_id\">
            </td>
            <td>$unit_sel_box</td>
            <td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][expitm_qty][]\" id=\"expitm_qty_$tmp_th_e\" value=\"1.00\" class=\"expitm_qty\" onchange=\"changeQtyByProductID(this.value,$tmp_th_e);\" onclick=\"this.select(); setTmpVal(this.value);\"></td>
            <td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][product_cost][]\" id=\"product_cost_$tmp_th_e\" value=\"$pro_dlts->product_cost\" class=\"product_cost\" onchange=\"calculateTotal();\" ></td>
            <td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][expitm_dis][]\" id=\"expitm_dis_$tmp_th_e\" value=\"\" class=\"expitm_dis\" onchange=\"changeDiscountByProductID(this.value,1);\" onclick=\"this.select(); setTmpVal(this.value);\">
            <input type=\"hidden\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][expitm_dis_val][]\" id=\"expitm_val_$tmp_th_e\" value=\"\" class=\"expitm_dis_val\">
            </td>
            <td><input type=\"text\" style=\"width:100%; text-align:right\" name=\"row_e[$tmp_th_e][sub_total_item][]\" id=\"sub_total_item_$tmp_th_e\" value=\"\" class=\"\" readonly></td>
            <td><a onclick=\"deleteExpensesItem($tmp_th_e)\"><i style=\"cursor:pointer;\" title=\"Remove\" id=\"1446800197032\" class=\"fa fa-times tip podel\"></i></a></td>
            </tr>
            ";
            $e           = array(
                'status' => 1,
                'row_details' => $row_details,
                'msg' => $row_details
            );
            echo json_encode($e);
        } else {
            $e = array(
                'status' => 0,
                'row_details' => '',
                'msg' => $msg
            );
            echo json_encode($e);
        }
    }
    public function view()
    {
        $data['main_menu_name']    = $this->main_menu_name;
        $data['sub_menu_name']     = '';
        $exp_id                    = $this->uri->segment('3');
        $data['exp_item_list']     = $this->Expenses_Model->get_exp_item_list_by_exp_id($exp_id);
        $data['exp_details']       = $this->Purchases_Order_Model->get_exp_info($exp_id);
        $data['customer_details']  = $this->Customer_Model->get_customer_info($data['exp_details']['customer_id']);
        $data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($data['exp_details']['warehouse_id']);
        $data['exp_id']            = $exp_id;
        $this->load->view('expenses_view', $data);
    }
    public function get_next_ref_no()
    {
        $query            = $this->Expenses_Model->get_next_ref_no();
        $result           = $query->row();
        $exp_reference_no = sprintf("%05d", $result->exp_id + 1);
        $exp_reference_no = $exp_reference_no;
        echo json_encode(array(
            'exp_reference_no' => $exp_reference_no
        ));
    }
    public function expenses_details()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = '';
        $exp_id                 = $this->uri->segment('3');
        if (isset($exp_id)) {
            $data['exp_details'] = $this->Expenses_Model->get_expenses_details_by_id($exp_id);
            $data['expitm_list'] = $this->Expenses_Model->get_expenses_items_by_id($exp_id);
        }
        $data['exp_id'] = $exp_id;
        $this->load->view('expenses_details', $data);
    }
    public function sale_multiple_payment_print()
    {
        $smp_id                    = $this->uri->segment('3');
        $data['mp_details']        = $this->Sale_Multiple_Payment_Model->get_sale_multiple_payment_details_by_id($smp_id);
        $mp_details                = $data['mp_details'];
        $data['mp_itm_list']       = $this->Sale_Multiple_Payment_Model->get_sale_multiple_payment_items_by_id($smp_id);
        $data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($data['mp_details']->warehouse_id);
        $this->load->view('models/sale_multiple_payment_print', $data);
    }
	
	function delete_smp()
    {
		$smp_id        	= $this->input->get('smp_id');
		$result			= $this->Sale_Multiple_Payment_Model->delete_sale_multiple_payment_by_id($smp_id);
		//echo $result;
		//$result = 0;
		$data = array('result'=>$result);
		//print_r($data);
		return json_encode($data);
	}
    public function exp_details()
    {
        $exp_id                    = $this->input->get('exp_id');
        $data['exp_details']       = $this->Expenses_Model->get_exp_info($exp_id);
        $data['exp_item_list']     = $this->Expenses_Model->get_exp_item_list_by_exp_id($exp_id);
        $data['customer_details']  = $this->Customer_Model->get_customer_info($data['exp_details']['customer_id']);
        $data['warehouse_details'] = $this->Warehouse_Model->get_warehouse_info($data['exp_details']['warehouse_id']);
        $data['cr_limit_list']     = $this->Common_Model->get_all_cr_limit();
        $this->load->view('models/expenses_print', $data);
    }
    public function get_retured_cheque_list()
    {
        
        $data          = array();
        $cheq_return      = $this->Payment_Process_Model->get_all_cheque_return();
        $totalData     = count($cheq_return);
        $totalFiltered = $totalData;
        foreach ($cheq_return as $row) {

            $return_date = date('Y-m-d', strtotime($row['return_date']));
            $today=date('Y-m-d');
            $date1=date_create($return_date);
            $date2=date_create($today);
            $diff=date_diff($date1,$date2);
            $nestedData            = array();  
            $smp_id                = $row['ret_pay_id'];
            $total_paid_amount =$this->Payment_Process_Model->get_total_cheque_return_paid($smp_id);;           
            $nestedData[]          = $row['pay_ret_ref_no'];
            $nestedData[]          = $row['cus_name'];
            $nestedData[]          = $row['payment_ref_no'];
            $nestedData[]          = $row['payment_date'];
            $nestedData[]          = $row['bank_name']; 
            $nestedData[]          = $row['return_date'];
            $nestedData[]          = $row['user_first_name']; 
            $nestedData[]          = $row['smp_amount'];            
            $nestedData[]          = $row['panalty_charge'];           
            $nestedData[]          = $row['total_return_amount'];
            $nestedData[]          = $total_paid_amount;       
            $nestedData[]          = $row['total_return_amount']-$total_paid_amount;     
            $nestedData[]          = $diff->format("%a");
            
            
            $prepared_status_dis   = '';
            $checked_status_dis    = '';
            $approved_status_dis   = '';
            $authorized_status_dis = '';
            $actionTxtDisble       = '';
            $actionTxtEnable       = '';
            $actionTxtUpdate       = '';
            $actionTxtDelete       = '';
            $url                   = '';
            $mid                    ='';

			$start = '<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">
                            ';
							
			

                $mid	= '
                <li><a  data-toggle="modal" href="'.base_url('payment_process/manage/'.$row['customer_id']).'" ><i class="fa fa-exchange"></i> Cheque return settlement  </a></li>
                '; 


             
							
			$end	= '</ul></div>';
			
            $nestedData[]          = $start.$mid.$end;
            $data[]                = $nestedData;
        }
        $json_data = array(
            "recordsTotal" => intval($totalData),
            "recordsFiltered" => intval($totalFiltered),
            "data" => $data
        );
        echo json_encode($json_data);
    }

    function update_cheque()
    {
        $smp_id        	= $this->input->get('smp_id');
        $status        	= $this->input->get('status');
        if($status==4){
            $return_date=date("Y-m-d");            
            $data=array('payment_status'=>$status,'payment_return_date'=>$return_date);
        }else{
            $data=array('payment_status'=>$status);  
        }        
		$result			= $this->Sale_Multiple_Payment_Model->update_cheque($smp_id,$data);
		//echo $result;
		//$result = 0;
		$data = array('result'=>$result);
		//print_r($data);
		return json_encode($data);
    }
    

    public function cheq_return_update()
    {
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = '';
        $pay_no            = $this->uri->segment('3');
      
       $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
       $data['customer_list']  = $this->Customer_Model->get_all_customers();
       $data['ch_return_reason_list']   = $this->Payment_Process_Model->get_cheque_return_reason();
       $data['bank_list'] = $this->Bank_Model->get_all_bank();
       $data['user_list'] = $this->User_Model->get_all_cash_collector_users();
       $data['cr_limit_list'] =array();        
       $data['smp_id']    = $pay_no;

       //print_r($data['ch_return_reason_list']);


        $this->load->view('payment/cheque_return_update', $data);
    }



    public function save_cheque_return()
    {	
        $this->load->library('form_validation'); //form validation lib
       
        $this->form_validation->set_rules('collector_id', 'Responsible Person', 'required');      
        $this->form_validation->set_rules('return_reason', 'Return Reason', 'required');
        $this->form_validation->set_rules('smp_id', 'Payment Id', 'required'); 
      
       
        if ($this->form_validation->run() == FALSE) {
            $st = array(
                'sale_id' => 0,
                'error' => 1,
                'disMsg' => validation_errors()
            );
            echo json_encode($st);
        } else {
        //--------------------------------------------------------------------------
      
        $smp_id               = $this->input->post('smp_id');
        $collector_id         = $this->input->post('collector_id');
        $ref_no               = $this->input->post('ref_no');                
        $date_time            = date('Y-m-d', strtotime($this->input->post('sale_pymnt_date_time')));
      	$sale_note            = $this->input->post('sale_note');
		$return_reason        = $this->input->post('return_reason');
        $user_id              = $this->session->userdata('ss_user_id');

        $panalty=$this->Payment_Process_Model->get_panalty_charge($return_reason); 
        $details=$this->Payment_Process_Model->get_cheque_details($smp_id);         
             
        $data       = array(
            'pay_ret_ref_no' => $ref_no,
            'return_date' => $date_time,           
            'payment_id' => $smp_id,          
            'return_reason_id' => $return_reason ,   
            'panalty_charge' => $panalty['charge_amount'] , 
            'return_payment_amount' => $details['smp_amount'] ,          
            'total_return_amount' => $details['smp_amount'] +$panalty['charge_amount'],          
            'return_payment_type' => 2 ,   
            'return_remarks' => $sale_note ,   
            'return_pay_status' => 1, 
            'responsible_person' => $collector_id,            
        );
        $this->Payment_Process_Model->save_cheque_return($data); 
        
        $return_date=date("Y-m-d");            
        $data_array=array('payment_status'=>4,'payment_return_date'=>$return_date);    
        $result			= $this->Sale_Multiple_Payment_Model->update_cheque($smp_id,$data_array); 
        $disMsg = '';       
        echo json_encode(array(
            'sale_id' => 1,
            'error' => 0,
            'disMsg' => $disMsg
        ));       
      }
    }
    

    public function over_payment_settlment()
    {
        $this->load->model('Sales_Return_Model');        
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'over_payment_settlment';
        $customer_id            = $this->uri->segment('3');
        $payment_id            = $this->uri->segment('4');
        $data['warehouse_list'] = $this->Warehouse_Model->get_all_warehouse();
        $data['customer_list']  = $this->Customer_Model->get_all_customers();        
        $data['sales_list']     = $this->Sale_Multiple_Payment_Model->get_sale_complete_info_by_customer_id($customer_id);
        $balance=0;
        $warehouse="";
        $bank="";
        $payment_type="";
        $smp_id="";
        $collector_id="";
        $sale_pymnt_cheque_no="";
        $sale_pymnt_crdt_card_no="";

        if($payment_id){
        $paydata=   $this->Payment_Process_Model->get_cheque_details($payment_id);
        $sale_paid=$this->Payment_Process_Model->get_total_sale_paid_by_smp_id($payment_id);		
        $return_paid=$this->Payment_Process_Model->get_total_cheque_return_paid_by_smp_id($payment_id);
        $balance=$paydata['smp_amount']-$sale_paid-$return_paid;
        $bank=$paydata['bank_id'];
        $smp_id=$paydata['smp_id'];
        $collector_id=$paydata['collector_id'];
        $sale_pymnt_cheque_no=$paydata['payment_ref_no'];
        $sale_pymnt_crdt_card_no=$paydata['payment_ref_no'];
        $warehouse=$paydata['warehouse_id'];
        $payment_type=$paydata['payment_type'];
        }
        $data['balance']=$balance;
        
        $data['bank_list'] = $this->Bank_Model->get_all_bank();
        $data['user_list'] = $this->User_Model->get_all_cash_collector_users();
        $data['cr_limit_list'] =array();        
        $data['customer_id']    = $customer_id;
        $data['payment_id']    = $payment_id;

        $data['smp_id']                  = $smp_id;
        $data['collector_id']            = $collector_id;
        $data['warehouse_id']            = $warehouse;
        $data['sale_pymnt_paying_by']    = $payment_type;
        $data['sale_pymnt_cheque_no']    = $sale_pymnt_cheque_no;
        $data['bank_id']                = $bank;
        $data['sale_pymnt_crdt_card_no'] = $sale_pymnt_crdt_card_no;
        $data['payment_list'] = $this->Payment_Process_Model->get_uncomplte_multiple_payment($customer_id);
        $this->load->view('payment/over_payment_settlment', $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', 'required');        
        $this->form_validation->set_rules('customer_id', 'Customer', '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[sale_multiple_payment.payment_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('customer_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');
        $smp_id               = $this->input->post('smp_id');
                
        $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();
       
        $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==2){
            $payment_ref_number=$sale_pymnt_cheque_no;
            $payment_type=2;   
            $payment_status=1;         
        }
        if($sale_pymnt_paying_by==3){
            $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==1){
            $payment_type=1;
        }         
       
        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];
                }
				//if($this->input->post('sale_pymnt_cheque_no'))
				//$sale_note.= '<br />Cheque Value:'.$total_val;
                $data_item = array(
                    'sale_id' => $row[$i]['sale_id'][0],
                    'sale_pymnt_amount' => floatval($row[$i]['amount'][0]),
                    'sale_pymnt_paying_by' => $sale_pymnt_paying_by,
                    'user_id' => $user_id,
					'bank_id' => $bank_id,
                    'sale_pymnt_added_date_time' => $sale_pymnt_added_date_time,
                    'sale_payment_type' => 'sale',
                    'sale_pymnt_cheque_no' => $sale_pymnt_cheque_no,
                    'sale_pymnt_crdt_card_no' => $sale_pymnt_crdt_card_no,
                    'sale_pymnt_crdt_card_holder_name' => $sale_pymnt_crdt_card_holder_name,
                    'sale_pymnt_crdt_card_type' => $sale_pymnt_crdt_card_type,
                    'sale_pymnt_crdt_card_month' => $sale_pymnt_crdt_card_month,
                    'sale_pymnt_crdt_card_year' => $sale_pymnt_crdt_card_year,
                    'sale_pymnt_date_time' => $sale_pymnt_date_time,
                    'smp_id' => $smp_id,
					'sale_pymnt_note' => $sale_note,
					'sale_pymnt_note_two' => $sale_note_two
                );
                if ($collection) {
                    $this->Sale_Multiple_Payment_Model->save_sale_multiple_payment($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
        ));
         //-------------------------------------------------------------------------------------
    }
    }
    
   





}