<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
// error_reporting(0);
class Invoice extends CI_Controller 
{
	public function __construct()
	{
	 	parent::__construct();	
		$this->load->model('Invoice_model');
		$this->load->library('Generate_bill_lib'); 
		$this->load->library("pagination");
	}

	public function generate_invoice()
	{  
		if(!$this->session->userdata('logged_in')) 
			redirect('Login');

		$url		=	'Invoice/generate_invoice';
		$order_field= 	'view';
		$join_array = 	array(0=>array(0=>USER_PERM_TBL,1=>"up_menu_id=menu_id",2=>''));
		$result 	=	$this->Invoice_model->select_data(MENU_TBL,'*',array("url"=>$url,"up_emp_id"=>$this->session->userdata('user_id')),'1',$join_array,$order_field,"DESC",'','','');
		if(empty($result))
		{
			$data['page_title'] 	=	'Warning';
	        $data['page_name']  	= 	'warning';
	        $data['page_master']	= 	'Dashboard';
	        $data['page_master_url'] = 	'Dashboard';
	        $data['page_function']	=	'';
			$this->load->view('template/default', $data);
		}
		else
		{	
			$condition 				=	array();
			
			if($this->input->post('search')){

				if($this->input->post('bill_created_date')!=''){
					$bill_created_date = date("Y-m-d", strtotime($this->input->post('bill_created_date')));
				}

				else{
					$bill_created_date = '';
				}

				$search_data = array(
					'bill_id'              => $this->input->post('bill_id'),
					'bill_created_date'    => $bill_created_date
				);

				$this->session->set_userdata('search_criteria_data',$search_data);
			}
			else{

				$search_data = array(
					'bill_id'               => '',
					'bill_created_date'     => ''				
				);
				$this->session->set_userdata('search_criteria_data',$search_data);
			}

			
			if ($this->session->userdata('search_criteria_data')){
				$GetData = $this->session->userdata('search_criteria_data');
			}

			$data['search_data']       = $GetData;
			$config                    = array();
			$config['base_url']        = base_url().'Invoice/generate_bill';
			if($GetData!=''){
				$config['total_rows']  = $this->Invoice_model->search_record_count($GetData);
			}
			else{
				$config['total_rows']  = $this->Invoice_model->record_count();
			}

			$config['per_page']        = 50;
        	$config['uri_segment']     = 3;


        	$config['full_tag_open']   = '<ul class="pagination" style="float:right;">';
        	$config['full_tag_close']  = '</ul>';
        	$config['first_link']      = false;
        	$config['last_link']       = false;
        	$config['first_tag_open']  = '<li>';
        	$config['first_tag_close'] = '</li>';
        	$config['prev_link']       = '&laquo';
        	$config['prev_tag_open']   = '<li class="prev">';
        	$config['prev_tag_close']  = '</li>';
        	$config['next_link']       = '&raquo';
        	$config['next_tag_open']   = '<li>';
        	$config['next_tag_close']  = '</li>';
        	$config['last_tag_open']   = '<li>';
        	$config['last_tag_close']  = '</li>';
        	$config['cur_tag_open']    = '<li class="active"><a href="#">';
        	$config['cur_tag_close']   = '</a></li>';
        	$config['num_tag_open']    = '<li>';
        	$config['num_tag_close']   = '</li>';

        	$this->pagination->initialize($config);
        	$page                      = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        	$data['invoice_details']   = $this->Invoice_model->select_invoice_details($config["per_page"], $page, $GetData);
        	//echo $this->db->last_query(); die();
			$data["links"]             = $this->pagination->create_links();
			$data['invno']            = $this->Invoice_model->select_bill_no();			
			$data['page_title'] 	   = 'Generate Invoice';
		    $data['page_name']  	   = 'invoice/invoice-lists';
		    $data['page_master']	   = 'Generate Bill';
		    $data['page_master_url']   = 'Invoice/generate_invoice';
		    $data['page_function']	   = 'List';
			$this->load->view('template/default', $data);
		}
	}

	public function invoice_list()
	{
	
		if(!$this->session->userdata('logged_in')) 
			redirect('Login');

		$url		=	'Invoice/invoice_list';
		$order_field= 	'view';
		$join_array = 	array(0=>array(0=>USER_PERM_TBL,1=>"up_menu_id=menu_id",2=>''));
		$result 	=	$this->Invoice_model->select_data(MENU_TBL,'*',array("url"=>$url,"up_emp_id"=>$this->session->userdata('user_id')),'1',$join_array,$order_field,"DESC",'','','');
		if(empty($result))
		{
			$data['page_title'] 	=	'Warning';
	        $data['page_name']  	= 	'warning';
	        $data['page_master']	= 	'Dashboard';
	        $data['page_master_url'] = 	'Dashboard';
	        $data['page_function']	=	'';
			$this->load->view('template/default', $data);
		}
		else
		{	
			$condition 				=	array();
			
			if($this->input->post('search')){
				
				
				$rad=$this->input->post('r');
				//print_r($rad);
				//die();
			$bill_from_date=$this->input->post('bill_from_date');
            $bill_to_date=$this->input->post('bill_to_date');
				if($this->input->post('bill_from_date')!=''){
					$bill_from_date = $this->input->post('bill_from_date');
					
				}
				
				
				if($this->input->post('bill_to_date')!=''){
					$bill_to_date = $this->input->post('bill_to_date');
					//print_r($bill_to_date);
					//die();
				}
				

				//else{
					//$bill_created_date = '';
				//}

				$search_data = array(
					
					'bill_from_date'    => $bill_from_date,
						'bill_to_date'    => $bill_to_date
				);
				
		//$data['invoice_details']   = $this->Invoice_model->select_invoice_new_details( $search_data);
				
				$this->session->set_userdata('search_criteria_data',$search_data);
			}
			else{

				$search_data = array(
					
					'bill_from_date'     => '',	
					'bill_to_date'     => ''	
				);
				$this->session->set_userdata('search_criteria_data',$search_data);
			}

			
			if ($this->session->userdata('search_criteria_data')){
				$GetData = $this->session->userdata('search_criteria_data');
			}

			$data['search_data']       = $GetData;
			$config                    = array();
			$config['base_url']        = base_url().'Invoice/invoice_list';
			if($GetData!=''){
				$config['total_rows']  = $this->Invoice_model->search_record_count_new($GetData);
			}
			else{
				$config['total_rows']  = $this->Invoice_model->record_count_new();
			}

			$config['per_page']        = 50;
        	$config['uri_segment']     = 3;


        	$config['full_tag_open']   = '<ul class="pagination" style="float:right;">';
        	$config['full_tag_close']  = '</ul>';
        	$config['first_link']      = false;
        	$config['last_link']       = false;
        	$config['first_tag_open']  = '<li>';
        	$config['first_tag_close'] = '</li>';
        	$config['prev_link']       = '&laquo';
        	$config['prev_tag_open']   = '<li class="prev">';
        	$config['prev_tag_close']  = '</li>';
        	$config['next_link']       = '&raquo';
        	$config['next_tag_open']   = '<li>';
        	$config['next_tag_close']  = '</li>';
        	$config['last_tag_open']   = '<li>';
        	$config['last_tag_close']  = '</li>';
        	$config['cur_tag_open']    = '<li class="active"><a href="#">';
        	$config['cur_tag_close']   = '</a></li>';
        	$config['num_tag_open']    = '<li>';
        	$config['num_tag_close']   = '</li>';

        	$this->pagination->initialize($config);
        	$page                      = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        	$data['invoice_details']   = $this->Invoice_model->select_invoice_new_details($config["per_page"], $page, $GetData);
			
				$data['invno']            = $this->Invoice_model->select_act_bill_no();
			
			$data['rad']=$rad;
			$data['bill_from_date']=$bill_from_date;
			$data['bill_to_date']=$bill_to_date;
        	//echo $this->db->last_query(); die();
			$data["links"]             = $this->pagination->create_links();
					
			$data['page_title'] 	   = 'Invoice Cancel';
		    $data['page_name']  	   = 'invoice_gen/invoice_list';
		    $data['page_master']	   = 'Generate Bill';
		    $data['page_master_url']   = 'Invoice/invoice_list';
		    $data['page_function']	   = 'List';
			$this->load->view('template/default', $data);
		}
	}
	
	public function rename_invoice()
	{
		$ids=$this->input->post('ids');
		$bill=$this->input->post('bill');
		$this->db->select('old_invoice_no');
		$this->db->from('invoice');
		$this->db->where('id',$bill);
		$q=$this->db->get()->row();
		$old=$q->old_invoice_no;
		//print_r($old);
		//die();
		$ids=json_decode($ids);
		
		//die();
		foreach($ids as $key =>$value)
		{//print_r($value);
			$inv=$value->raw_prd_inv;
			$id=$value->raw_prd_id;
			   $this->db->set('invoice_no',$old);
				$this->db->where('id',$value->raw_prd_id);
				$this->db->update('invoice');
			//echo $this->db->last_query();
			//die();
		}
		//echo $this->db->last_query();
			//die();
		//die();
		echo json_encode(array('status'=>'success'));
	}
	
	
	
	public function up_invoice(){
		
		
		
		
		//$prefix_result  =	$this->select_data(PREFIX_TBL,'prefix_id,prefix_name,current_no',array('prefix_company_id'=>$company_id,'prefix_branch_id'=>$branch_id,'type'=>$type,'delete_status'=>0), 1, array(),'prefix_id',"DESC",'','' ,'');	

		
		//$prefix_id 	=	$prefix_result->prefix_id;
		//$current_no 	=	$prefix_result->current_no;
		
		
		
		$ids=$this->input->post('ids');
		$ids=json_decode($ids);
		//print_r($ids);die();
	//	$arr=array();
			foreach ($ids as $key => $value) {
				$inv=$value->raw_prd_inv;
				
				$this->db->select('company,branch');
				$this->db->where('invoice_no',$inv);
				$this->db->from('invoice');
				$res=$this->db->get()->row();
				$company_id=$res->company;
				
				$branch_id=$res->branch;
				//print_r($company_id);
				//print_r($branch_id);
				//die();
				
				$prefix_result  =	$this->Invoice_model->select_data(PREFIX_TBL,'prefix_id,prefix_name,current_no',array('prefix_company_id'=>$company_id,'prefix_branch_id'=>$branch_id,'type'=>1,'delete_status'=>0), 1, array(),'prefix_id',"DESC",'','' ,'');	

		
		$prefix_id 	=	$prefix_result->prefix_id;
		
		//$this->db->select('current_no');
		//$this->db->from('current_no');
		//$this->db->where('');
		
		
		$current_no 	=	$prefix_result->current_no;
				
				$result = substr($inv, 0, 3);
				$this->db->select('current_no,id');
					$this->db->from('current_no');
				
				if($result=='IMP')
				{
					
					$this->db->where('type',1);
					
					
				}
				else{
				$this->db->where('type',0);	
				}
				$sql=$this->db->get()->row();
				$current_no=$sql->current_no;
				
				//print_r($result);
				//die();
				
				$exploded = explode(' ', $inv);
				$last=end($exploded);
				if(($current_no-1)==$last)
				{
				$this->db->set('current_no',$last);
				$this->db->where('id',$sql->id);
				$this->db->update('current_no');
				}
				//print_r($last);
				//die();
				
				//$barr=array('id'=>$value->raw_prd_id,
				//'inv'=>$value->raw_prd_inv);
				//$arr[]=$barr;
				$this->db->set('old_invoice_no',$inv);
				$this->db->where('id',$value->raw_prd_id);
				$this->db->update('invoice');
				
				$can=$value->raw_prd_inv."_cancel";
				//print_r($can);die();
				$this->db->set('status',0);
				$this->db->where('id',$value->raw_prd_id);
				$this->db->update('invoice');
				
				$this->db->set('invoice_no',$can);
				$this->db->where('id',$value->raw_prd_id);
				$this->db->update('invoice');
				
				$this->db->set('status',0);
				$this->db->where('invoice_id',$value->raw_prd_id);
				$this->db->update('invoice_details');
				
				$this->db->set('status',0);
				$this->db->where('invoice_id',$value->raw_prd_id);
				$this->db->update('invoice_import_details');
				
				
				
				
			}
			//$drop='';
			
			//foreach ($arr as $k => $v) {
				//$drop.='<option value="'.$v['id'].'">'.$v['inv'].'</option>';
			//}
			
			echo json_encode(array('status'=>'success'));
		
	}
	
	public function get_driver()
	{		
		$entered_str 	=	$this->input->get("q");
		echo $this->Invoice_model->get_driver($entered_str);
	}
	
	

	public function add_invoice()
	{
		
		if(!$this->session->userdata('logged_in')) 
			redirect('Login');
			
		$url		=	'Invoice/generate_invoice';
		$order_field= 	'add';
		$join_array = 	array(0=>array(0=>USER_PERM_TBL,1=>"up_menu_id=menu_id",2=>''));
		$result 	=	$this->Invoice_model->select_data(MENU_TBL,'*',array("url"=>$url,"up_emp_id"=>$this->session->userdata('user_id')),'1',$join_array,$order_field,"DESC",'','','');
		
		if(empty($result))
		{
			$data['page_title'] 	 =	'Warning';
	        $data['page_name']  	 = 	'warning';
	        $data['page_master']	 = 	'Dashboard';
	        $data['page_master_url'] = 	'Dashboard';
	        $data['page_function']	 =	'';
			$this->load->view('template/default', $data);
		}
		else
		{			
			if ($this->input->post('submit'))
			{
				$ttype         = $this->input->post("type");				
				$company       = $this->input->post("bill_company_id");
				$branch        = $this->input->post("bill_brnch_id");
 				$customer      = $this->input->post("bill_cust_id");
				$invoice_date  = $this->input->post("invoice_date");
				$type          = 1;
				
		$this->form_validation->set_error_delimiters('<div style="color:red;text-align:center" class="error"><strong>', '</strong></div>');
				
		if($ttype=='1') // IMPORT 
		{
				
				$this->form_validation->set_rules($this->get_invoice_rule(0));
				if ($this->form_validation->run('add_invoice') == true) 
				{
					
					
					$shipper       		   = $this->input->post("bill_cnsgnr_id");
					$bill_number   		   = $this->input->post("bill_no");
					$gross_weight          = $this->input->post("gross_weight");
					$free_days             = $this->input->post("free_days");
					$port_of_loading       = $this->input->post("port_of_loading");
					$place_of_delivery     = $this->input->post("place_of_delivery");
					$fpod                  = $this->input->post("fpod");
					$container_no          = $this->input->post("container_no");
					$ocean_vessel          = $this->input->post("ocean_vessel");
					$voyage                = $this->input->post("voyage");
					$vessel_berth          = $this->input->post("vessel_berth");
					$arrival_date          = $this->input->post("arrival_date");
					$volume                = $this->input->post("volume");
					$job_ref               = $this->input->post("job_ref");									
					$shipping_bill_no      = '0';
					$exp_container_no      = '0';
					$exp_volume            = '0';
					$exp_container_type    = '0';
					$seal_no               = '0';
					$job_no                = '0';
					$exp_por               = '0';
					$exp_pol               = '0';
					$exp_pod               = '0';
					$exp_fpd               = '0';
					$exp_vessel            = '0';
					$exp_voy               = '0';
					$exp_sailing_date      = '';
					$exp_exchange_rate     = '0';
					$ihc       		       = $this->input->post("ihc");

					if($ihc=='1')
					{
						$ihcsac            = $this->input->post("ihsac");
						
						//print_r($ihcsac);
						//die();
						$usd               = $this->input->post("amt");	
						$ihc_amnt   	   = $this->input->post("ihc_amnt");
						$ihc_sgst   	   = $this->input->post("ihc_sgst");
						$ihc_sgst_amt      = $this->input->post("ihc_sgst_amt");
						$ihc_cgst   	   = $this->input->post("ihc_cgst");
						$ihc_cgst_amt      = $this->input->post("ihc_cgst_amt");
						$ihc_igst   	   = $this->input->post("ihc_igst");
						$ihc_igst_amt      = $this->input->post("ihc_igst_amt");
						$ihc_tax_amnt      = $this->input->post("ihc_tax_amnt");
					}
					else
					{   
						$usd               = 0;	
						$ihc_amnt   	   = 0;
						$ihc_sgst   	   = 0;
						$ihc_sgst_amt      = 0;
						$ihc_cgst   	   = 0;
						$ihc_cgst_amt      = 0;
						$ihc_igst   	   = 0;
						$ihc_igst_amt      = 0;
						$ihc_tax_amnt      = 0;
						$ihcsac            = '';
					}
					
					
					$invoice_no                   = $this->Invoice_model->get_invoice_no_curr($company,$branch,$type);
					$insert_array	              =	    array(	
							"branch"		      =>	$branch,
							"company"	          =>	$company,
							"invoice_no"	      =>	"IMP/21-22/".$invoice_no,
							"actual_invoice"	  =>    $invoice_no,
							"invoice_date"        =>    date('Y-m-d',strtotime($invoice_date)),
							"bill_no"			  =>	$bill_number,
							"shipping_bill_no"    =>    $shipping_bill_no,
							"point_of_discharge"  =>    "0",							
							"shipper"             =>    $shipper,
							"customer"            =>    $customer,
							"gross_weight"		  =>	$gross_weight,
							"free_days"           =>    $free_days,
							"port_of_loading"	  =>	$port_of_loading,
							"place_of_delivery"	  =>	$place_of_delivery,
							"fpod"                =>	$fpod,
							"container_no"		  =>	$container_no,
							"ocean_vessel"		  =>	$ocean_vessel,
							"voyage"			  =>	$voyage,
							"vessel_berth"        =>    $vessel_berth,
							"arrival_date"		  =>	date('Y-m-d',strtotime($arrival_date)),
							"tot_vol"			  =>	$volume,
							"job_ref"             =>    $job_ref,
							"status"              =>    1,														
							"exp_container_no"    =>    $exp_container_no,
							"exp_volume"          =>    $exp_volume,
							"exp_container_type"  =>	$exp_container_type,
							"seal_no"             =>    $seal_no,
							"job_no"              =>    $job_no,
							"exp_por"	          =>	$exp_por,
							"exp_pol"	          =>	$exp_pol,
							"exp_pod"             =>	$exp_pod,
							"exp_fpd"		      =>	$exp_fpd,
							"exp_vessel"		  =>	$exp_vessel,
							"exp_voy"			  =>	$exp_voy,
							"exp_sailing_date"    =>    date('Y-m-d',strtotime($exp_sailing_date)),
							"exp_exchange_rate"	  =>	$exp_exchange_rate,						
							"place_of_receipt"	  =>	'0',
							"place_of_issue"	  =>	'',
							"date_of_issue"       =>    date('Y-m-d'),
							"total_amount"        =>    $this->input->post("tot_before_tax"),
							"sgst_per"            =>    $this->input->post("sgst"),
							"cgst_per"            =>    $this->input->post("cgst"),
							"igst_per"            =>    $this->input->post("igst"),
							"sgst_amt"            =>    $this->input->post("sgst_amt"),
							"cgst_amt"            =>    $this->input->post("cgst_amt"),
							"igst_amt"            =>    $this->input->post("igst_amt"),
 							"tax_amount"          =>    $this->input->post("tax_amnt"),
							"grand_total"         =>    round($this->input->post("view_total")),
							"type"                =>    $this->input->post("type"),							
							"ihc_applicable"      =>    $ihc,
							"ihc_sgst_amount"     =>    $ihc_sgst_amt,
							"ihc_sgst_per"		  =>	$ihc_sgst,
							"ihc_cgst_per"        =>    $ihc_cgst,
							"ihc_cgst_amount"	  =>	$ihc_cgst_amt,
							"ihc_igst_per"	      =>	$ihc_igst,
							"ihc_igst_amount"     =>	$ihc_igst_amt,
							"ihc_tax_amnt"		  =>	$ihc_tax_amnt,
							"ihc_amount"		  =>	$ihc_amnt,
							"ihc_sac"	          => 	$ihcsac,
							"ihc_usd"		      =>	$usd,												
							"created_date"	      =>	date('Y-m-d H:i:s'),
							"import_total"	      =>	$this->input->post("tot_amounts"),
							"remarks"	          =>	$this->input->post("remarks")								
							);

						$this->Invoice_model->save_data(INVOICE_TBL,$insert_array,array(),0);
						//echo $this->db->last_query(); die();
						$invoiceId = $this->db->insert_id();
					
					
					$goods         = $this->input->post("goods");
					$sac           = $this->input->post("sac");
					$amount        = $this->input->post("amount");
					$date_of_issue = date('Y-m-d',strtotime($invoice_date));
					$type          = 1;
					$from_date     = $this->input->post("from_date");
					$to_date       = $this->input->post("to_date");
					$imp_days      = $this->input->post("imp_days");
					$imp_volume    = $this->input->post("imp_volume");
					$imp_usd       = $this->input->post("imp_usd");
					$imp_usd_tot   = $this->input->post("imp_usd_tot");
					$imp_rate      = $this->input->post("imp_rate");
					$imp_total     = $this->input->post("imp_total");
					

						if($invoiceId!='')
						{

							$count    = $this->input->post("gcount");

                            for($i = 0;$i<$count;$i++){
        
								$insertDet	        =	array(
									"invoice_id"        =>  $invoiceId,
									"customer"          =>  $customer,
									"goods"             =>  $goods[$i],
									"sac"               =>  $sac[$i],
									"amount"            =>  $amount[$i],
									"status"            =>  1

									);
								 $this->Invoice_model->save_data(INVOICE_DTL_TBL,$insertDet,array(),0);
						   }

					}
					
					$count    = $this->input->post("impcount");
						for($i = 0;$i<$count;$i++)
						{
        
								$insertDet	        =	array(
									"invoice_id"        =>  $invoiceId,
									"customer"          =>  $customer,
									"from_date"         =>  date('Y-m-d',strtotime($from_date[$i])),
									"to_date"           =>  date('Y-m-d',strtotime($to_date[$i])),
									"days"              =>  $imp_days[$i],
									"volume"            =>  $imp_volume[$i],
									"usd_day"           =>  $imp_usd[$i],
									"usd_total"         =>  $imp_usd_tot[$i],
									"ex_rate"           =>  $imp_rate[$i],
									"total_rupees"      =>  $imp_total[$i],
									"status"            =>  1
									);
								 $this->Invoice_model->save_data("invoice_import_details",$insertDet,array(),0);
						   }

					$this->session->set_flashdata('msg', "Invoice Added Successfully..!");
					redirect('Invoice/generate_invoice');


					
				}
				else
				{
					$this->form_validation->set_message('rule', 'Error Message');
				}
			}
			
			else  /////////////// export
			{
				$this->form_validation->set_rules($this->get_invoice_rule(0));
				if ($this->form_validation->run('add_invoice') == true) 
				{
					
					//// export
					
					$shipper       = $this->input->post("exp_shipper_id");
					$bill_number   		  = $this->input->post("exp_bill_no");
					$shipping_bill_no      = $this->input->post("shipping_bill_no");
					$exp_container_no   = $this->input->post("exp_container_no");
					$exp_volume       = $this->input->post("exp_volume");
					$exp_container_type   = $this->input->post("exp_container_type");
					$seal_no       = $this->input->post("seal_no");
					$job_no   = $this->input->post("job_no");
					$exp_por       = $this->input->post("exp_por");
					$exp_pol   = $this->input->post("exp_pol");
					$exp_pod       = $this->input->post("exp_pod");
					$exp_fpd   = $this->input->post("exp_fpd");
					$exp_vessel       = $this->input->post("exp_vessel");
					$exp_voy   = $this->input->post("exp_voy");
					$exp_sailing_date       = $this->input->post("exp_sailing_date");
					$exp_exchange_rate   = $this->input->post("exp_exchange_rate");
					$ihc       		= $this->input->post("ihc");
					if($ihc=='1')
					{   
						$usd               = $this->input->post("amt");	
						$ihcsac            = $this->input->post("ihsac");
						$ihc_amnt   	= $this->input->post("ihc_amnt");
						$ihc_sgst   	= $this->input->post("ihc_sgst");
						$ihc_sgst_amt   = $this->input->post("ihc_sgst_amt");
						$ihc_cgst   	= $this->input->post("ihc_cgst");
						$ihc_cgst_amt   = $this->input->post("ihc_cgst_amt");
						$ihc_igst   	= $this->input->post("ihc_igst");
						$ihc_igst_amt   = $this->input->post("ihc_igst_amt");
						$ihc_tax_amnt   = $this->input->post("ihc_tax_amnt");
						
					}
					else
					{   
						$usd            = 0;	
						$ihc_amnt   	= 0;
						$ihc_sgst   	= 0;
						$ihc_sgst_amt   = 0;
						$ihc_cgst   	= 0;
						$ihc_cgst_amt   = 0;
						$ihc_igst   	= 0;
						$ihc_igst_amt   = 0;
						$ihc_tax_amnt   = 0;
						$ihcsac            = '';
					}
				
					$gross_weight       = '0';
					$free_days   = 0;
					$port_of_loading       = '0';
					$place_of_delivery   = '0';
					$fpod       = '0';
					$container_no   = '0';
					$ocean_vessel       = '0';
					$voyage   = '0';
					$vessel_berth       = '0';
					$arrival_date   = '';
					$volume       = '0';
					$job_ref   = '0';
					
					
					$type          = 1;
					$invoice_no    = $this->Invoice_model->get_invoice_no_curr($company,$branch,$type);
						$insert_array	              =	    array(	
							"branch"		      =>	$branch,
							"company"	          =>	$company,
							"invoice_no"	      =>	 "EXP/21-22/".$invoice_no,
							"actual_invoice"	  =>    $invoice_no,
							"invoice_date"        =>    date('Y-m-d',strtotime($invoice_date)),
							"bill_no"			  =>	$bill_number,
							"shipping_bill_no"    =>    $shipping_bill_no,
							"point_of_discharge"  =>    "0",
							
							"shipper"             =>    $shipper,
							"customer"            =>    $customer,
							"gross_weight"		  =>	$gross_weight,
							"free_days"           =>    $free_days,
							"port_of_loading"	  =>	$port_of_loading,
							"place_of_delivery"	  =>	$place_of_delivery,
							"fpod"                =>	$fpod,
							"container_no"		  =>	$container_no,
							"ocean_vessel"		  =>	$ocean_vessel,
							"voyage"			  =>	$voyage,
							"vessel_berth"        =>    $vessel_berth,
							"arrival_date"		  =>	$arrival_date,
							"tot_vol"			  =>	$volume,
							"job_ref"             =>    $job_ref,
							"status"              =>    1,
							"ihc_sac"	          => 	$ihcsac,
							
							"exp_container_no"             =>    $exp_container_no,
							"exp_volume"            =>    $exp_volume,
							"exp_container_type"		  =>	$exp_container_type,
							"seal_no"             =>    $seal_no,
							"job_no"           =>    $job_no,
							"exp_por"	  =>	$exp_por,
							"exp_pol"	  =>	$exp_pol,
							"exp_pod"                =>	$exp_pod,
							"exp_fpd"		  =>	$exp_fpd,
							"exp_vessel"		  =>	$exp_vessel,
							"exp_voy"			  =>	$exp_voy,
							"exp_sailing_date"        =>   date('Y-m-d',strtotime($exp_sailing_date)),
							"exp_exchange_rate"		  =>	$exp_exchange_rate,
							"ihc_applicable"      =>    $ihc,
							"ihc_sgst_amount"     =>    $ihc_sgst_amt,
							"ihc_sgst_per"		  =>	$ihc_sgst,
							"ihc_cgst_per"        =>    $ihc_cgst,
							"ihc_cgst_amount"	  =>	$ihc_cgst_amt,
							"ihc_igst_per"	      =>	$ihc_igst,
							"ihc_igst_amount"     =>	$ihc_igst_amt,
							"ihc_tax_amnt"		  =>	$ihc_tax_amnt,
							"ihc_amount"		  =>	$ihc_amnt,
							"ihc_usd"		      =>	$usd,
						     
							"place_of_receipt"	  =>	'0',
							"place_of_issue"	  =>	'',
							"date_of_issue"       =>    date('Y-m-d'),
							"total_amount"        =>    $this->input->post("tot_before_tax"),
							"sgst_per"            =>    $this->input->post("sgst"),
							"cgst_per"            =>    $this->input->post("cgst"),
							"igst_per"            =>    $this->input->post("igst"),
							"sgst_amt"            =>    $this->input->post("sgst_amt"),
							"cgst_amt"            =>    $this->input->post("cgst_amt"),
							"igst_amt"            =>    $this->input->post("igst_amt"),
 							"tax_amount"          =>    $this->input->post("tax_amnt"),
							"grand_total"         =>    round($this->input->post("view_total")),
							"type"                =>    $this->input->post("type"),
							"created_date"	      =>	date('Y-m-d H:i:s'),
							"import_total"	      =>	$this->input->post("tot_amounts"),	
							"remarks"	          =>	$this->input->post("remarks")							
							);

						$this->Invoice_model->save_data(INVOICE_TBL,$insert_array,array(),0);
						$invoiceId = $this->db->insert_id();
					
					
					
					
					$goods         = $this->input->post("goods");
					$sac           = $this->input->post("sac");
					$amount        = $this->input->post("amount");
					$date_of_issue = date('Y-m-d',strtotime($invoice_date));
					$type          = 1;
					$from_date        = $this->input->post("from_date");
					$to_date        = $this->input->post("to_date");
					$imp_days        = $this->input->post("imp_days");
					$imp_volume        = $this->input->post("imp_volume");
					$imp_usd        = $this->input->post("imp_usd");
					$imp_usd_tot        = $this->input->post("imp_usd_tot");
					$imp_rate       = $this->input->post("imp_rate");
					$imp_total        = $this->input->post("imp_total");
					
					
					
						if($invoiceId!='')
						{

							$count    = $this->input->post("gcount");

                            for($i = 0;$i<$count;$i++){
        
								$insertDet	        =	array(
									"invoice_id"        =>  $invoiceId,
									"customer"          =>  $customer,
									"goods"             =>  $goods[$i],
									"sac"               =>  $sac[$i],
									"amount"            =>  $amount[$i],
									"status"            =>  1

									);
								 $this->Invoice_model->save_data(INVOICE_DTL_TBL,$insertDet,array(),0);
						   }

					}
					
				

                           
							$this->session->set_flashdata('msg', "Invoice Added Successfully..!");
							redirect('Invoice/generate_invoice');


					
				}
				else
				{
					$this->form_validation->set_message('rule', 'Error Message');
				}
			}
			
			
			}

			$data['branch_bill_no']   = $this->Invoice_model->select_data(BRANCH_TBL,$select='branch_bill_no',array(), $by_row=0, array(),'branch_name',"ASC",'', 0, null);		
			$data['branch_drpdwn']    =	$this->Invoice_model->select_data(BRANCH_TBL,$select='branch_id,branch_name,branch_bill_no',array(), $by_row=0, array(),'branch_id',"ASC",'', 0, null);
			$data['company_drpdwn']   =	$this->Invoice_model->select_data(COMPANY_TBL,$select='cmp_id,cmp_name',array(), $by_row=0, array(),'cmp_name',"ASC",'', 0, null);
			$data['consignor_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNOR_TBL,$select='consignor_id,consignor_name',array(), $by_row=0, array(),'consignor_name',"ASC",'', 0, null);
			$data['consignee_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNEE_TBL,$select='consignee_id,consignee_name',array(), $by_row=0, array(),'consignee_name',"ASC",'', 0, null);
			$data['customer_drpdwn']  =	$this->Invoice_model->select_data(CUSTOMER_TBL,$select='customer_id,customer_name',array(), $by_row=0, array(),'customer_name',"ASC",'', 0, null);
			$data['notify_drpdwn']    =	$this->Invoice_model->select_data(NOTIFY_TBL,$select='notify_id,notify_name',array(), $by_row=0, array(),'notify_name',"ASC",'', 0, null);
			$data['portname_drpdwn']  =	$this->Invoice_model->select_data(PORT_TBL,$select='port_of_dis_id,port_of_dis_name',array(), $by_row=0, array(),'port_of_dis_name',"ASC",'', 0, null);

			$data['date_format_text'] =	$date_format_text;
			$data['page_title'] 	  =	'Invoice';
		    $data['page_name']  	  = 'invoice/add-invoice';
		    $data['page_master']	  = 'Generate Bill';
		    $data['page_master_url']  = 'Invoice/add_invoice';
		    $data['page_function']	  =	'Add';
			$this->load->view('template/default', $data); //invoice_date
		}
	}
	public function edit_invoice($id)
	{
		$data["invoicenosearch"]   = '';
	//	echo "<pre>";print_r();exit();
	//echo "here". $this->session->userdata('user_id');exit();

		if(!$this->session->userdata('logged_in')) 
			redirect('Login');

			//$invoice_no             = $this->Invoice_model->get_invoice_no_curr($company,$branch,$type);
	

           
		       //	echo "id-->".$id; exit();
		      $data["invoice_edit_id"]    = $this->Invoice_model->edit_invoice_no($id);
			  $invoice_no_search = $data["invoice_edit_id"]->invoice_no;
			 // echo  $invoice_no_search//exit();
			
			if ($this->input->post('get_invoice'))
			{
				
				$invoice_no_search          = $this->input->post("invoice_no_search");
				
				
				$data["invoicenosearch"]    = $invoice_no_search;
				$data["invoice_details"]    = $this->Invoice_model->get_invoice_id($invoice_no_search);
				$invoiceID = $data["invoice_details"]->id;
			
			//	echo "<pre>";print_r($data["invoice_details"]); die();
			
				//echo "----------<pre>";print_r($_POST);exit();

				$data["invoice_details2"]   = $this->Invoice_model->get_invoice_details($invoiceID );
                $data["invoice_details1"]   = $this->Invoice_model->get_invoice_import_details($invoiceID);

				$data['invoice_no']         = $invoice_no_search;
				
			//	 echo "invoice_no:".$invoice_no_search ; //exit();
			  // echo "<pre>";print_r($data["invoice_details"]); 
			//exit();
			
			}
			
			if($this->input->post('update_invoice')!="" ){

				//echo "<pre>";print_r($data["invoice_details"]); 
		    
			$url		=	'Invoice/generate_invoice';
			$order_field= 	'Edit';
			$join_array = 	array(0=>array(0=>USER_PERM_TBL,1=>"up_menu_id=menu_id",2=>''));
			$result 	=	$this->Invoice_model->select_data(MENU_TBL,'*',array("url"=>$url,"up_emp_id"=>$this->session->userdata('user_id')),'1',$join_array,$order_field,"DESC",'','','');
		    // echo "<pre>".print_r($result);
			//print_r($this->input->post('update_invoice')) ;
			
			 //exit();
			if(empty($result))
			{
				$data['page_title'] 	 =	'Warning';
				$data['page_name']  	 = 	'warning';
				$data['page_master']	 = 	'Dashboard';
				$data['page_master_url'] = 	'Dashboard';
				$data['page_function']	 =	'';
				$this->load->view('template/default', $data);
			}
			else
			{			
				if ($this->input->post('update_invoice'))
				{  //echo "here";
					//exit();
					$ttype         = $this->input->post("type");				
					$company       = $this->input->post("bill_company_id");
					$branch        = $this->input->post("bill_brnch_id");
					$customer      = $this->input->post("bill_cust_id");
					$invoice_date  = $this->input->post("invoice_date");
					$type          = 1;
					$invoice_num   = $this->input->post("invoice_id");

					$invoice_ids   = $this->input->post("invoice_main");
					//echo "invoice_ids->".$invoice_ids;
					//exit;
			$this->form_validation->set_error_delimiters('<div style="color:red;text-align:center" class="error"><strong>', '</strong></div>');
				
			if($ttype=='1') // IMPORT 
			{

			
				

					$this->form_validation->set_rules($this->get_invoice_rule(0));
					if ($this->form_validation->run('edit_invoice') == true) 
					{
						
						
						$shipper       		   = $this->input->post("bill_cnsgnr_id");
						$bill_number   		   = $this->input->post("bill_no");
						$gross_weight          = $this->input->post("gross_weight");
						$free_days             = $this->input->post("free_days");
						$port_of_loading       = $this->input->post("port_of_loading");
						$place_of_delivery     = $this->input->post("place_of_delivery");
						$fpod                  = $this->input->post("fpod");
						$container_no          = $this->input->post("container_no");
						$ocean_vessel          = $this->input->post("ocean_vessel");
						$voyage                = $this->input->post("voyage");
						$vessel_berth          = $this->input->post("vessel_berth");
						$arrival_date          = $this->input->post("arrival_date");
						$volume                = $this->input->post("volume");
						$job_ref               = $this->input->post("job_ref");		
						//$usd               = $this->input->post("amt");							
						$shipping_bill_no      = '0';
						$exp_container_no      = '0';
						$exp_volume            = '0';
						$exp_container_type    = '0';
						$seal_no               = '0';
						$job_no                = '0';
						$exp_por               = '0';
						$exp_pol               = '0';
						$exp_pod               = '0';
						$exp_fpd               = '0';
						$exp_vessel            = '0';
						$exp_voy               = '0';
						$exp_sailing_date      = '';
						$exp_exchange_rate     = '0';
						$ihc       		       = $this->input->post("ihc");
	
						if($ihc=='1')
						{
							$ihcsac            = $this->input->post("ihsac");
							
							//print_r($ihcsac);
							//die();
							$usd               = $this->input->post("amt");	
							$ihc_amnt   	   = $this->input->post("ihc_amnt");
							$ihc_sgst   	   = $this->input->post("ihc_sgst");
							$ihc_sgst_amt      = $this->input->post("ihc_sgst_amt");
							$ihc_cgst   	   = $this->input->post("ihc_cgst");
							$ihc_cgst_amt      = $this->input->post("ihc_cgst_amt");
							$ihc_igst   	   = $this->input->post("ihc_igst");
							$ihc_igst_amt      = $this->input->post("ihc_igst_amt");
							$ihc_tax_amnt      = $this->input->post("ihc_tax_amnt");
						}
						else
						{  
							$usd               = 0;
							$ihc_amnt   	   = 0;
							$ihc_sgst   	   = 0;
							$ihc_sgst_amt      = 0;
							$ihc_cgst   	   = 0;
							$ihc_cgst_amt      = 0;
							$ihc_igst   	   = 0;
							$ihc_igst_amt      = 0;
							$ihc_tax_amnt      = 0;
							$ihcsac            = '';
						}
						
						
					//	$invoice_no                   = $this->Invoice_model->get_invoice_no_curr($company,$branch,$type);
					
					     	$insert_array	          =	    array(	
								"branch"		      =>	$branch,
								"company"	          =>	$company,
							
								"invoice_date"        =>    date('Y-m-d',strtotime($invoice_date)),
								"bill_no"			  =>	$bill_number,
								"shipping_bill_no"    =>    $shipping_bill_no,
								"point_of_discharge"  =>    "0",							
								"shipper"             =>    $shipper,
								"customer"            =>    $customer,
								"gross_weight"		  =>	$gross_weight,
								"free_days"           =>    $free_days,
								"port_of_loading"	  =>	$port_of_loading,
								"place_of_delivery"	  =>	$place_of_delivery,
								"fpod"                =>	$fpod,
								"container_no"		  =>	$container_no,
								"ocean_vessel"		  =>	$ocean_vessel,
								"voyage"			  =>	$voyage,
								"vessel_berth"        =>    $vessel_berth,
								"arrival_date"		  =>	date('Y-m-d',strtotime($arrival_date)),
								"tot_vol"			  =>	$volume,
								"job_ref"             =>    $job_ref,
								"status"              =>    1,														
								"exp_container_no"    =>    $exp_container_no,
								"exp_volume"          =>    $exp_volume,
								"exp_container_type"  =>	$exp_container_type,
								"seal_no"             =>    $seal_no,
								"job_no"              =>    $job_no,
								"exp_por"	          =>	$exp_por,
								"exp_pol"	          =>	$exp_pol,
								"exp_pod"             =>	$exp_pod,
								"exp_fpd"		      =>	$exp_fpd,
								"exp_vessel"		  =>	$exp_vessel,
								"exp_voy"			  =>	$exp_voy,
								"exp_sailing_date"    =>    date('Y-m-d',strtotime($exp_sailing_date)),
								"exp_exchange_rate"	  =>	$exp_exchange_rate,						
								"place_of_receipt"	  =>	'0',
								"place_of_issue"	  =>	'',
								"date_of_issue"       =>    date('Y-m-d'),
								"total_amount"        =>    $this->input->post("tot_before_tax"),
								"sgst_per"            =>    $this->input->post("sgst"),
								"cgst_per"            =>    $this->input->post("cgst"),
								"igst_per"            =>    $this->input->post("igst"),
								"sgst_amt"            =>    $this->input->post("sgst_amt"),
								"cgst_amt"            =>    $this->input->post("cgst_amt"),
								"igst_amt"            =>    $this->input->post("igst_amt"),
								 "tax_amount"          =>    $this->input->post("tax_amnt"),
								"grand_total"         =>    round($this->input->post("view_total")),
								"type"                =>    $this->input->post("type"),							
								"ihc_applicable"      =>    $ihc,
								"ihc_sgst_amount"     =>    $ihc_sgst_amt,
								"ihc_sgst_per"		  =>	$ihc_sgst,
								"ihc_cgst_per"        =>    $ihc_cgst,
								"ihc_cgst_amount"	  =>	$ihc_cgst_amt,
								"ihc_igst_per"	      =>	$ihc_igst,
								"ihc_igst_amount"     =>	$ihc_igst_amt,
								"ihc_tax_amnt"		  =>	$ihc_tax_amnt,
								"ihc_amount"		  =>	$ihc_amnt,
								"ihc_sac"	          => 	$ihcsac,
								"ihc_usd"		      =>	$usd,												
								"created_date"	      =>	date('Y-m-d H:i:s'),
								"import_total"	      =>	$this->input->post("tot_amounts"),
								"remarks"	          =>	$this->input->post("remarks")								
								);
						
						//echo "<pre>";print_r($insert_array);
						//exit();
						//echo "invoice_no".$invoice_no_search; exit();
							$arData  = array('invoice_no'=>$invoice_num );// Edit invoice_no
							
							//For saving log data
							$post_array=json_encode($insert_array);
							$created_by = $this->session->userdata('user_id');
							$created_date = date('Y-m-d H:i:s');
                
						    $this->Invoice_model->invoice_log_data($invoice_num,$post_array,$created_by,$created_date);
						//	echo $this->db->last_query(); 
							echo "<br>";
							

							//Updating invoice table
							$result =	$this->Invoice_model->save_data(INVOICE_TBL,$insert_array,$arData,1);//exit();
						//	echo $this->db->last_query(); 
							echo "<br>"; 

							//$invoiceId = $this->db->insert_id();
						echo "from_date". $fromDate =	$this->input->post("from_date");
						echo "todate".$toDate   = $this->input->post("to_date");
						
						$goods         = $this->input->post("goods");
						$sac           = $this->input->post("sac");
						$amount        = $this->input->post("amount");
						$date_of_issue = date('Y-m-d',strtotime($invoice_date));
						$type          = 1;
					//echo "aftr_from".	$from_date     = date('Y-m-d',strtotime($fromDate));
					//echo "aftr_to". 	$to_date       = date('Y-m-d',strtotime($toDate)); exit();
						$imp_days      = $this->input->post("imp_days");
						$imp_volume    = $this->input->post("imp_volume");
						$imp_usd       = $this->input->post("imp_usd");
						$imp_usd_tot   = $this->input->post("imp_usd_tot");
						$imp_rate      = $this->input->post("imp_rate");
						$imp_total     = $this->input->post("imp_total");
						
						if($result!='')
						{		
							//For saving detail log data
							//$detail_array=json_encode($insertDet);
							$created_by = $this->session->userdata('user_id');
							$created_date = date('Y-m-d H:i:s');
							//echo"<pre>";    print_r($detail_array);exit();
							$this->Invoice_model->invoice_log_detail($invoice_ids,$detail_array,$created_by,$created_date);
							//echo $this->db->last_query(); 
							echo "<br>";

							//change status of existing invoice detail values of old invoice id
							// echo "invoice_ids----------->".$invoice_ids; 
							$this->Invoice_model->change_status_detail($invoice_ids);
							//echo $this->db->last_query(); 
							//echo "<br>";

                           //For saving import log data
						   $import_array=json_encode($insertDet);
						   //echo"<pre>";    print_r($detail_array);exit();
						   $created_by = $this->session->userdata('user_id');
						   $created_date = date('Y-m-d H:i:s');
			   
						   $this->Invoice_model->invoice_log_import($invoice_ids,$detail_array,$created_by,$created_date);
						   //echo $this->db->last_query(); 
						 //  echo "<br>";

						  //changing status of existing import detail values from old invoice id	     
							$this->Invoice_model->change_status_import($invoice_ids);
						//	echo $this->db->last_query(); 
						//	echo "<br>";
 
							if($invoice_ids!='')
							{  
							//$arId  = array('invoice_id'=>$invoice_ids );// Edit invoice_id

								//echo "arId------------>"."<pre>"; print_r($arId) ;
								// exit();
							$count    = $this->input->post("gcount");
							//echo "invoice_ids".$invoice_ids; //exit();
							//echo "<br>";
							//echo "<br>";
								for($i = 0;$i<$count;$i++){
			
									$insertDet	        =	array(
										"invoice_id"        =>  $invoice_ids,
										"customer"          =>  $customer,
										"goods"             =>  $goods[$i],
										"sac"               =>  $sac[$i],
										"amount"            =>  $amount[$i],
										"status"            =>  1
	
										);
										
									 //$arId  = array('invoice_id'=>$invoice_ids );// Edit invoice_id
									 
									
									//Update invoice detail table
									 $this->Invoice_model->save_data("invoice_details",$insertDet,array(),0);
									 //echo $this->db->last_query(); 
									 //echo "<br>";
							   }
	
						  }
								
						   $count    = $this->input->post("impcount");
						  // echo "impcount".$count; //exit();
							for($i = 0;$i<$count;$i++)
							{
			
									$insertDet	        =	array(
										"invoice_id"		=>  $invoice_ids,
										"customer"          =>  $customer,
										"from_date"         =>  date('Y-m-d',strtotime($fromDate[$i])),
										"to_date"           =>  date('Y-m-d',strtotime($toDate[$i])),
										"days"              =>  $imp_days[$i],
										"volume"            =>  $imp_volume[$i],
										"usd_day"           =>  $imp_usd[$i],
										"usd_total"         =>  $imp_usd_tot[$i],
										"ex_rate"           =>  $imp_rate[$i],
										"total_rupees"      =>  $imp_total[$i],
										"status"            =>  1
										);
									 $arId  = array('invoice_id'=>$invoice_ids );// Edit invoice_id
									 
									 $this->Invoice_model->save_data("invoice_import_details",$insertDet,array(),0);
									// echo $this->db->last_query(); //die();
									// echo "<br>";
							   }
							} //exit();
						$this->session->set_flashdata('msg', "Invoice Updated Successfully..!");
						redirect('Invoice/generate_invoice');
					}
					else
					{
						$this->form_validation->set_message('rule', 'Error Message');
					}
				}
				
				else  /////////////// export
				{
					$this->form_validation->set_rules($this->get_invoice_rule(0));
					if ($this->form_validation->run('edit_invoice') == true) 
					{ //echo "here"; exit();
						
						//// export
						
						$shipper       = $this->input->post("exp_shipper_id");
						$bill_number   		  = $this->input->post("exp_bill_no");
						$shipping_bill_no      = $this->input->post("shipping_bill_no");
						$exp_container_no   = $this->input->post("exp_container_no");
						$exp_volume       = $this->input->post("exp_volume");
						$exp_container_type   = $this->input->post("exp_container_type");
						$seal_no       = $this->input->post("seal_no");
						$job_no   = $this->input->post("job_no");
						$exp_por       = $this->input->post("exp_por");
						$exp_pol   = $this->input->post("exp_pol");
						$exp_pod       = $this->input->post("exp_pod");
						$exp_fpd   = $this->input->post("exp_fpd");
						$exp_vessel       = $this->input->post("exp_vessel");
						$exp_voy   = $this->input->post("exp_voy");
						$exp_sailing_date       = $this->input->post("exp_sailing_date");
						$exp_exchange_rate   = $this->input->post("exp_exchange_rate");
						//$usd               = $this->input->post("amt");	
						$ihc       		= $this->input->post("ihc");
						if($ihc=='1')
						{   
							$usd               = $this->input->post("amt");	
							$ihcsac            = $this->input->post("ihsac");
							$ihc_amnt   	= $this->input->post("ihc_amnt");
							$ihc_sgst   	= $this->input->post("ihc_sgst");
							$ihc_sgst_amt   = $this->input->post("ihc_sgst_amt");
							$ihc_cgst   	= $this->input->post("ihc_cgst");
							$ihc_cgst_amt   = $this->input->post("ihc_cgst_amt");
							$ihc_igst   	= $this->input->post("ihc_igst");
							$ihc_igst_amt   = $this->input->post("ihc_igst_amt");
							$ihc_tax_amnt   = $this->input->post("ihc_tax_amnt");
						}
						else
						{   $usd            = 0;	
							$ihc_amnt   	= 0;
							$ihc_sgst   	= 0;
							$ihc_sgst_amt   = 0;
							$ihc_cgst   	= 0;
							$ihc_cgst_amt   = 0;
							$ihc_igst   	= 0;
							$ihc_igst_amt   = 0;
							$ihc_tax_amnt   = 0;
							$ihcsac            = '';
						}
					
						$gross_weight       = '0';
						$free_days   = 0;
						$port_of_loading       = '0';
						$place_of_delivery   = '0';
						$fpod       = '0';
						$container_no   = '0';
						$ocean_vessel       = '0';
						$voyage   = '0';
						$vessel_berth       = '0';
						$arrival_date   = '';
						$volume       = '0';
						$job_ref   = '0';
						
						
						$type          = 1;
						//$invoice_no    = $this->Invoice_model->get_invoice_no_curr($company,$branch,$type);
							$insert_array	          =	    array(	
								"branch"		      =>	$branch,
								"company"	          =>	$company,
								
							
								"invoice_date"        =>    date('Y-m-d',strtotime($invoice_date)),
								"bill_no"			  =>	$bill_number,
								"shipping_bill_no"    =>    $shipping_bill_no,
								"point_of_discharge"  =>    "0",
								
								"shipper"             =>    $shipper,
								"customer"            =>    $customer,
								"gross_weight"		  =>	$gross_weight,
								"free_days"           =>    $free_days,
								"port_of_loading"	  =>	$port_of_loading,
								"place_of_delivery"	  =>	$place_of_delivery,
								"fpod"                =>	$fpod,
								"container_no"		  =>	$container_no,
								"ocean_vessel"		  =>	$ocean_vessel,
								"voyage"			  =>	$voyage,
								"vessel_berth"        =>    $vessel_berth,
								"arrival_date"		  =>	$arrival_date,
								"tot_vol"			  =>	$volume,
								"job_ref"             =>    $job_ref,
								"status"              =>    1,
								"ihc_sac"	          => 	$ihcsac,
								
								"exp_container_no"             =>    $exp_container_no,
								"exp_volume"           		   =>    $exp_volume,
								"exp_container_type"		   =>	$exp_container_type,
								"seal_no"            		   =>    $seal_no,
								"job_no"           			   =>    $job_no,
								"exp_por"	                   =>	$exp_por,
								"exp_pol"	                   =>	$exp_pol,
								"exp_pod"                      =>	$exp_pod,
								"exp_fpd"		               =>	$exp_fpd,
								"exp_vessel"		  =>	$exp_vessel,
								"exp_voy"			  =>	$exp_voy,
								"exp_sailing_date"        =>   date('Y-m-d',strtotime($exp_sailing_date)),
								"exp_exchange_rate"		  =>	$exp_exchange_rate,
								"ihc_applicable"      =>    $ihc,
								"ihc_sgst_amount"     =>    $ihc_sgst_amt,
								"ihc_sgst_per"		  =>	$ihc_sgst,
								"ihc_cgst_per"        =>    $ihc_cgst,
								"ihc_cgst_amount"	  =>	$ihc_cgst_amt,
								"ihc_igst_per"	      =>	$ihc_igst,
								"ihc_igst_amount"     =>	$ihc_igst_amt,
								"ihc_tax_amnt"		  =>	$ihc_tax_amnt,
								"ihc_amount"		  =>	$ihc_amnt,
								"ihc_usd"		      =>	$usd,
							
								"place_of_receipt"	  =>	'0',
								"place_of_issue"	  =>	'',
								"date_of_issue"       =>    date('Y-m-d'),
								"total_amount"        =>    $this->input->post("tot_before_tax"),
								"sgst_per"            =>    $this->input->post("sgst"),
								"cgst_per"            =>    $this->input->post("cgst"),
								"igst_per"            =>    $this->input->post("igst"),
								"sgst_amt"            =>    $this->input->post("sgst_amt"),
								"cgst_amt"            =>    $this->input->post("cgst_amt"),
								"igst_amt"            =>    $this->input->post("igst_amt"),
								 "tax_amount"          =>    $this->input->post("tax_amnt"),
								"grand_total"         =>    round($this->input->post("view_total")),
								"type"                =>    $this->input->post("type"),
								"created_date"	      =>	date('Y-m-d H:i:s'),
								"import_total"	      =>	$this->input->post("tot_amounts"),	
								"remarks"	          =>	$this->input->post("remarks")							
								);
								
							///echo "<pre>";print_r($insert_array);
							//exit();
							
							
							$arData  = array('invoice_no'=>$invoice_num );// Edit invoice_no
							
							
							//For saving log data
							$post_array=json_encode($insert_array);
							$created_by = $this->session->userdata('user_id');
							$created_date = date('Y-m-d H:i:s');
                
						    $this->Invoice_model->invoice_log_data($invoice_num,$post_array,$created_by,$created_date);
						//	echo $this->db->last_query(); 
						//	echo "<br>";
						//	echo "<br>";
							
							//Updating invoice table
						$result =	$this->Invoice_model->save_data(INVOICE_TBL,$insert_array,$arData,1);
							
							//echo $this->db->last_query(); //die();
						//	echo "<br>";
						//	echo "<br>";
							//$invoiceId = $this->db->insert_id();
						
					//	echo "result---------------->".$result;exit;
						
						
						$goods         = $this->input->post("goods");
						$sac           = $this->input->post("sac");
						$amount        = $this->input->post("amount");
						$date_of_issue = date('Y-m-d',strtotime($invoice_date));
						$type          = 1;
						$from_date        = $this->input->post("from_date");
						$to_date        = $this->input->post("to_date");
						$imp_days        = $this->input->post("imp_days");
						$imp_volume        = $this->input->post("imp_volume");
						$imp_usd        = $this->input->post("imp_usd");
						$imp_usd_tot        = $this->input->post("imp_usd_tot");
						$imp_rate       = $this->input->post("imp_rate");
						$imp_total        = $this->input->post("imp_total");
						
					
	
							if($result!='')
							{   
								 //For saving detail log data
								 $detail_array=json_encode($insertDet);
								 $created_by = $this->session->userdata('user_id');
								 $created_date = date('Y-m-d H:i:s');

							 
								 $this->Invoice_model->invoice_log_detail($invoice_ids,$detail_array,$created_by,$created_date);
								 //echo $this->db->last_query(); 
							  // echo "<br>";
							   //echo "<br>";
								
                                //change status of existing invoice detail values of old invoice id
								// echo "invoice_ids----------->".$invoice_ids; 
								$this->Invoice_model->change_status_detail($invoice_ids);
							///	echo $this->db->last_query(); 
							//	echo "<br>";

							  
								$count    = $this->input->post("gcount");
								//echo "count------------" .$count; //exit();
								for($i = 0;$i<$count;$i++){
			
									$insertDet	        =	array(

										"invoice_id"        =>  $invoice_ids,
										"customer"          =>  $customer,
										"goods"             =>  $goods[$i],
										"sac"               =>  $sac[$i],
										"amount"            =>  $amount[$i],
										"status"            =>  1
	
										);
									

									
									 $this->Invoice_model->save_data("invoice_details",$insertDet,array(),0);
									// echo $this->db->last_query(); //die();
									
							           // echo "<br>";
							   }
	
						}
					 //exit();
								$this->session->set_flashdata('msg', "Invoice Updated Successfully..!");
								redirect('Invoice/generate_invoice');

					}
					else
					{
						$this->form_validation->set_message('rule', 'Error Message');
					}
				}
				
				
				}
	
				$data['branch_bill_no']   = $this->Invoice_model->select_data(BRANCH_TBL,$select='branch_bill_no',array(), $by_row=0, array(),'branch_name',"ASC",'', 0, null);		
				$data['branch_drpdwn']    =	$this->Invoice_model->select_data(BRANCH_TBL,$select='branch_id,branch_name,branch_bill_no',array(), $by_row=0, array(),'branch_id',"ASC",'', 0, null);
				$data['company_drpdwn']   =	$this->Invoice_model->select_data(COMPANY_TBL,$select='cmp_id,cmp_name',array(), $by_row=0, array(),'cmp_name',"ASC",'', 0, null);
				$data['consignor_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNOR_TBL,$select='consignor_id,consignor_name',array(), $by_row=0, array(),'consignor_name',"ASC",'', 0, null);
				$data['consignee_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNEE_TBL,$select='consignee_id,consignee_name',array(), $by_row=0, array(),'consignee_name',"ASC",'', 0, null);
				$data['customer_drpdwn']  =	$this->Invoice_model->select_data(CUSTOMER_TBL,$select='customer_id,customer_name',array(), $by_row=0, array(),'customer_name',"ASC",'', 0, null);
				$data['notify_drpdwn']    =	$this->Invoice_model->select_data(NOTIFY_TBL,$select='notify_id,notify_name',array(), $by_row=0, array(),'notify_name',"ASC",'', 0, null);
				$data['portname_drpdwn']  =	$this->Invoice_model->select_data(PORT_TBL,$select='port_of_dis_id,port_of_dis_name',array(), $by_row=0, array(),'port_of_dis_name',"ASC",'', 0, null);
	
				$data['date_format_text'] =	$date_format_text;
				$data['page_title'] 	  =	'Invoice';
				$data['page_name']  	  = 'invoice/edit-invoice';
				$data['page_master']	  = 'Generate Bill';
				$data['page_master_url']  = 'Invoice/edit_invoice';
				$data['page_function']	  =	'Edit';
				$this->load->view('template/default', $data); //invoice_date
		   }

		 
		}
		  else{

			$data['branch_bill_no']   = $this->Invoice_model->select_data(BRANCH_TBL,$select='branch_bill_no',array(), $by_row=0, array(),'branch_name',"ASC",'', 0, null);		
			$data['branch_drpdwn']    =	$this->Invoice_model->select_data(BRANCH_TBL,$select='branch_id,branch_name,branch_bill_no',array(), $by_row=0, array(),'branch_id',"ASC",'', 0, null);
			$data['company_drpdwn']   =	$this->Invoice_model->select_data(COMPANY_TBL,$select='cmp_id,cmp_name',array(), $by_row=0, array(),'cmp_name',"ASC",'', 0, null);
			$data['consignor_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNOR_TBL,$select='consignor_id,consignor_name',array(), $by_row=0, array(),'consignor_name',"ASC",'', 0, null);
			$data['consignee_drpdwn'] =	$this->Invoice_model->select_data(CONSIGNEE_TBL,$select='consignee_id,consignee_name',array(), $by_row=0, array(),'consignee_name',"ASC",'', 0, null);
			$data['customer_drpdwn']  =	$this->Invoice_model->select_data(CUSTOMER_TBL,$select='customer_id,customer_name',array(), $by_row=0, array(),'customer_name',"ASC",'', 0, null);
			$data['notify_drpdwn']    =	$this->Invoice_model->select_data(NOTIFY_TBL,$select='notify_id,notify_name',array(), $by_row=0, array(),'notify_name',"ASC",'', 0, null);
			$data['portname_drpdwn']  =	$this->Invoice_model->select_data(PORT_TBL,$select='port_of_dis_id,port_of_dis_name',array(), $by_row=0, array(),'port_of_dis_name',"ASC",'', 0, null);


		        $data['date_format_text'] =	$date_format_text;
				$data['page_title'] 	  =	'Invoice';
				$data['page_name']  	  = 'invoice/edit-invoice';
				$data['page_master']	  = 'Generate Bill';
				$data['page_master_url']  = 'Invoice/edit_invoice';
				$data['page_function']	  =	'Edit';
				$this->load->view('template/default', $data); //invoice_date 
		 }
	}






	public function get_invoice_rule($update=0)
	{
		$config 	= array();

		 $config []	=   array(
		                     'field'   => 'bill_brnch_id', 
		                     'label'   => 'Branch', 
		                     'rules'   => 'required'
		                  );
		
        $config []	=   array(
		                     'field'   => 'bill_company_id', 
		                     'label'   => 'Company', 
		                     'rules'   => 'required'
		                  );
        $config []	=   array(
		                     'field'   => 'bill_cust_id', 
		                     'label'   => 'Customer', 
		                     'rules'   => 'required'
		                  );
        
       
        $config []	=   array(
						      'field'   => 'invoice_date', 
						      'label'   => 'Invoice Date', 
						      'rules'   => 'required'
						  );
		 // $config []	=   array(
			// 	             'field'   => 'goods1', 
			// 	             'label'   => 'Goods', 
			// 	             'rules'   => 'required'
			// 	          );
		 // $config []	=   array(
			// 			     'field'   => 'sac1', 
			// 			     'label'   => 'SAC', 
			// 			     'rules'   => 'required'
			// 			  );

   //      $config []	=   array(
			// 			     'field'   => 'amount1', 
			// 			     'label'   => 'Amount', 
			// 			     'rules'   => 'required'
			// 			  );

   //      $config []	=   array(
			// 			     'field'   => 'place_of_delivery', 
			// 			     'label'   => 'Place of delivery', 
			// 			     'rules'   => 'required'
			// 			  );
   //       $config []	=   array(
			// 			     'field'   => 'voyage', 
			// 			     'label'   => 'Voyage', 
			// 			     'rules'   => 'required'
			// 			  );
        //    $config []	=   array(
						  //     'field'   => 'freight_payment', 
						  //     'label'   => 'Freight payment', 
						  //     'rules'   => 'required'
						  // );
 			// $config []	=   array(
				// 		      'field'   => 'place_of_issue', 
				// 		      'label'   => 'Place of issue', 
				// 		      'rules'   => 'required'
				// 		  );
    //         $config []	=   array(
				// 		      'field'   => 'date_of_issue', 
				// 		      'label'   => 'Date of issue', 
				// 		      'rules'   => 'required'
				// 		  );

        //      $config []	=   array(
						  //     'field'   => 'container_no', 
						  //     'label'   => 'Container No', 
						  //     'rules'   => 'required'
						  // );
        return $config;
    }


    public function get_branch()
	{
		$entered_str 	=	$this->input->get("q");
		echo $this->Invoice_model->get_branch($entered_str);
	}

	public function get_company()
	{
		$entered_str 	=	$this->input->get("q");
		echo $this->Invoice_model->get_company($entered_str);
	}

	public function get_consignor(){
		$entered_str 	=	$this->input->get("q");
		echo $this->Invoice_model->get_consignor($entered_str);
	}
	public function get_consignee(){
			$entered_str 	=	$this->input->get("q");
			echo $this->Invoice_model->get_consignee($entered_str);
		}

	public function get_customer(){
			$entered_str 	=	$this->input->get("q");
			echo $this->Invoice_model->get_customer($entered_str);
		}	
	public function get_notify(){
		$entered_str 	=	$this->input->get("q");
		echo $this->Invoice_model->get_notify($entered_str);
	}
	public function get_portname(){
			$entered_str 	=	$this->input->get("q");
			echo $this->Invoice_model->get_portname($entered_str);
		}

	public function insert_branch_bill_no(){
		$branch_bill_no    = $this->input->post("branch_bill_no");

		$data['insert_branch_bill_no']  =  $this->Invoice_model->insert_branch_bill_no($branch_bill_no);
	}

	public function changestatus(){
		$id= $this->input->post('bill_id');
		$data['change_status'] = $this->Invoice_model->changestatus($id);
	}
	public function rejectstatus(){
			$id= $this->input->post('bill_id');
			$data['reject_status'] = $this->Invoice_model->rejectstatus($id);
		}



	public function	get_branch_bill_no(){
		$id=$this->input->post('id');
		echo $this->Invoice_model->get_branch_bill_no($id);

	}

    /*public function pdf_Invoice($bill_id)
    {
        error_reporting(-1);
	    ini_set('max_execution_time', -1);
		$this->load->library('m_pdf');
    	$invoice_id 			  =	$this->uri->segment(3);		
		$data['bill_id']          = $invoice_id;
		
		$data['get_bill_details'] = $this->Invoice_model->get_bill_details($invoice_id);
		$data['goods_details']    = $this->Invoice_model->get_goods_details($invoice_id);
		// echo "<pre>";
		// die(print_r($data['goods_details']));
		$style_dataOne            = file_get_contents(base_url()."assets/css/style.css");
		$style_dataTwo            = file_get_contents(base_url()."assets/css/bootstrap.css");

        //load the view and saved it into $html variable
        $html		 = $this->load->view('invoice/pdf-demo', $data, true);
        $header		 = $this->load->view('invoice/pdf-demo-header', $data, true);
        $footer		 = $this->load->view('invoice/pdf-demo-footer-original', $data, true);
 		$pdfFilePath = "original-pdf.pdf";

  
		$this->m_pdf->pdf->mPDF('utf-8', 'A4');
		$this->m_pdf->pdf->showWatermarkImage = true;
		$this->m_pdf->pdf->pagenumPrefix = '';//'Page number ';
		$this->m_pdf->pdf->pagenumSuffix = '/';
		$this->m_pdf->pdf->nbpgPrefix = '';//' out of ';
		$this->m_pdf->pdf->nbpgSuffix = '';//' pages';

 		$wm = base_url() . 'images/draft.png';
		$this->m_pdf->pdf->WriteHTML($style_dataOne,1);
		$this->m_pdf->pdf->WriteHTML($style_dataTwo,1);
 		$this->m_pdf->pdf->SetHTMLHeader(mb_convert_encoding($header, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'),"E");

		$this->m_pdf->pdf->shrink_tables_to_fit=0;// = true;
		
		$this->m_pdf->pdf->AddPage('', // L - landscape, P - portrait 
								   '', '', '', '',
								   10, // margin_left
								   10, // margin right
								   138, // margin top
								   55, // margin bottom
								   5, // margin header
								   5); 
        $this->m_pdf->pdf->WriteHTML(mb_convert_encoding($html, 'UTF-8', 'UTF-8'),2);
        $this->m_pdf->pdf->Output($pdfFilePath, "D");  

    }*/
public function pdf_Invoice($bill_id)
    {
       // error_reporting(-1);
	    //ini_set('max_execution_time', -1);
		$this->load->library('m_pdf');
    	$invoice_id 			  =	$this->uri->segment(3);		
		$data['bill_id']          = $invoice_id;
		$data['get_bill_details'] = $this->Invoice_model->get_bill_details($invoice_id);
		$data['goods_details']    = $this->Invoice_model->get_goods_details($invoice_id);
		$data['invo_details']     = $this->Invoice_model->get_invo_details($invoice_id);

	//	echo "<pre>";print_r($data["invo_details"]); die(); exit();

		$grand_totals             = $data['get_bill_details']->grand_total;	
	    //exit();
		
	    $amnt_word                = $this->getIndianCurrencyss($grand_totals);		
	 	$data['amnt_word']        = $amnt_word;
		
		$style_dataOne            = file_get_contents(base_url()."assets/css/style.css");
		$style_dataTwo            = file_get_contents(base_url()."assets/css/bootstrap.css");

        //load the view and saved it into $html variable
        $html		 = $this->load->view('invoice/pdf-demo', $data,true);
        $header		 = $this->load->view('invoice/pdf-demo-header', $data,true);
        $footer		 = $this->load->view('invoice/pdf-demo-footer-original', $data,true);
		
 		$pdfFilePath = "original-pdf.pdf";
	


		$this->m_pdf->pdf->mPDF('utf-8', 'A4');
		$this->m_pdf->pdf->showWatermarkImage = true;
		$this->m_pdf->pdf->pagenumPrefix = '';//'Page number ';
		$this->m_pdf->pdf->pagenumSuffix = '/';
		$this->m_pdf->pdf->nbpgPrefix = '';//' out of ';
		$this->m_pdf->pdf->nbpgSuffix = '';//' pages';

 		$wm = base_url() . 'images/draft.png';
		$this->m_pdf->pdf->WriteHTML($style_dataOne,1);
		$this->m_pdf->pdf->WriteHTML($style_dataTwo,1);
 		$this->m_pdf->pdf->SetHTMLHeader(mb_convert_encoding($header, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'),"E");

		$this->m_pdf->pdf->shrink_tables_to_fit=0;// = true;
		
		$this->m_pdf->pdf->AddPage('', // L - landscape, P - portrait 
								   '', '', '', '',
								   10, // margin_left
								   10, // margin right
								   138, // margin top
								   55, // margin bottom
								   5, // margin header
								   5); 
        $this->m_pdf->pdf->WriteHTML(mb_convert_encoding($html, 'UTF-8', 'UTF-8'),2);
        $this->m_pdf->pdf->Output($pdfFilePath, "D"); /* */

    }
	
	
	 public function pdf_Invoice_imp($bill_id)
    {
       // error_reporting(-1);
	    //ini_set('max_execution_time', -1);
		$this->load->library('m_pdf');
    	$invoice_id 			  =	$this->uri->segment(3);		
		$data['bill_id']          = $invoice_id;
		
		$data['get_bill_details'] = $this->Invoice_model->getV2bill_details($invoice_id);
		$data['goods_details']    = $this->Invoice_model->get_goods_details($invoice_id);
		$data['imp_details']      = $this->Invoice_model->get_imp_details($invoice_id);
		$data['invo_details']     = $this->Invoice_model->get_invo_details($invoice_id);

		//echo "<pre>";print_r($data["invo_details"]); die(); exit();
		
		$grand_totals = $data['get_bill_details']->grand_total;
		
		$amnt_word = $this->getIndianCurrencyss($grand_totals);
		$data['amnt_word']      = $amnt_word;
		$style_dataOne            = file_get_contents(base_url()."assets/css/style.css");
		$style_dataTwo            = file_get_contents(base_url()."assets/css/bootstrap.css");

        //load the view and saved it into $html variable
        //$html		 = $this->load->view('invoice/pdf-demo', $data,true);
        $header		 = $this->load->view('invoice/imp_pdf_header', $data,true);
        $footer		 = $this->load->view('invoice/imp_pdf_footer', $data,true);
		
 		$pdfFilePath = "original-pdf.pdf";
	


		$this->m_pdf->pdf->mPDF('utf-8', 'A4');
		$this->m_pdf->pdf->showWatermarkImage = true;
		$this->m_pdf->pdf->pagenumPrefix = '';//'Page number ';
		$this->m_pdf->pdf->pagenumSuffix = '/';
		$this->m_pdf->pdf->nbpgPrefix = '';//' out of ';
		$this->m_pdf->pdf->nbpgSuffix = '';//' pages';

 		$wm = base_url() . 'images/draft.png';
		$this->m_pdf->pdf->WriteHTML($style_dataOne,1);
		$this->m_pdf->pdf->WriteHTML($style_dataTwo,1);
 		$this->m_pdf->pdf->SetHTMLHeader(mb_convert_encoding($header, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'));
		$this->m_pdf->pdf->SetHTMLFooter(mb_convert_encoding($footer, 'UTF-8', 'UTF-8'),"E");

		$this->m_pdf->pdf->shrink_tables_to_fit=0;// = true;
		
		$this->m_pdf->pdf->AddPage('', // L - landscape, P - portrait 
								   '', '', '', '',
								   10, // margin_left
								   10, // margin right
								   138, // margin top
								   55, // margin bottom
								   5, // margin header
								   5); 
        $this->m_pdf->pdf->WriteHTML(mb_convert_encoding($html, 'UTF-8', 'UTF-8'),2);
        $this->m_pdf->pdf->Output($pdfFilePath, "D"); /* */

    }
	
	 function getIndianCurrencyss(float $number)
     {
		
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null;
    $digits_length = strlen($no);
    $i = 0;
    $str = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
        7 => 'seven', 8 => 'eight', 9 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');
    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }
    $Rupees = implode('', array_reverse($str));
    $paise = ($decimal) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
}

	
	
	
	
	
	
public function getIndianCurrency(float $number)
{
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null;
    $digits_length = strlen($no);
    $i = 0;
    $str = array();
    $words = array(0 => '', 01 => 'one', 02 => 'two',
        03 => 'three', 04 => 'four', 05 => 'five', 06 => 'six',
        07 => 'seven', 08 => 'eight', 09 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');
    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? '' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }
    $Rupees = implode('', array_reverse($str));
	//print_r($Rupees);
	//die();
    $paise = ($decimal) ? " and " . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
}

function convertToIndianCurrency($number) {
    $no = round($number);
    $decimal = round($number - ($no = floor($number)), 2) * 100;    
    $digits_length = strlen($no);    
    $i = 0;
    $str = array();
    $words = array(
        0 => '',
        1 => 'One',
        2 => 'Two',
        3 => 'Three',
        4 => 'Four',
        5 => 'Five',
        6 => 'Six',
        7 => 'Seven',
        8 => 'Eight',
        9 => 'Nine',
        10 => 'Ten',
        11 => 'Eleven',
        12 => 'Twelve',
        13 => 'Thirteen',
        14 => 'Fourteen',
        15 => 'Fifteen',
        16 => 'Sixteen',
        17 => 'Seventeen',
        18 => 'Eighteen',
        19 => 'Nineteen',
        20 => 'Twenty',
        30 => 'Thirty',
        40 => 'Forty',
        50 => 'Fifty',
        60 => 'Sixty',
        70 => 'Seventy',
        80 => 'Eighty',
        90 => 'Ninety');
    $digits = array('', 'Hundred', 'Thousand', 'Lakh', 'Crore');
    while ($i < $digits_length) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;            
            $str [] = ($number < 21) ? $words[$number] . ' ' . $digits[$counter] . $plural : $words[floor($number / 10) * 10] . ' ' . $words[$number % 10] . ' ' . $digits[$counter] . $plural;
        } else {
            $str [] = null;
        }  
    }
    
    $Rupees = implode(' ', array_reverse($str));
    $paise = ($decimal) ? " And ". ($words[$decimal - $decimal%10]) ." " .($words[$decimal%10])." Paise "  : '';
    return ($Rupees ?   $Rupees .'Rupees ' : '') . $paise . " Only";
}
	
}