class Foodcourt::OrdersController < BaseFoodcourtController
  def show
    @webview = false
    if check_mobile
      @webview = true
    end

    @tables   = Table.unscoped.all.active.order('status desc')
    @rooms    = Room.unscoped.all.active.order('status desc')
    @complete = Sale.where("DATE_FORMAT(CONVERT_TZ(created_at, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') = ? and sale_status != 'new'",Time.not.utc.strftime('%Y-%m-%d'))
    @orders   = Order.includes("sale_orders").where("DATE_FORMAT(CONVERT_TZ(created_at, '+00:00', '<%= Time.zone.formatted_offset %>'), '%Y-%m-%d') = ? and status != 'billed' and source != 'quick_service'",Time.current.strftime('%Y-%m-%d')).order('date desc')
    @order = Order.find(params[:order_id])
    booking = Booking.select('bookings.booking_id, bookings.dining_facility_id')
              .joins(" JOIN booking_orders as bo on bo.booking_id = bookings.booking_id")
              .where("bo.order_id='#{params[:order_id]}'").first()

    @booking = Array.new
    if !booking.nil?
      if booking.dining_facility_id.to_i > 0
        dining_facilities = DiningFacility.find_by_id(booking.dining_facility_id)
        @booking.push({'booking_id' => booking.booking_id, 'dining_facility_id' => booking.dining_facility_id, 'type' => dining_facilities.type})
      else
        @booking.push({'booking_id' => booking.booking_id, 'dining_facility_id' => booking.dining_facility_id, 'type' => nil})
      end

    end
    @customers = Customer.pluck("customer_id, name")
    #for split bill
    lookup_spit_bill = Lookup.collection_of('split_bill')
    @split_bill = 0
    if !lookup_spit_bill[0].nil?
      @split_bill = lookup_spit_bill[0][1]
    end

    sale_order = SaleOrder.find_by_order_id(@order.order_id)
    if sale_order
      unless sale_order.sale_id.nil?
        sale = Sale.find(sale_order.sale_id)
        @sale_status = sale.sale_status
      end
    end

    @order.order_items.each_with_index do |item, order_item_index|
      if !item.set_menu_items.nil?
        instance_item_sets = JSON.parse(item.set_menu_items)
        arr_instance_item_sets = Array.new
        instance_item_sets.each do |instance_item|
          item_instance_name = MenuItemInstance.find_by_item_instance_code(instance_item["item_instance_code"]).item_instance_name
          arr_instance_item_sets.push(item_instance_name)
          item.price = item.price.to_f + instance_item["price"].to_f
        end
        @order.order_items[order_item_index].set_menu_items = arr_instance_item_sets
      end
    end
  end
  def app_orders
    if params[:booking_id].present?
      @booking = Booking.select("orders.*,bookings.*,customers.*")
               .joins("JOIN booking_orders ON booking_orders.booking_id=bookings.booking_id")
               .joins("JOIN orders ON orders.order_id=booking_orders.order_id")
               .joins("JOIN customers ON orders.customer_id=customers.customer_id")
               .where("orders.source='app' and bookings.booking_id='#{params[:booking_id]}'").first
      @customer_id =@booking.customer_id
      @booking_id =@booking.booking_id
      @order_id =@booking.order_id
      @sale_data = Sale.find_by_sale_id(@booking.sale_id)
    elsif params[:pending_id]
      id = params[:pending_id]
      if id.include? "SAL"
        @pending = Sale.includes(:sale_items).find_by(sale_id: id)
        @status = "sale"
      elsif id.include? "BKI"
        @pending = Booking.includes(:order_items).find_by(booking_id: id)
        @status = "order"
      end
    end
    @current_shift = current_user.current_shift || ShiftSale.current_shift
    sale_status = ['completed', 'void']

    @pending_sales = Sale.where('shift_sale_id = ? AND sale_status NOT IN (?)', @current_shift.id, sale_status)
    @pending_completed = Sale.where('shift_sale_id = ? AND sale_status IN (?)', @current_shift.id, sale_status)
    @pending_orders = Sale.pending_order('food_court')

    @completed, @bookings = Sale.get_foodcourt_current_shift_orders
  end

  def current_shift_order_count
    @current_shift =  current_user.current_shift || ShiftSale.current_shift
    status = ['completed', 'void']
    @pending_sales = Sale.where('shift_sale_id = ? AND sale_status NOT IN (?)', @current_shift.id, status)
    @pending_orders = Sale.pending_order('food_court')
    @occupied_table = @pending_sales.length + @pending_orders.length
    render json: @occupied_table
  end

  def modify_order
    @zone     = Zone.all
    @tables   = Table.active.order('status desc')
    @rooms    = Room.active.order('status desc')

    @cashier_type = "food_court"
    today = Time.current
    day = Date.today.wday

    @menus    = []
    @menu     = []

    @zone     = Zone.all
    @tables   = Table.active.order('status desc')
    @rooms    = Room.active.order('status desc')

    if params[:id].include? "BKI"
      @table_id = nil
      @table = nil
      @booking = Booking.find(params[:id])
    else
      @table_id = params[:id]
      @table = DiningFacility.find(@table_id)
      @booking = @table.get_booking
    end

    # byebug
    @sale_id = @booking.sale_id

    if @booking
      @booking_id = @booking.booking_id
      @obj_order = @booking.orders.first
      @order_id = @obj_order.order_id
      @customer = @obj_order.customer
      @date = @obj_order.created_at
      @order_items = @booking.order_items
    end

    render "foodcourt/addorders/detail"
  end

  def update_modify_order
    booking = Booking.find(params[:booking_id])
    sale = booking.sale
    if sale && sale.sale_status != 'new'
      render :json => { :status => false }
    end

    is_extra_time = false
    extra_time = ''
    cashier_type = "quick_service"

    items_arr = []
    JSON.parse(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
       if i["parent_order_item_id"]
         items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"parent_order_item_id": i["parent_order_item_id"],"options": i["options"]}
       else
        items = {"order_item_id": i["order_item_id"],"item_instance_code": i["item_instance_code"],"quantity": i["quantity"],"options": i["options"]}
       end
       items_arr.push(items)
     }

    # begin
    Order.transaction do
      order = Order.new
      order.source = params[:order_source]
      order.order_type = params[:order_type]
      # order.customer_id = params[:customer_id].present? ? params[:customer_id] : walkin.customer_id # for no customer id from mobile
      order.items = items_arr
      order.guest = params[:guest_info]
      order.table_id = params[:table_id]  # this is dining facilities's id
      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

      order.new_booking = false
      order.booking_id = booking.booking_id

      if order.generate
        if sale
          Sale.add_to_existing_pending_invoice(nil, sale.sale_id, booking)
          render :json => { :status => true, :data => sale }
        else
          render :json => { :status => true, :data => 'OK' }
        end
      else
        render :json => { :status => false }
      end
    end
  end

  def request_bill
    sale_data =[]
    customer_id = params[:customer_id]
    if !ShiftSale.current_shift.nil?
      order_id = params[:order_id]
      order = Order.find(order_id)
      booking = order.booking
      if Customer.exists?(customer_id: customer_id)
        booking.orders.update_all(customer_id: customer_id)
      end
      if booking.checkin_at.utc > Time.now.utc && booking.checkout_at.nil?
        @status = false
        @error_message = "Operation failed, Could not request bill!"
      else
        table = DiningFacility.find_by(id: booking.dining_facility_id)

        if booking.sale_id.nil?
          if sale_data = Sale.generate_invoice_from_booking(booking, current_login_employee, current_user, order.source, params[:current_checkin_induties_count])
            # in-duty update
            in_duties = InDuty.where("booking_id=?", booking.id)
            if !in_duties.empty?
              in_duties.each do |in_duty|
                induty = InDuty.find(in_duty.id)
                induty.sale_id = sale_data.sale_id
                induty.out_time = Time.now
                induty.save
              end
            end

            action_by = current_user.name
            type = "REQUEST_BILL"

            remark = "Request bill Receipt No #{sale_data.receipt_no}"
            sale_audit = SaleAudit.record_audit_sale(sale_data.sale_id,remark,action_by,type )

            # Promotion Activation
            Promotion.promo_activate(sale_data)

            #bill channel
            if ENV["SERVER_MODE"] == 'cloud'
              from = request.host
            else
              from = ""
            end

            if ["quick_service", "cashier"].include? order.source
              ActionCable.server.broadcast "bill_channel", table: table, from: from
            end

            unless ["quick_service", "food_court"].include? order.source
              #check checkInOut pdf print
              checkout_time = Lookup.collection_of('checkout_time')
              if !booking.dining_facility_id.nil?
                terminal = DiningFacility.find_by_id(booking.dining_facility_id)
                cashier_terminal = CashierTerminal.find_by_id(terminal.zone_id)

                if (!checkout_time.empty?) && (ENV["SERVER_MODE"] != "cloud") #no print in cloud server
                  unique_code = "CheckInOutPdf"
                  printer = PrintSetting.find_by_unique_code(unique_code)

                  # print when complete click
                  order_queue_printer = Printer::OrderQueuePrinter.new(printer)

                  if !printer.nil?
                    order_queue_printer.print_check_in_out(printer, cashier_terminal, booking, table)
                  end
                end
              end
            end
            @status = true
            sale_id = sale_data.sale_id
          else
            @status = false
            sale_id = nil
          end
        else
          @status = true
          sale_id = booking.sale_id
        end
      end

      respond_to do |format|
        format.json { render :json => { :status => @status, :sale_id => sale_id } }
      end
    else
      respond_to do |format|
        format.json {
          render :json => { :status => false, :error_message => "No Current Open Shift for This Employee" } }
      end
    end
    #
  end

  def completed
    customer =Customer.find_by_customer_id(params[:customer_id])
    phone_number =customer.contact_no
    if Order.send_message(phone_number,params[:order_id],current_shop.name)
      booking =Booking.find(params[:booking_id])
      booking.booking_status ='completed'
      booking.save!
    end
  end

  def cancel_order
    order_id = params[:order_id]

    if order_id.present?
      order   = Order.find(order_id)
      booking = order.booking
      if order && booking
        if order.order_items.present?
          order.order_items.update_all(order_item_status: 'cancelled')
        end
        order.status = 'cancelled'
        order.save
        booking.booking_status = 'cancelled'
        booking.save
        respond_to do |format|
          format.json { render :json => { :status => true, :order_id => order_id } }
        end
      else
        respond_to do |format|
          format.json { render :json => { :status => false, :error_message => "Order not found" } }
        end
      end
    else
      respond_to do |format|
        format.json { render :json => { :status => false, :error_message => "OrderID does not exist" } }
      end
    end
  end

end
