<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Sale_Multiple_Payment 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('Sale_Multiple_Payment_Model');
        $this->load->model('Bank_Model');
        $this->load->model('Sales_Return_Model');
        
    }
    public function index()
    {
        $data['expenses']       = $this->Expenses_Model->get_all_expenses();
        $data['main_menu_name'] = $this->main_menu_name;
        $data['sub_menu_name']  = 'sale_multiple_payment_list';
        $this->load->view('sale_multiple_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']  = 'sale_multiple_payment_add';
        $customer_id            = $this->uri->segment('3');
        $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);
        $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('sale_multiple_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', '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_amount' => floatval($total_val),
            '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->Sale_Multiple_Payment_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(
                    '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
        ));
         //-------------------------------------------------------------------------------------
    }
    }
    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 list_sale_multiple_payment()
    {
        $requestData   = $_REQUEST;
        $columns       = array(
            0 => 'exp_id',
            1 => 'exp_id',
            2 => 'exp_id',
            3 => 'exp_id',
            4 => 'exp_id',
            5 => 'exp_id'
        );
        $data          = array();
        $expenses      = $this->Sale_Multiple_Payment_Model->get_all_list_sale_multiple_payment();
        $totalData     = count($expenses);
        $totalFiltered = $totalData;
        foreach ($expenses as $row) {
            $nestedData            = array();
            $smp_id                = $row['smp_id'];
            $total_paid_amount     = '';
            //$nestedData[]          = $row['smp_id'];
            $nestedData[]          = $row['smp_no'];
            $nestedData[]          = $row['ref_no'];
            $nestedData[]          = $row['smp_added_date']; 
            $nestedData[]          = $row['cus_name'];
            $nestedData[]          = $row['p_type_name'];            
            $nestedData[]          = $row['payment_ref_no'];
            $nestedData[]          = $row['smp_amount'];
            $nestedData[]          = $row['p_status_name'];           
            $nestedData[]          = $row['payment_date'];  
            $nestedData[]          = $row['bank_name']; 
            
            $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">
                            ';
							
			if($row['payment_type']==2 && $row['payment_status']!=4){
                $mid	= '<li><a onClick="update_cheque(' . $row['smp_id'] . ',2)" data-toggle="modal" href="#" ><i class="fa fa-trash-o"></i> Deposit This Cheque</a></li>
                <li><a onClick="update_cheque(' . $row['smp_id'] . ',3)" data-toggle="modal" href="#" ><i class="fa fa-trash-o"></i> Realize This Cheque</a></li>
                 <li><a  data-toggle="modal" href="'.base_url('payment_process/cheq_return_update/'.$row['smp_id']).'" ><i class="fa fa-trash-o"></i> Return This Cheque</a></li>
                <li><a onClick="delete_smp(' . $row['smp_id'] . ')" data-toggle="modal" href="#" ><i class="fa fa-trash-o"></i> Delete Payment</a></li>
                 '; 
            }else{

                $mid	= '<li><a onClick="delete_smp(' . $row['smp_id'] . ')" data-toggle="modal" href="#" ><i class="fa fa-trash-o"></i> Delete Payment</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);
    }
    

    function update_old_recode()
    {

        $result	= $this->Sale_Multiple_Payment_Model->get_all_recode();

        foreach($result As $key){
            $id=$key['smp_id'];
            $p_stat=1;
            $ptype=1;
            $ref_no="";
            $payment_date= date('Y-m-d', strtotime($key['sale_pymnt_date_time'])); ; 
            $sale_pymnt_paying_by=$key['sale_pymnt_paying_by'];
            if($sale_pymnt_paying_by=="Cash"){
                $p_stat=1;
                $ptype=1;
            }
            if($sale_pymnt_paying_by=="Cheque"){
                $p_stat=1;
                $ptype=2;
                $ref_no=$key['sale_pymnt_cheque_no'];
            }
            if($sale_pymnt_paying_by=="Cheque_Return"){
                $p_stat=4;
                $ptype=2;
                $ref_no=$key['sale_pymnt_cheque_no'];
            }
            $data=array('payment_type'=>$ptype,'payment_status'=>$p_stat,'payment_ref_no'=>$ref_no,'payment_date'=>$payment_date);

           
            $result			= $this->Sale_Multiple_Payment_Model->update_cheque($id,$data);
            echo $id."-".  $result	 . "<br>";
        }





    }





}