class BatchLineItemsController < ApplicationController
	require "csv"
	skip_before_filter  :verify_authenticity_token 
	before_action :authenticate_member!
 	require 'digest/md5'
 	require 'barby'
	require 'barby/barcode/code_128'
	require 'barby/outputter/ascii_outputter'
	require 'barby/outputter/svg_outputter'


	def index      
        # user_id=current_member.user_id
        @product_category_id=""
        @clients=Client.all.order('id desc')    
        @product_categories=ProductCategory.all.order('id desc')

        find_client=Client.select(:id).order('id desc').last 
        if !find_client.nil?
        	client_id=find_client.id        	 

        	find_batch=Batch.where('client_id=?',client_id).order('id desc').first

        	if !find_batch.nil?
        		@product_category_id=find_batch.product_category_id
        	end
        	sub_query="(select * from batches where client_id="+client_id.to_s+"  and product_category_id ="+@product_category_id.to_s+" )"
			
			@batchLineItems=BatchLineItem.joins('inner join '+sub_query+' as batches on batches.id=batch_line_items.batch_id')
										 .select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)
			@result_count= @batchLineItems.total_count
		else			 
			@batchLineItems=BatchLineItem.joins('inner join  batches on batches.id=batch_line_items.batch_id')
										 .select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)
	    	@result_count= @batchLineItems.total_count
	    end 
	end	

	def export_to_seller
		@product_category_id=""
        @clients=Client.all.order('id desc')    
        @product_categories=ProductCategory.all.order('id desc')
        @sellers=User.where("user_type=?","Seller")

        find_client=Client.select(:id).order('id desc').last 
        if !find_client.nil?
        	client_id=find_client.id        	 

        	find_batch=Batch.where('client_id=?',client_id).order('id desc').first

        	if !find_batch.nil?
        		@product_category_id=find_batch.product_category_id
        	end
        	sub_query="(select * from batches where client_id="+client_id.to_s+"  and product_category_id ="+@product_category_id.to_s+" )"
			
			@batchLineItems=BatchLineItem.joins('inner join '+sub_query+' as batches on batches.id=batch_line_items.batch_id')
										 .select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)
			@result_count= @batchLineItems.total_count
		else			 
			@batchLineItems=BatchLineItem.joins('inner join  batches on batches.id=batch_line_items.batch_id')
										 .select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)
	    	@result_count= @batchLineItems.total_count
	    end 
	end 
	def search  
	    # user_id=current_member.user_id
	     
        batch_list=params[:batch]   
        client_id=params[:client]
        product_category_id=params[:product_category]

        @batchLineItems=nil
         
		if !batch_list.empty?			
   			sub_query="(select * from batches where id in ("+batch_list+") and  client_id="+client_id.to_s+" and product_category_id="+product_category_id.to_s+")"
   			 
			@batchLineItems=BatchLineItem.joins('inner join '+ sub_query +' as batches on batches.id=batch_line_items.batch_id')
										 .select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)									  
			@result_count= @batchLineItems.total_count
		else
			sub_query="(select * from batches where   client_id="+client_id.to_s+" and product_category_id="+product_category_id.to_s+")"
			@batchLineItems=BatchLineItem.joins('inner join '+ sub_query +'as batches on batches.id=batch_line_items.batch_id')
										.select('batch_line_items.*,batches.order_ref as batch_name').order('batch_line_items.id desc').page(params[:page]).per(10)									  
			@result_count= @batchLineItems.total_count
		end  
      
		# if @batchLineItems.nil?
		# 	@message="No search found!"
		# end           
	end
	def get_batch
		client_id=params[:client_id]
		product_category_id=params[:product_category_id]

	    batches=Batch.where('client_id=? and product_category_id=?',client_id,product_category_id)
	    			 .select('order_ref,id')	 
		if !batches.nil?
			render :json => { :data => batches,:status => true }
			# respond_with(data: batches,status: true)	
		# else
			# respond_with(data: nil,status: false)
		end
	end
	def export	
		batch_list=""
		@batchLineItems=nil	
		user_id=current_member.user_id

		@clients=Client.all
		@batches=Batch.where('user_id=?',user_id)	
		client_id=params[:client]
		product_category_id=params[:product_category]
		find_client=Client.find_by_id(client_id)	
		location_code=find_client.location_code
		client_name=find_client.name.downcase
		find_product=ProductCategory.find_by_id(product_category_id)
		product_name=find_product.name.downcase

		find_user=User.find_by_id(user_id)
		if !find_user.nil?
			exported_by=find_user.name
		end
		if params[:batch].present?
			batch_list=params[:batch]
		end		
			 
		if !batch_list.empty?
			res=Batch.where("client_id=? and product_category_id=? and id in (?)",client_id,product_category_id,batch_list).update_all("export_count = export_count + 1,exported_by='"+exported_by+"'")
			
			 
			sub_query= "(select * from batches where   client_id="+client_id.to_s+" and product_category_id="+ product_category_id.to_s+")"
			
			@batchLineItems = BatchLineItem.joins('inner join '+sub_query +" as batches on batches.id=batch_line_items.batch_id")
										    .joins('inner join product_categories product on product.id=batches.product_category_id')
											.where('batch_id in (?)',batch_list)
											.select("*,product.product_type_id ,product.name,'' as secret_token,'' as location_name")		
  		else
  			Batch.where("client_id=? ",client_id).update_all("export_count = export_count + 1,exported_by='"+exported_by+"'")
  			sub_query="(select * from batches where client_id ="+client_id+" and product_category_id="+ product_category_id+")"
  			@batchLineItems = BatchLineItem.joins('inner join '+sub_query+' as batches on batches.id=batch_line_items.batch_id')
  											.joins('inner join product_categories as product on product.id=batches.product_category_id')
  											.select("*,product.product_type_id ,product.name,'' as secret_token,'' as location_name")
		end	

		datestr= Time.now.strftime("%Y/%m/%d %H:%M:%S")
		filename=client_name.to_s+"_"+product_name.to_s+"_"+datestr
		respond_to do |format|	 
			format.html	
			format.csv { send_data @batchLineItems.to_csv(client_id,location_code), filename: "#{filename}.csv" }
	    end
	end	


	def export_seller
		batch_list=""
		@batchLineItems=nil	
		user_id=current_member.user_id

		@clients=Client.all
		@batches=Batch.where('user_id=?',user_id)	
		client_id=params[:client]
		product_category_id=params[:product_category]
		seller_id = params[:seller]
		find_client=Client.find_by_id(client_id)	
		location_code=find_client.location_code
		client_name=find_client.name.downcase
		find_product=ProductCategory.find_by_id(product_category_id)
		product_name=find_product.name.downcase

		find_user=User.find_by_id(user_id)
		if !find_user.nil?
			exported_by=find_user.name
		end
		if params[:batch].present?
			batch_list=params[:batch]
		end		
		today_date = Time.now.to_s
		if !batch_list.empty?
			res=Batch.where("client_id=? and product_category_id=? and id in (?)",client_id,product_category_id,batch_list).update_all("export_count = export_count + 1,exported_by='"+exported_by+"',export_to_seller_id='"+seller_id+"',export_to_seller_date='"+today_date+"'")
			
			 
			sub_query= "(select * from batches where   client_id="+client_id.to_s+" and product_category_id="+ product_category_id.to_s+")"
			
			@batchLineItems = BatchLineItem.joins('inner join '+sub_query +" as batches on batches.id=batch_line_items.batch_id")
										    .joins('inner join product_categories product on product.id=batches.product_category_id')
											.where('batch_id in (?)',batch_list)
											.select("*,product.product_type_id ,product.name,'' as secret_token,'' as location_name")		
  		else
  			# Batch.where("client_id=? ",client_id).update_all("export_count = export_count + 1,exported_by='"+exported_by+"',export_to_seller_id='"+seller_id+"',export_to_seller_date='"+today_date+"'")
  			Batch.where("client_id=? ",client_id).update_all("export_count = export_count + 1,exported_by='"+exported_by+"',export_to_seller_id='"+seller_id+"',export_to_seller_date='"+today_date+"'")
  			sub_query="(select * from batches where client_id ="+client_id+" and product_category_id="+ product_category_id+")"
  			@batchLineItems = BatchLineItem.joins('inner join '+sub_query+' as batches on batches.id=batch_line_items.batch_id')
  											.joins('inner join product_categories as product on product.id=batches.product_category_id')
  											.select("*,product.product_type_id ,product.name,'' as secret_token,'' as location_name")
		end	

		datestr= Time.now.strftime("%Y/%m/%d %H:%M:%S")
		filename=client_name.to_s+"_"+product_name.to_s+"_"+datestr
		respond_to do |format|	 
			format.html	
			format.csv { send_data @batchLineItems.to_csv_seller(client_id,location_code), filename: "#{filename}.csv" }
	    end
	end	

	def generate_cards
	end

	def generate_card_account_items
		# Generate Code
		batch_id=params[:id]     
        client_id=""
        qty = params[:qty]   
        total_count=0   
        check = params[:barcode]

       

        # check_member= Member.authenticate_session_token(session_token)
        # if !check_member.nil?         
            encrypt_key=""
            asset_identity=""

            find_batch = Batch.find_by_id(batch_id)
            if !find_batch.nil?
                card_type=find_batch.adult_or_child.upcase   
                product_category_id=find_batch.product_category_id
                find_product_category=ProductCategory.find_by_id(product_category_id) 

                if !find_product_category.nil? 
                    product_type=find_product_category.product_type_id

                    find_user=Client.find_by_id(find_batch.client_id)
                    if !find_user.nil?
                        encrypt_key=find_user.secrect_key    
                        location_code=find_user.location_code                               
                    
                        client_id=find_user.id
                        if !encrypt_key.nil?  
                        	# Generate with qty
                        	qty.to_i.times do |i|
		                            serial_no=BatchLineItem.generate_serial_no(client_id.to_s)

		                            asset_identity=BatchLineItem.generate_account_no(location_code)
		                            security_code=BatchLineItem.generate_security_code
		                            out=BatchLineItem.create_product(asset_identity,serial_no,batch_id,"","",security_code)                                
		                            if check.present?
		                            	barcode = BatchLineItem.generate_barcode
		                            	update_barcode = BatchLineItem.find_by_asset_identity(out[2])
		                            	update_barcode.barcode = barcode
		                            	# barcode_128 = Barby::Code128.new(barcode)
		                            	# update_barcode.barcode_format = barcode_128
		                            	update_barcode.save
		                            end
		                            total_count+=1
							end
							  respond_to do |format|
							    format.html { redirect_to batch_url(batch_id), notice: 'Successfully generated.' }
							    format.json { head :no_content }
   							  end
                            # Generate with qty 

                        else
                            @out=false,'Invalid User!'     
                        end
                    else
                        @out=false,"Client doesn't exist!"  
                    end
                else
                    @out=false,"Product Category doesn't exist!"
                end
            else
                @out=false,"Batch doesn't exist!"
            end
        # else
        #     @out=false,'Sorry!Unauthorized user!'
        # end
		# Generate Code
	end

	
end