class Origami::OtherChargesController < BaseOrigamiController
	authorize_resource :class => false

	def index
		@webview = false
	    if check_mobile
	      @webview = true  
	    end
	    
		sale_id = params[:sale_id]
		@cashier_type = params[:type]
	    if Sale.exists?(sale_id)
	      @sale_data = Sale.find(sale_id)
	      if @sale_data.bookings[0].dining_facility_id.to_i > 0
	      	@table =  DiningFacility.find(@sale_data.bookings[0].dining_facility_id)
	      else
	      	@table = nil
	      end	      
	    end
	end

	def create		
		sale_id = params[:sale_id]
	    other_charges_items = JSON.parse(params[:other_charges_items])
	    sub_total = params[:sub_total]
	    cashier_type = params[:cashier_type]

	    if Sale.exists?(sale_id)
	      sale = Sale.find(sale_id)
	      if sale.bookings[0].dining_facility_id.to_i > 0
	      	table_id = sale.bookings[0].dining_facility_id
	        table = DiningFacility.find(table_id)
		  else
		  	  table_id = nil
		      table = nil
	      end
	      

	      # sale.total_amount = sub_total.to_f
	      # sale.grand_total = sub_total.to_f + sale.total_tax;  
	      # sale.save   
	      if other_charges_items.length > 0
	        #save sale item for discount
	        other_charges_items.each do |di|
	          # origin_sale_item = SaleItem.find(di["id"])
	          sale_item = SaleItem.new

	          sale_item.sale_id = sale_id
	          sale_item.product_code = "Other Charges"
	          sale_item.product_name = "*" + di["name"]
	          sale_item.product_alt_name = ""
	          sale_item.status = "Other Charges"

	          sale_item.qty = 1
	          sale_item.unit_price = di["price"]
	          sale_item.taxable_price = di["price"] * 1
	          sale_item.is_taxable = di["is_taxable"]
	          sale_item.account_id = 0

	          sale_item.price = di["price"] * 1
	          sale_item.save

	          action_by = current_user.id
	          if table.nil?
	          	remark = "Add Other Charges - Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} |Charges ->#{di["price"]} For ->#{di["name"]}- Table ->"
	          else
	          	remark = "Add Other Charges - Receipt No #{sale.receipt_no} | Sale ID #{sale.sale_id} |Charges ->#{di["price"]} For ->#{di["name"]}- Table ->#{table.name}"
	          end
		      
		      sale_audit = SaleAudit.record_audit_for_edit(sale.sale_id,sale.cashier_id, action_by,remark,"ADDOTHERCHARGES" )

	        end                 
	      end 

	      # Re-calc All Amount in Sale
	      sale.compute_by_sale_items(sale_id, sale.sale_items, sale.total_discount, nil, cashier_type)	      
	    end	     
	    if !table.nil?
	    	dining = {:table_id => table_id, :table_type => table.type }
	    render :json => dining.to_json
		end	    
	end	
end