<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class Android extends CI_Controller
{
    var $main_menu_name = "android";
    var $sub_menu_name = "android";
    public function __construct()
    {
        parent::__construct();
       $this->load->model('Common_Model');
        $this->load->model('Warehouse_Model');
        $this->load->model('Transfer_Model');
        $this->load->model('Sales_Model');
        $this->load->model('Purchases_Model');
        $this->load->model('Report_Model');
        $this->load->model('Product_Damage_Model');
        $this->load->model('Sales_Return_Model');
        $this->load->model('Sequerty_Model');
        $this->load->model('Product_Models');
        $this->load->model('Customer_Model');
        $this->load->model('Expenses_Model');
        $this->load->model('User_Model');
        $this->load->model('Reports_Marketing_Model');
		$this->load->model('Route_Model');
		$this->load->model('In_Type_Model');
		$this->load->model('Android_Model');
		
		
    }
    public function index()
    {
    }
    public function login()
    {	//get user name and password
        $user_username = $this->uri->segment('3');
        $password      = $this->uri->segment('4');
		//get user id
        $user_id       = $this->User_Model->login($user_username, $password);
        if ($user_id) {
            $data['user_details'] = $this->User_Model->get_user_info($user_id);
            $ss_user_username     = $data['user_details']['user_username'];
            $ss_user_id           = $data['user_details']['user_id'];
            $ss_group_id          = $data['user_details']['group_id'];
            $ss_warehouse_id      = $data['user_details']['warehouse_id'];
            $ss_user_first_name   = $data['user_details']['user_first_name'];
            $ss_user_last_name    = $data['user_details']['user_last_name'];
            $ss_user_group_name   = $data['user_details']['user_group_name'];
            //if cash collector owener super admin
            if ($ss_group_id == 4 || $ss_group_id == 1 || $ss_group_id == 2 || $ss_group_id == 3 ||$ss_group_id == 5) {
                $stutus = 1;
                $user   = array(
                    'ss_stutus' => $stutus,
                    'ss_user_id' => $user_id,
                    'ss_group_id' => $ss_group_id,
                    'ss_warehouse_id' => $ss_warehouse_id,
                    'ss_user_first_name' => $ss_user_first_name,
                    'ss_user_group_name' => $ss_user_group_name,
                );
                echo json_encode($user);
            } else {
                $stutus = 2;
                $user   = array(
                    'ss_stutus' => $stutus
                );
                echo json_encode($user);
            }
        } else {
            $stutus = 0;
            $user   = array(
                'ss_stutus' => $stutus
            );
            echo json_encode($user);
        }
    }
	
	
	
	
	
    public function save_customer_via_online()
    {
		$this->load->library('form_validation'); //form validation lib	
		
		$customer_nic=$this->input->post('cus_nic');
		$customer_name=$this->input->post('cus_name');
		$customer_mobile=$this->input->post('cus_moblie');
		$customer_address=$this->input->post('cus_address');
		$customer_route=$this->input->post('cus_route');
		$user_id=$this->input->post('user_id');
		$location_latitude=$this->input->post('location_latitude');
		$location_long=$this->input->post('location_long');
		$location_status=$this->input->post('location_status');		
		$cus_code=$this->Common_Model->gen_ref_number('cus_id','customer','CUS');
		//validations
		$this->form_validation->set_rules('cus_nic', 'NIC', 'required');
		$this->form_validation->set_rules('cus_name', 'Name', 'required');
		$this->form_validation->set_rules('cus_moblie', 'Mobile', 'required');
		$this->form_validation->set_rules('cus_address', 'Address', 'required');
		$this->form_validation->set_rules('cus_route', 'Route', 'required');
		$this->form_validation->set_rules('user_id', 'Rep ID', 'required');
		
		 if ($this->form_validation->run() == FALSE)
        {
           $st = array('status' =>0,'validation' => validation_errors());
           echo json_encode($st);
        }
        else
        {
		$data=array(
			'priority'=>0,
			'route_id'=>$customer_route,
			'country_id'=>251,	
			'cus_name'=>$customer_name,
			'cus_code'=>$cus_code,
			'cus_phone'=>$customer_mobile,	
			'cus_address'=>$customer_address,
			'last_modify_by'=>$user_id ,
			'last_modify_date_time'=> date('Y-m-d H:i:s'),
			'location_latitude'=>$location_latitude ,
			'location_long'=>$location_long ,
			'location_status'=>$location_status ,			
		);	
		$cus_id='';
		$_insert=$this->Customer_Model->save_customer($data,$cus_id);		
		$lastid=$this->db->insert_id();
		$cus_details=$this->Customer_Model->get_customer_info($lastid);		
		 $st = array('status' =>1,'validation' =>'','data'=>$cus_details);
         echo json_encode($st);	
		}
	}	
	
	
	
	
	public function get_list_customer_user_id()
	{
		$user_id=$this->input->post('user_id');
		$this->load->model('Customer_Model');
		$this->load->model('Route_Assign_Model');	
		 
	  	$user_currunt=$this->Android_Model->get_user_active_delivery($user_id);	  
		$area_id=-5;
		$delivery_id=-5;
	  
	  	if(isset($user_currunt['id']))
		{
			$area_id=$user_currunt['area_id'];
			$delivery_id=$user_currunt['id'];		  
	  	}	
		$route_array=$this->Route_Assign_Model->get_relevent_route_ids($area_id);				
		$customer_list=$this->Customer_Model->get_all_customers_by_routes($route_array);		
		$data=array();
		foreach($customer_list as $cs)
		{
			$cus_id=$cs['cus_id'];				
			
			$data_item=array(
			'cus_id'=>$cs['cus_id'],
			'cus_code'=>$cs['cus_code'],
			'cus_name'=>$cs['cus_name'],
			'cus_phone'=>$cs['cus_phone'],
			'cus_phone2'=>$cs['cus_m_phone'],
			'cus_address'=>$cs['cus_address'],
			'route_id'=>$cs['route_id'],
			'location_status'=>$cs['location_status'],
			'location_latitude'=>$cs['location_latitude'],
			'location_long'=>$cs['location_long'],
			'cus_img'=>'',
			);
			
			$data[]=$data_item;
			
		}	
		
		$jsondata=array("data"=>$data);
		echo json_encode($jsondata);		
		
	}
	
	public function get_route_list()
	{
	  $user_id=$this->input->post('user_id');
	  $this->load->model('Route_Assign_Model');		 
	  $user_currunt=$this->Android_Model->get_user_active_delivery($user_id);		
	  $area_id=-5;
	  $delivery_id=-5;	  
	  if(isset($user_currunt['id']))
	  {
	  $area_id=$user_currunt['area_id'];
	  $delivery_id=$user_currunt['id'];		  
	  }
		$data['route_list']=$this->Route_Assign_Model->get_selected_route($area_id);
		echo json_encode($data);		
	}
	
	
	//-------------------------------------------
	
	public function save_transaction()
	{		
		$description=$this->input->post('description');
		$system_date_time=$this->input->post('system_date_time');
		$page_name=$this->input->post('page_name');
		$user_id=$this->input->post('user_id');
		$device_address=$this->input->post('device_address');		
		$added_date_time=date('Y-m-d H:i:s');			
		
		$user_currunt=$this->Android_Model->get_user_active_delivery($user_id);
		$area_id=-5;
	  	$delivery_id=-5;
	  	if(isset($user_currunt['id']))
	  	{
	  	$area_id=$user_currunt['area_id'];
	  	$delivery_id=$user_currunt['id'];		  
	  	}
				$data_item=array(
					'delivery_id'=>	$delivery_id, 				
					'description'=>$description,
					'system_date_time'=>date('Y-m-d H:i:s', strtotime($system_date_time)),								
					'user_id'=>$user_id,
					'device_address'=>$device_address,			
					'page_name'=>$page_name,	
					'added_date_time'=>	$added_date_time						
				);								
				$result=$this->Android_Model->save_log_android_transaction($data_item);		
			
			if ($result==1) {
				echo json_encode(array('error'=>1,'message'=>"Transaction done",'status' =>1));
			} else {
				echo json_encode(array('error'=>0,'message'=>"Error occurd!",'status' =>0));
			}		
	}
	
	public function get_all_easy_customers()
	{	
		$this->load->model('Customer_Model');				
		$data['customer_list']=$this->Customer_Model->get_all_easy_customers_list();
		echo json_encode($data);	
	}
	
	
	
	

	//transaction log start
	function save_transaction_log()
	{
		$transaction_id=$this->input->post('transaction_id');
		$transaction_customer=$this->input->post('transaction_customer');
		$transaction_user=$this->input->post('transaction_user');
		$transaction_recode_id=$this->input->post('transaction_recode_id');
		$transaction_type=$this->input->post('transaction_type');	
		$transaction_start_time=$this->input->post('transaction_start_time');
		$transaction_sending_type=$this->input->post('transaction_sending_type');
		$connection_status=$this->input->post('connection_status');
		$data_saving_type=$this->input->post('data_saving_type');
		$transaction_end_time=$this->input->post('transaction_end_time');	
		$response_status=$this->input->post('response_status');
		$response_result=$this->input->post('response_result');
		$response_message=$this->input->post('response_message');
		$device_id=$this->input->post('device_id');
		$log=$this->input->post('log');
		$added_date_time=date('Y-m-d H:i:s');
		
		$data=array(
				'transaction_id'=>$transaction_id,	
				'transaction_customer'=>$transaction_customer,
				'transaction_user'=>$transaction_user,
				'transaction_recode_id'=>$transaction_recode_id,
				'transaction_type'=>$transaction_type,
				'transaction_start_time'=>$transaction_start_time,
				'transaction_sending_type'=>$transaction_sending_type,
				'connection_status' => $connection_status,
				'data_saving_type' => $data_saving_type,
				'transaction_end_time' => $transaction_end_time,
				'response_status' => $response_status,
				'response_result' => $response_result,
				'log' => $log,
				'device_id' => $device_id,
				'added_date_time' => $added_date_time,
			);
              $result=$this->Android_Model->save_transaction_log($data);
		
			
			if ($result==1) {
				echo json_encode(array('error'=>1,'message'=>"Transaction done",'status' =>1));
			} else {
				echo json_encode(array('error'=>0,'message'=>"Error occurd!",'status' =>0));
			}	
	}
	//transaction log starendt


	public function save_location()
	{
		$this->load->model('Customer_Model');
		$user_id                    = $this->input->post('user_id');
        $cus_id                     = $this->input->post('cus_id');
        $location_status            = $this->input->post('location_status');
        $location_latitude          = $this->input->post('location_latitude');
		$location_long           	= $this->input->post('location_long');		
		
		$data=array(
			'locaton_update_user_id'=>$user_id, 
			'location_status'=>$location_status,
			'location_latitude'=>$location_latitude,
			'location_long'=>$location_long,
			);	
			
		$result=$this->Customer_Model->customer_location_save($cus_id,$data);
		
		if($result==1){			
			$data_r=array(
			'status'=>1, 
			'error'=>0,
			'message'=>"Successfuly Updated",
			);			
		}
		else
		{			
		$data_r=array(
			'status'=>0, 
			'error'=>1,
			'message'=>"Not Saved",
			);		
		}		
		echo json_encode($data_r);	
		
	}
	

	
	function save_visit_location()
	{		
		$date=$this->input->post('date');
		$user_id=$this->input->post('user_id');
		$cus_id=$this->input->post('cus_id');
		$location_latitude=$this->input->post('location_latitude');
		$location_long=$this->input->post('location_long');
		$device_id=$this->input->post('device_id');
		$time=$this->input->post('time');
		$transaction=$this->input->post('transaction');
		$transaction_type=$this->input->post('transaction_type');
		$recode_id=$this->input->post('recode_id');
		$system_date_time=date('Y-m-d H:i:s');
		$route_id=$this->input->post('route_id');		
		
		$data=array(
				'date'=>$date,	
				'user_id'=>$user_id,
				'cus_id'=>$cus_id,
				'location_latitude'=>$location_latitude,
				'location_long'=>$location_long,
				'device_id'=>$device_id,
				'time'=>$time,
				'transaction'=>$transaction,
				'transaction_type'=>$transaction_type,
				'recode_id'=>$recode_id,
				'route_id'=>$route_id,
				'system_date_time'=>$system_date_time,				
			);
              $result=$this->Android_Model->save_visitlocation_log($data);
			  if ($result==1) {
				echo json_encode(array('error'=>1,'message'=>"Done",'status' =>1));
			} else {
				echo json_encode(array('error'=>0,'message'=>"Error occurd!",'status' =>0));
			}		
	}
	
	public function get_customer_outstanding_list()
    {
	 	$route_id        = $this->input->get('area_id');
		$start=1;
		$length=500;
		$search=$this->input->get('search');
		$totalData = 1000;//$this->Reports_Marketing_Model->get_all_customers_by_area_id($route_id,"","",$search);
		$totalFiltered=1000;
        $customer_list = $this->Reports_Marketing_Model->get_all_customers_by_area_id($route_id,$start,$length,$search);
        $json_data          = array();
        foreach ($customer_list as $row) {

            $total_outstanding_amount=0;
           		
			$customer_id=$row['cus_id'];
			$sale_total = $this->Reports_Marketing_Model->get_all_sale_total_by_customer_id($customer_id);
			$sale_paid = $this->Reports_Marketing_Model->get_all_paid_total_by_customer_id($customer_id);		
            $sale_list = $this->Reports_Marketing_Model->get_all_sale_list_by_customer_id($customer_id);
            $return_balance =0; //$this->Reports_Marketing_Model->get_cheque_return_balance_by_customer_id($customer_id);
            $return_cheque_list = $this->Reports_Marketing_Model->get_all_cheque_return_list_by_customer_id($customer_id);
            $over_cheq_list = $this->Reports_Marketing_Model->get_uncomplte_multiple_payment($customer_id);
            $cus_payment_balance=0;
            foreach($over_cheq_list as $ovc)
            {
                $id=$ovc['smp_id'];
                $sale_paid=$this->Reports_Marketing_Model->get_total_sale_paid_by_smp_id($id);		
                $return_paid=$this->Reports_Marketing_Model->get_total_cheque_return_paid_by_smp_id($id);
                $sale_balance=$ovc['smp_amount']-$return_paid-$sale_paid;
                $cus_payment_balance+=$sale_balance;
            }
		
			$return_full_amount=0;
			$count=0;
			$sale_array=array();
			foreach($sale_list as $key){
				$converted_sale_date   = date('Y-m-d', strtotime($key['sale_datetime']));
				$s_paid = $this->Reports_Marketing_Model->get_all_paid_total_by_sale_id($key['sale_id']);
				
				$return_tot=$this->Sales_Return_Model->get_relevant_return_by_sale_id($key['sale_id']);		
		if(isset($return_tot['sl_rtn_total']))
		{
		$return_tot_amt=$return_tot['sl_rtn_total'];
		}
		else
		{
			$return_tot_amt=0;
		}		
		if(isset($return_tot['sls_rtn_total_paid']))
		{
		$return_tot_paid=$return_tot['sls_rtn_total_paid'];
		}
		else
		{
			$return_tot_paid=0;
		}
				
				
				$sale_total_full=$key['sale_total']-$return_tot_amt;
                $s_outstanding=($key['sale_total']-$return_tot_amt)-($s_paid);
                
                $total_outstanding_amount+=$s_outstanding;
				$count=1;
				$s_outstanding=number_format($s_outstanding, 2, '.', '');
				
				$temp_sale_array=array(
				    'sale_id'=>$key['sale_id'],
				    'sale_reference_no'=>$key['sale_reference_no'],
				    'card_ref_number'=>$key['card_ref_number'],
				    'converted_sale_date'=>$converted_sale_date,
				    'due_date'=>$key['due_date'],
				    'invoice_type_name'=>$key['invoice_type_name'],
				    'sale_total_full'=>$sale_total_full,
				    's_paid'=>$s_paid,
				    's_outstanding'=>$s_outstanding,
				    );
				    
				    $sale_array[]=$temp_sale_array;
				
				//$table_row='<tr><td>'.$key['sale_reference_no'].'</td>'.'<td>'.$key['card_ref_number'].'</td>'.'<td>'.$converted_sale_date.'</td>'.'<td>'.$key['due_date'].'</td>'.'<td><span class="'.$key['class_name_report'].'">'.$key['invoice_type_name'].'</span></td>'.'<td>'.$sale_total_full.'</td><td>'.$s_paid.'</td><td>'.$s_outstanding.'</td></tr>';
		
			$return_full_amount+=$return_tot_amt;
			}			
					
		
			$return_count=0;
			
			$return_cheque_array=array();
			foreach($return_cheque_list as $key){
                $retun_paid_amount=$this->Reports_Marketing_Model->get_cheque_reurn_paid_amount($key['ret_pay_id']);
                $chequ_return_balance_amount=$key['total_return_amount']-$retun_paid_amount;
                $che_re_due_date=date('Y-m-d', strtotime($key['return_date']. ' + 10 day'));
                $return_count=1;
				//$table_row='<tr><td>'.$key['payment_ref_no'].'</td>'.'<td>'.$key['payment_date'].'</td>'.'<td>'.$key['return_date'].'</td>'.'<td>'.$che_re_due_date.'</td>'.'<td>'.$key['smp_amount'].'</td><td>'.$key['panalty_charge'].'</td><td>'.$chequ_return_balance_amount.'</td></tr>';           
                $temp_retyurn_array=array(
                     'payment_ref_no'=>$key['payment_ref_no'],
                     'payment_date'=>$key['payment_date'],
                     'return_date'=>$key['return_date'],
				    'smp_amount'=>$key['smp_amount'],
				    'che_re_due_date'=>$che_re_due_date,
				    'panalty_charge'=>$key['panalty_charge'],
				    'chequ_return_balance_amount'=>$chequ_return_balance_amount,
                    );
                    $return_cheque_array[]=$temp_retyurn_array;
            }           
            $nested_data = array( 
            'cus_id'=>$row['cus_id'],
     		'cus_code'=>$row['cus_code'],
            'cus_name'=>$row['cus_name'],
            'cus_address'=> $row['cus_address'],
            'over_payment'=>number_format($cus_payment_balance,2,".",""),
            'outstanding'=> number_format($total_outstanding_amount-$cus_payment_balance,2,".",""),
            'sale_list'=>$sale_array,
            'cheque_return_list'=>$return_cheque_array,
            );
            $json_data[]    = $nested_data;
        }
        echo json_encode(array(
			//"recordsTotal"    => intval( $totalData ),  
			//"recordsFiltered" => intval( $totalFiltered ),
            'data' => $json_data
        ));
    }
    
    public function get_bank_list()
    {
        $this->load->model('Bank_Model');
        $bank_list = $this->Bank_Model->get_all_bank();
          echo json_encode(array(
            'data' => $bank_list
        ));
    }
    
    
    //update 2021-02-03 DDN Makola Join Project
    
     public function get_invoice_type_list()
    {
        $this->load->model('In_Type_Model');
        $invoice_type = $this->In_Type_Model->get_active_in_types();
          echo json_encode(array(
            'data' => $invoice_type
        ));
    }
    
     function get_direct_sale_list()
    {
        $this->load->model('Sales_Model');
        $this->load->model('Android_Model');
        $user_id=$this->input->post('user_id');
        $user_currunt = $this->Android_Model->get_user_active_delivery($user_id);
        $area_id      = -5;
        $delivery_id  = -5;
        if (isset($user_currunt['id'])) {
            $area_id     = $user_currunt['area_id'];
            $delivery_id = $user_currunt['id'];
        }
        $sale_list= $this->Android_Model->get_delivery_sale_list($delivery_id,$user_id);
        $sales=array();
        foreach($sale_list as $row){
            $products=array();
            $product_list= $this->Android_Model->get_delivery_sale_product_list($row['sale_id']);
            foreach($product_list as $row_i){
            $data_item=array(
            'product_id'=> $row_i['product_id'],
            'item_code'=> $row_i['product_code'],
            'item_name'=> $row_i['product_name'],
            'invoice_qty'=> $row_i['quantity'],
            'product_price'=> $row_i['net_price'],
            'gross_amount'=> $row_i['gross_total'],
            'discount'=> $row_i['discount_val'],
            'net_amount'=> $row_i['net_total'],
            );
            $products[]=$data_item;
            }
             $data=array(
            'sale_id'=> $row['sale_id'],
            'invoice_date'=> $row['sale_datetime'],
            'bill_no'=> $row['card_ref_number'],
            'cus_code'=> $row['cus_code'],
            'cus_name'=> $row['cus_name'],
            'rep_name'=> $row['user_first_name'],
            'total_gross_amount'=> $row['sale_inv_gross_total'],
            'total_discount'=> $row['total_added_discount_value']+$row['total_default_discount_value']+$row['sale_inv_discount_amount'],
            'total_net_amount'=>$row['sale_total'] ,
            'sale_item_list'=> $products
            );
            $sales[]=$data;
        }
         $st = array(
                'data' => $sales
        );
        echo json_encode($st);
    }
    
     function get_multiple_payment_list()
    {
        $this->load->model('Sales_Model');
        $this->load->model('Android_Model');
        $user_id=$this->input->post('user_id');
        $user_currunt = $this->Android_Model->get_user_active_delivery($user_id);
        $area_id      = -5;
        $delivery_id  = -5;
        if (isset($user_currunt['id'])) {
            $area_id     = $user_currunt['area_id'];
            $delivery_id = $user_currunt['id'];
        }
        $payment_list= $this->Android_Model->get_delivery_payment_list($delivery_id,$user_id);
        $sales=array();
        foreach($payment_list as $row){
            $single_payment=array();
            $single_payment_list= $this->Android_Model->get_delivery_sale_single_payment_list($row['smp_id']);
            foreach($single_payment_list as $row_i){
            $data_item=array(
            'sale_id'=> $row_i['sale_id'],
            'invoice_no'=> $row_i['card_ref_number'],
            'payable_amount'=> $row_i['sale_pymnt_amount'],
            'paid_amount'=> $row_i['sale_pymnt_amount'],
            'outstanding_amount'=> 0,
            );
            $single_payment[]=$data_item;
            }
             $data=array(
            'payment_id'=> $row['smp_id'],
            'payment_date'=> $row['payment_date'],
            'bill_no'=> $row['ref_no'],
            'cus_code'=> $row['cus_code'],
            'cus_name'=> $row['cus_name'],
            'rep_name'=> $row['user_first_name'],
            'total_payable_amount'=>0,
            'total_paid_amount'=> $row['smp_amount'],
            'p_type_name'=> $row['p_type_name'],
            'total_outstanding_amount'=>0 ,
            'payment_invoice_list '=> $single_payment
            );
            $sales[]=$data;
        }
         $st = array(
                'data' => $sales
        );
        echo json_encode($st);
    }
	
	
	
	
	
	
	

}