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

class Cash_Collect extends CI_Controller {

    var $main_menu_name = "cash_collect";
	var $sub_menu_name = "cash_collect";

	public function __construct()
	{
		parent::__construct();
		
		
		$this->load->model('Route_Model');
		$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('Sales_Return_Model');
		$this->load->model('User_Model');
		$this->load->model('Transfer_Model');
		$this->load->model('Purchases_Model');
		$this->load->model('Product_Damage_Model');
		$this->load->model('Cash_Collect_Model');
		$this->load->model('Issue_Cards_Model');
	}
	
	//Sales list page load
	public function index()
	{	
		$user_id=$this->session->userdata('ss_user_id');
		$user_group=$this->session->userdata('ss_group_id');
		
		{
		if($user_group==5)	
		{
		$issue_card_id=$this->Cash_Collect_Model->get_last_issue_card_details_by_user_id($user_id);
		
		
			if(isset($issue_card_id['issue_card_id']))
			{
			$issue_card_details=$this->Issue_Cards_Model->get_issue_card_details_by_issue_card_id($issue_card_id['issue_card_id']);
			$collector_id=$issue_card_details['collector_id'];
			$id=$issue_card_details['wharehouse_id'];
			$route_id=$issue_card_details['route_id'];		
			$data['ICID']=$issue_card_id['issue_card_id'];
			$data['wharehose_details']=$this->Warehouse_Model->get_warehouse_info($id);
			$data['cash_collector_details']=$this->User_Model->get_rep_first_and_second_name_by_id($collector_id);
			$data['issue_card_details']=$this->Cash_Collect_Model->get_issue_card_details_by_issue_card_id($issue_card_id['issue_card_id']);
			$data['issue_card_items_details']=$this->Cash_Collect_Model-> get_issue_card_item_list_by_issue_card_id($issue_card_id['issue_card_id']);
			}
			
			}
		
		}	
	
		
		
		$data['cash_collector_list']=$this->User_Model->get_all_cash_collector_users();
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='cash_collect';
		$this->load->view('cash_collection_add',$data);
	}	
	
	function admin()
	{
		
		$user_id=$this->session->userdata('ss_user_id');
		$user_group=$this->session->userdata('ss_group_id');
		
		
		if($user_group==1||$user_group==2 )	
		{
				
		$data['cash_collector_list']=$this->User_Model->get_all_cash_collector_users();
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='cash_collect';
		$this->load->view('cash_collection_add_admin',$data);
		
		}elseif($user_group==5)
		{
		 $data['cash_collector_list']=$this->User_Model->get_all_cash_collector_users();
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='cash_collect';
		$this->load->view('cash_collection_add',$data);	
		}
		
	}
	
	
	public function get_all_recivble_invoice_by_cash_collectr_id()
	{
		$user_id=$this->session->userdata('ss_user_id');
		$user_group=$this->session->userdata('ss_group_id');
		
		
		
		
		$cash_collector_id=$this->input->get('CI');
		$issue_card_id_temp=$this->Cash_Collect_Model->get_last_issue_card_details_by_user_id($cash_collector_id);		
		if(isset($issue_card_id_temp['issue_card_id'])){
		
		$issue_card_id=$issue_card_id_temp['issue_card_id'];		
		$invoices=$this->Cash_Collect_Model->get_issue_card_item_list_by_issue_card_id($issue_card_id);
		
		
	/*	$json=array();
		
	 	foreach ($data['invoices'] as $row)
		{
				
		
		$json_itm=array(
			 		'sale_id'=> $row['sale_id'],
					'sale_reference_no'=> $row['sale_reference_no'],
					'sale_total'=> $row['sale_total'],
					'sale_pymnt_amount'=> $row['sale_pymnt_amount'],
					'totat_down_payment'=> $row['totat_down_payment'],
					'term_amount'=> $row['term_amount'],
					'no_of_months'=> $row['no_of_months'],
					'sale_datetime'=> $row['sale_datetime'],
					            
                    );
				//print_r($json_itm);
		
		array_push($json,$json_itm);
						
		}		
		
		echo json_encode($json);*/		
		
		
		$data=array();
	$tmpcount=0;
	$tmptot=0;
	
	/*$d1 = new DateTime('2017-08-20');
	$d2 = new DateTime('2017-10-22');

	// @link http://www.php.net/manual/en/class.dateinterval.php
	$interval = $d2->diff($d1);

	$interval->format('%m months');

	print_r($interval->format('%m months'));
	print_r($interval->format('%d days'));*/
	
	
	foreach ($invoices as $row)
	{
		
		$tmpcount++;
	$tmptot=$tmptot+$row['sale_total'];
	$invoice_total=$row['sale_total'];
	$downpayment= $row['totat_down_payment'];
	$term_amount= $row['term_amount'];  
	$no_of_months= $row['no_of_days']; 
	$sale_paid= $row['sale_pymnt_amount'];
	$record_date_temp= $row['sale_datetime']; 	
	$record_date= new DateTime($record_date_temp);
	$record_date_final = $record_date->format('Y-m-d');
	
	$now_date = new DateTime();
	$now_date_final = $now_date->format('Y-m-d');
	
	
	
	
	$d1 = new DateTime($record_date_final);
	$d2 = new DateTime($now_date_final);

	$interval = $d2->diff($d1);

	$interval->format('%m months');

	$months=$interval->format('%m');
	$dates=$interval->format('%d');
	
	
	$to_be_paid=$invoice_total-$sale_paid;
	
	
	
		
	if($no_of_months>=$months)
	{
	$shoud_be_paid=$downpayment+($term_amount*$months);	
	
	}
	else 
	{
	$shoud_be_paid=$downpayment+($term_amount*$no_of_months);
		
	}
	
	$temp=$shoud_be_paid-$sale_paid;
	//print_r($temp);
	
	if($temp>=0)
	{
	$shoud_be_paid_today=$shoud_be_paid-$sale_paid;	
		
	}
	else
	{
	$shoud_be_paid_today=$shoud_be_paid-$sale_paid;	
	}
	
	if($term_amount==0||$no_of_months==0)
	{
		
		$shoud_be_paid_today=$invoice_total-$sale_paid;		
	}
	
		
	 
	
	if($shoud_be_paid_today<0)
	{ 
	$shoud_be_paid_today= "CR(".number_format($shoud_be_paid_today, 2, '.', ',').")";
	} 
	else
	{
		 $shoud_be_paid_today=  number_format($shoud_be_paid_today, 2, '.', ',');
	} 
		
		
		
		
		
		$nestedData=array();
		$issue_card_id=$row['sale_id'];
		$nestedData[]=$tmpcount;
		$nestedData[]=$row['cus_name'];
		$nestedData[]=$row['sale_reference_no']." / ".$row['card_ref_number'];
		$nestedData[]=number_format($to_be_paid, 2, '.', ',');
		$nestedData[]=number_format($term_amount, 2, '.', ',');
		$nestedData[]=$shoud_be_paid_today."<input type='hidden' align='center' name='payment' id= os_". $row['sale_id']." value =".$shoud_be_paid_today."  class='form-control datetime text-right'>";
		
		$nestedData[]="<input type='text' align='center' name='payment' id= p_". $row['sale_id']." value ='0.00'  class='form-control datetime text-right'>";
		
		
		
		$nestedData[]="
		
		<div class = 'btn-group' onClick = cash_collect(".$row['sale_id'] .")> <a title = '' class = 'btn btn-primary btn-xs' data-original-title = 'Add' > <i class = 'fa fa-money' > </i> <span class = 'hidden-sm hidden-xs' > ADD </span></a>
</div> 
		
	
		
		<div class='btn-group text-left'>
		
		
		
		                   
					        <button data-toggle='dropdown' class='btn btn-default btn-xs btn-primary dropdown-toggle' type='button'><i class='fa fa-print'></i> Action<span class='caret'> </span></button>
                            <ul role='menu' class='dropdown-menu pull-right'>
                            <li><a href=".base_url()."sales2/view/".$row['sale_id']."><i class='fa fa-file-text-o'></i> Sale Details</a></li>
							
							<li><a href=".base_url()."cash_collect/print_payment_slip?sale_id=".$row['sale_id']."><i class='fa fa-file-text-o'></i>Print Reciept</a></li>
							
                            </ul></div> 
							
						";
	
		$data[]=$nestedData;
	}	
	
	
	$json_data = array(
	"data"=>$data
	);
	
	echo json_encode($json_data);
	
		}
		
		else
		
		{
			
			
		$nestedData=array();	
		$nestedData[]="<?php echo &nbsp; ?>";	
		$nestedData[]="Not assing any issue card yet";
		$nestedData[]="";
		$nestedData[]="";
		$nestedData[]="";
		$nestedData[]="";
		$nestedData[]="";
		$nestedData[]="";
		$data[]=$nestedData;
	
		$json_data = array("data"=>$data);
	
	echo json_encode($json_data);
			
		}
	
	
		
	}
	
		
		
			
		

		

	
	
	
	
	
	
	
	
	//Sales details view
	public function print_payment_slip()
	{
	$sale_id= $this->input->get('sale_id');
	$data['payment_details']=$this->Cash_Collect_Model->get_last_payment_details_by_sales_id($sale_id);
	$this->load->view('models/print_sale_payment',$data);
	
	}

	//Sales add page
	public function add_sale_payments()
	{
		$sale_id= $this->input->get('sale_id');
        $sale_type = $this->input->get('sale_type');
		$amount = $this->input->get('amount');
		$sale_pymnt_ref_no="";
		$srh_from_date= $this->input->get('srh_from_date');
		
		$date2=date_create($srh_from_date);
		$converted_date=date_format($date2,"Y-m-d");
		
		$sale_pymnt_date_time=date("Y-m-d H:i:s");
		$sale_pymnt_date_time_send=date("Y-m-d H:i:s");
		//$sale_pymnt_cheque_no="";
		//$sale_pymnt_crdt_card_no="";
		//$sale_pymnt_crdt_card_holder_name="";
		//$sale_pymnt_crdt_card_month="";
		//$sale_pymnt_crdt_card_year="";
		//$sale_pymnt_crdt_card_type="";
		$sale_type = $sale_type;

		$sale_pymnt_note="cash collector received";
		$user_id=$this->session->userdata('ss_user_id');
		$sale_pymnt_added_date_time=date("Y-m-d H:i:s");
		$sale_pymnt_id='';
		$sale_pymnt_amount=$amount;
        $sale_pymnt_paying_by="cash";


			$data=array(
				'sale_pymnt_amount'=>$sale_pymnt_amount,	
				'sale_pymnt_ref_no'=>$sale_pymnt_ref_no,
				'sale_pymnt_paying_by'=>$sale_pymnt_paying_by,
				'sale_pymnt_date_time'=>$converted_date,
				'sale_pymnt_note'=>$sale_pymnt_note,
				'user_id'=>$user_id,
				'sale_id'=>$sale_id,
				'sale_pymnt_added_date_time'=>$sale_pymnt_added_date_time,				
				'sale_payment_type' => $sale_type
			);
			
			
			
		$this->Cash_Collect_Model->save_sale_payments($data,$sale_pymnt_id);
        echo json_encode(array('req_id'=>'','error'=>'','disMsg'=>'',));
    
			
               
		
	}	
	
	//Sales payment page 
	public function payments()
	{
        $data['sale_id'] = $this->input->get('id');
        $data['sale_type'] = $this->input->get('sale_type');
        $this->load->view('models/sales_payment',$data);	
	}
	public function get_old_credit_amount()
	{
		$cus_id=$this->input->get('cus_id');
		$invocie_data=$this->Sales_Model->get_all_sales_bu_cus_id($cus_id);
		$balance_sub_tot_each=0;
		if(count($invocie_data)){ 
	$balance_sub_tot=0;
	 
	 	
foreach ($invocie_data as $inv)
 {
	 
	 $total_paid_amount=$this->Sales_Model->get_total_paid_by_sale_id($inv->sale_id);
	 $balance_h=0;
	 $balance_h=$inv->sale_total-$total_paid_amount;
	 

	 

	
	if($balance_h){
			$balance_sub_tot_each+=$balance_h;
			
			//reduse this sale return amount
			$sale_pymnt_ruturn_amount=0;
			$sale_pymnt_ruturn_amount=$this->Sales_Return_Model->get_total_return_by_sale_id($inv->sale_id);
			$balance_sub_tot_each-=$sale_pymnt_ruturn_amount;
	}
	 //end check date range
 }
		}
		//$balance_sub_tot_each=500;
		//echo $balance_sub_tot_each;
	//	$old_credit_amount=$balance_sub_tot_each;
		echo json_encode(array('old_credit_amount'=>$balance_sub_tot_each));
	}
	
	

	
	

	
	public function cash_collection_details()
	{		
		$issue_card_id =  $this->uri->segment(3);
		$issue_card_details=$this->Issue_Cards_Model->get_issue_card_details_by_issue_card_id($issue_card_id);
		
		
		$collector_id=$issue_card_details['collector_id'];
		$id=$issue_card_details['wharehouse_id'];
		$route_id=$issue_card_details['route_id'];
		
		$data['ICID']=$issue_card_id;
		$data['main_menu_name']=$this->main_menu_name;
		$data['sub_menu_name']='';
		$data['wharehose_details']=$this->Warehouse_Model->get_warehouse_info($id);
		$data['cash_collector_details']=$this->User_Model->get_rep_first_and_second_name_by_id($collector_id);
		$data['issue_card_details']=$this->Cash_Collect_Model->get_issue_card_details_by_issue_card_id($issue_card_id);
		$data['issue_card_items_details']=$this->Cash_Collect_Model-> get_issue_card_item_list_by_issue_card_id($issue_card_id);	
		
		 $this->load->view('cash_collection_details',$data);	
	}
}