class Api::BillController < Api::ApiController

  #Create invoice based on booking
  #Output and invoice

  def create
    @status = false
    @error_message = "Order ID or Booking ID is require to request for a bill."
    # if shift_by_terminal = ShiftSale.current_open_shift(get_cashier[0])
    if !ShiftSale.current_shift.nil?
    #create Bill by Booking ID
      table = 0
      if params[:booking_id].present?
        booking  = Booking.find(params[:booking_id])
        if booking.booking_orders.count > 0
          if booking.checkin_at > Time.current && booking.checkout_at.nil?
            @status = false
            @error_message = "Operation failed, Could not request bill!"
          else
            order = booking.orders.first

            unless shift = ShiftSale.current_open_shift(current_login_employee)
              # for Multiple Cashier by Zone
              if booking.dining_facility_id
                table = DiningFacility.find(booking.dining_facility_id)
                cashier_zone = CashierTerminalByZone.find_by_zone_id(table.zone_id)
                shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null and cashier_terminal_id = #{cashier_zone.cashier_terminal_id}").first
              else
                shift = ShiftSale.current_shift
              end
            end

            #for multiple zone with terminal
            if !shift.nil?
              cashier = Employee.find(shift.employee_id)
            else
             multiple_zone = CashierTerminalByZone.where("zone_id = #{table.zone_id}")
              multiple_zone.each do |zone|
                shift = ShiftSale.where("shift_started_at is not null and shift_closed_at is null and cashier_terminal_id = #{zone.cashier_terminal_id}").first
                if !shift.nil? then
                  cashier = Employee.find(shift.employee_id)
                  break
                end
              end
            end

            if @sale_data = booking.sale
              @status = true
            elsif @sale_data = Sale.generate_invoice_from_booking(booking, current_login_employee, cashier, order.source, params[:current_checkin_induties_count])
              @status = true
            else
              @status = false
            end
          end
        else
          @status = false
          @error_message = "There is no order for '#{params[:booking_id]}'"
        end
      end

      # Bind shift sale id to sale
      # @sale_data.shift_sale_id = shift_by_terminal.id
      # @sale_data.save
      if @sale_data && booking.dining_facility_id.present?
        #check checkInOut pdf print
        checkout_time = Lookup.collection_of('checkout_time')

        if (!checkout_time.empty?) && (ENV["SERVER_MODE"] != "cloud") #no print in cloud server
          terminal = DiningFacility.find_by_id(booking.dining_facility_id)
          cashier_terminal = CashierTerminal.find_by_id(terminal.zone_id)

          unique_code = "CheckInOutPdf"
          printer = PrintSetting.find_by_unique_code(unique_code)

          if !printer.nil?
            # print when complete click
            order_queue_printer = Printer::OrderQueuePrinter.new(printer)

            order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, table)
          end
        end

        Promotion.promo_activate(@sale_data)

        #BillBroadcastJob.perform_later(table)
        if ENV["SERVER_MODE"] == 'cloud'
          from = request.subdomain  + "." + request.domain
        else
          from = ""
        end
        ActionCable.server.broadcast "bill_channel",table: table, from: from
      end
    else
      @status = false
      @error_message = "No Current Open Shift"
    end

    #@sale_data = Sale.find_by_sale_id(@sale_id)
    #@sale_items = SaleItem.where("sale_id=?",@sale_id)

# Not Use for these printed bill cannot give customer
    # @sale_data = Sale.find_by_sale_id(@sale_id)
    # @sale_items = SaleItem.where("sale_id=?",@sale_id)

    # unique_code = "ReceiptBillPdf"
    # #shop detail
    # shop_details = @shop

    # customer= Customer.find(@sale_data.customer_id)
    # # get member information
    # member_info = Customer.get_member_account(customer)


    # # 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(@sale_items)

    #customer= Customer.find(@sale_data.customer_id)
    # get member information
    #member_info = Customer.get_member_account(customer)

    # printer = Printer::ReceiptPrinter.new(print_settings)
    # printer.print_receipt_bill(print_settings, false, nil,@sale_items,@sale_data,customer.name, item_price_by_accounts, member_info, shop_details)
  end

  def request_bill
    if params[:order_items]
      is_extra_time = false
      extra_time = ''

      # params[:order_items].each { |i|
      #   i["item_instance_code"] = i["item_instance_code"].downcase.to_s
      #   if i["item_instance_code"].include? "ext"
      #     is_extra_time = true
      #     arr_exts = i["item_instance_code"].split("_")
      #     if arr_exts[1].match(/^(\d)+$/)
      #       time = arr_exts[1].to_i*60*i["quantity"].to_i
      #       extra_time = Time.at(time)
      #     end
      #   end
      # }

      @order = Order.new
      @order.source = "cashier"
      @order.order_type = "Takeaway"
      @order.customer_id = takeaway.customer_id # for no customer id from mobile
      @order.items = params[:order_items]
      @order.guest = params[:guest_info]
      @order.table_id = params[:table_id]  # this is dining facilities's id
      @order.new_booking = true
      @order.waiters = current_login_employee.name
      @order.employee_name = current_login_employee.name

      @order.is_extra_time = is_extra_time
      @order.extra_time    = extra_time

      @status, @booking = @order.generate

      if @status && @booking
        shift = ShiftSale.current_open_shift(current_login_employee)
        if !shift.nil?
          cashier = Employee.find(shift.employee_id)
          if (@booking.booking_id)
            order = @booking.orders.first

            if @sale_data = @booking.sale
              @status = true
            elsif @sale_data = Sale.generate_invoice_from_booking(@booking, current_login_employee, cashier, order.source, params[:current_checkin_induties_count])
              @status = true
            else
              @status = false
            end
          end
          # Promotion.promo_activate(@sale)
          # @status = true
          # render json: JSON.generate({:status => true, :sale_id => @sale_id, :sale_data => @sale_data.to_json })
        else
          @status = false
          @error_message = "No Current Open Shift!"
          # render json: JSON.generate({:status => false, :error_message => "No Current Open Shift!"})
        end
      else
        @status = false
        @error_message = "Create order failed, some error occurred!"
        # render json: JSON.generate({:status => false, :error_message => "Create order failed, some error occurred!"})
      end
    else
      @status = false
      @error_message = "Parameters missing!"
      # render json: JSON.generate({:status => false, :error_message => "Parameters missing!"})
    end
  end

  private
  def bill_params
    params.permit(:booking_id, :order_id)
  end
end
