class Reports::ReceiptNoController < BaseReportController
authorize_resource :class => false
	def index
		@payments = [["All Payment",''], ["Cash Payment","cash"], ["Credit Payment","creditnote"], ["FOC Payment","foc"]]
		@payment_method =  PaymentMethodSetting.all
		from, to = get_date_range_from_params
		customer_filter = params[:customer]

		@shift_sale_range = ''

    @shift = ''
    if params[:shift_name].to_i != 0

      @shift_sale_range = Sale.get_by_shift_sale_by_item(from,to,Sale::SALE_STATUS_COMPLETED)

      @shift_sale = ShiftSale.find(params[:shift_name])
      if to.blank?
        @shift = ShiftSale.where('shift_started_at = ? and shift_closed_at is NULL ',@shift_sale.shift_started_at)
      else
        if @shift_sale.shift_closed_at.blank?
          @shift = ShiftSale.where('shift_started_at = ? and shift_closed_at is NULL',@shift_sale.shift_started_at)
        else
          @shift = ShiftSale.where('shift_started_at = ? and shift_closed_at = ? ',@shift_sale.shift_started_at, @shift_sale.shift_closed_at)
        end
      end
    end

		@lookup = Lookup.find_by_lookup_type('reprint_receipt')
		if @lookup.nil?
			@lookup = Lookup.create_reprint_receipt_lookup
		end

    payment_type = params[:payment_type]
      @sale_data = Sale.get_shift_sales_by_receipt_no(@shift_sale_range, @shift, from, to, payment_type, customer_filter)
      @sale_taxes = Sale.get_separate_tax_by_customer(@shift_sale_range, @shift, from, to, payment_type, customer_filter)
      @tax_profiles = TaxProfile.group('name').order('order_by asc') #.limit(2)

      @from       = from
      @to         = to
      # get printer info
      @print_settings = PrintSetting.get_precision_delimiter()
      if @shift.present?
      @shift.each do |sh|
        @shift_from = sh.shift_started_at.nil? ? '-' : sh.shift_started_at.strftime("%e %b %I:%M%p")
        @shift_to = sh.shift_closed_at.nil? ? '-' : sh.shift_closed_at.strftime("%e %b %I:%M%p")
        @shift_data = sh
      end
    end

		respond_to do |format|
      format.html
      format.xls
    end
	end

	def show
		from, to  = get_date_range_from_params

    @sale_data = Sale.get_by_shift_sale_by_item(from,to,Sale::SALE_STATUS_COMPLETED)

		date_arr = Array.new
		@sale_data.each do |sale|
			local_opening_date = sale.opening_date.nil? ? '-' : sale.opening_date.strftime("%e %b %I:%M%p")
			local_closing_date = sale.closing_date.nil? ? '-' : sale.closing_date.strftime("%e %b %I:%M%p")
			opening_date = sale.opening_date.nil? ? '-' : sale.opening_date.utc
			closing_date = sale.closing_date.nil? ? '-' : sale.closing_date.utc
			shift_id = sale.id.nil? ? '-' : sale.id
			str = {:shift_id => shift_id, :local_opening_date => local_opening_date, :local_closing_date => local_closing_date, :opening_date => opening_date, :closing_date => closing_date}
			date_arr.push(str)
		end

    out = {:status => 'ok', :message => date_arr}

    respond_to do |format|
      format.json { render json: out }
    end
	end

	def sync_data

	  @orders, @order_items, @sales, @sale_items, @sale_taxes, @sale_payments, @sale_orders, @sale_audits, @bookings, @assigned_order_items, @shift_sales = Booking.get_sync_data(params[:sale_id])

		# Here comes to call the sync api
		# url	= "http://192.168.1.176:3000/en/api/sync_data"
	  url = Lookup.sync_url
	  token = Lookup.get_sync_token
	  @message = ''
		# token = Lookup.token

	  unless url.nil? and token.nil?
	  	begin
      		@result = HTTParty.post(url.to_str,
                :body => { :orders =>  @orders,
                		   :order_items => @order_items,
                		   :sale_orders => @sale_orders,
                		   :sales => @sales,
                		   :sale_items => @sale_items,
                		   :sale_audits => @sale_audits,
                		   :sale_payments => @sale_payments,
                		   :sale_taxes => @sale_taxes,
                		   :bookings => @bookings,
                		   :assigned_order_items => @assigned_order_items,
                		   :shift_sales => @shift_sales
                         }.to_json,
                :headers => {
                        'Content-Type' => 'application/json',
                        'Authorization' => "Bearer #{token}"
                }, :timeout => 10,
                :verify_ssl => OpenSSL::SSL::VERIFY_NONE,
                :verify => false )

		rescue HTTParty::Error
        	response = { status: false, message: "Can't open membership server "}
      	rescue Net::OpenTimeout
        	response = { status: false, message: "Can't open membership server "}
      	rescue OpenURI::HTTPError
        	response = { status: false, message: "Can't open membership server "}
      	rescue SocketError
        	response = { status: false, message: "Can't open  server "}
      	rescue Errno::EHOSTDOWN
        	response = { status: false, message: "Can't open  server "}
      	rescue Errno::ECONNREFUSED, Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError
        	response = { status: false, message: "Can't open membership server"}
      	end
      	@message = @result.parsed_response['message']
	  end

	  respond_to do |format|
		format.html { redirect_to '/en/reports/receipt_no/', notice: @message}
	  end
	end

	def reprint
    sale_id = params[:sale_id]
    member_info = nil
    latest_order_no = nil
    saleObj = Sale.find(sale_id)

    # For Cashier by Zone
    bookings = Booking.where("sale_id='#{sale_id}'")

    booking = Booking.find_by_sale_id(sale_id)
    latest_order = booking.booking_orders.joins(" JOIN orders ON orders.order_id = booking_orders.order_id").where("orders.source = 'quick_service'").order("order_id DESC").limit(1).first()
    if !latest_order.nil?
      latest_order_no = latest_order.order_id
    end
    # if bookings.count > 1
    #   # for Multiple Booking
    #   table = DiningFacility.find(bookings[0].dining_facility_id)
    # else
    #   table = DiningFacility.find(bookings[0].dining_facility_id)
    # end
    shift = ShiftSale.current_open_shift(current_user)
    if !shift.nil?
      cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id)
    else
      if bookings[0].dining_facility_id.to_i > 0
        table = DiningFacility.find(bookings[0].dining_facility_id)
        cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
        cashier_terminal = CashierTerminal.find(cashier_zone.cashier_terminal_id)
      else
          shift = ShiftSale.find(saleObj.shift_sale_id)
          cashier_terminal = CashierTerminal.find(shift.cashier_terminal_id)
      end
    end

    # if ENV["SERVER_MODE"] != "cloud" #no print in cloud server
      receipt_bill_a5_pdf = Lookup.collection_of("print_settings") #print_settings with name:ReceiptBillA5Pdf
      unique_code = "ReceiptBillPdf"
      if !receipt_bill_a5_pdf.empty?
        receipt_bill_a5_pdf.each do |receipt_bilA5|
          if receipt_bilA5[0] == 'ReceiptBillA5Pdf'
            if receipt_bilA5[1] == '1'
              unique_code = "ReceiptBillA5Pdf"
            else
              unique_code = "ReceiptBillPdf"
            end
          end
        end
      end
      customer= Customer.find(saleObj.customer_id)

      #shop detail
      #shop_detail =  @shop
      # get member information
      rebate = MembershipSetting.find_by_rebate(1)
      if customer.membership_id != nil && rebate
        member_info = Customer.get_member_account(customer)
        rebate_amount  = Customer.get_membership_transactions(customer,saleObj.receipt_no)
        current_balance = SaleAudit.paymal_search(sale_id)
      end

      #for card sale data
      card_data = Array.new
      card_sale_trans_ref_no = Sale.getCardSaleTrans(sale_id)
      if !card_sale_trans_ref_no.nil?
        card_sale_trans_ref_no.each do |cash_sale_trans|
          card_res_date = cash_sale_trans.res_date.strftime("%Y-%m-%d").to_s
          card_res_time = cash_sale_trans.res_time.strftime("%H:%M").to_s
          card_no = cash_sale_trans.pan.last(4)
          card_no = card_no.rjust(19,"**** **** **** ")
          card_data.push({'res_date' => card_res_date, 'res_time' => card_res_time, 'batch_no' => cash_sale_trans.batch_no, 'trace' => cash_sale_trans.trace, 'pan' => card_no, 'app' => cash_sale_trans.app, 'tid' => cash_sale_trans.terminal_id, 'app_code' => cash_sale_trans.app_code, 'ref_no' => cash_sale_trans.ref_no, 'mid' => cash_sale_trans.merchant_id})
        end
      end

      #card_balance amount for Paymal payment
      card_balance_amount,transaction_ref = SaleAudit.getCardBalanceAmount(sale_id)

      # get printer info
      print_settings=PrintSetting.find_by_unique_code(unique_code)

      # Calculate price_by_accounts
      item_price_by_accounts = SaleItem.calculate_price_by_accounts(saleObj.sale_items)
      discount_price_by_accounts = SaleItem.get_discount_price_by_accounts(saleObj.sale_items)
      other_amount = SaleItem.calculate_other_charges(saleObj.sale_items)

      printer = Printer::ReceiptPrinter.new(print_settings)

      filename, receipt_no, cashier_printer = printer.print_receipt_bill(print_settings, false, nil, cashier_terminal,saleObj.sale_items,saleObj,customer.name, item_price_by_accounts, discount_price_by_accounts, member_info,rebate_amount,current_shop, "Re-print",current_balance,card_data,other_amount,latest_order_no,card_balance_amount,nil,transaction_ref)

      result = {
        :status => true,
        :filepath => filename,
        :printer_model => print_settings.brand_name,
        :printer_url => print_settings.api_settings
      }

      # Mobile Print
      # render :json => result.to_json
			respond_to do |format|
				format.html { redirect_to '/en/reports/receipt_no/', notice: "Printing Completed."}
				format.json { render json: result }
		  end
    # end
  end

end
