class Transactions::BookingsController < ApplicationController
  load_and_authorize_resource except: [:create]
  before_action :set_transactions_booking, only: [:show, :edit, :update, :destroy]

  def index

    filter     = params[:receipt_no]
    from       = params[:from]
    to         = params[:to]

    if filter.nil? && from.nil? && to.nil?
        @bookings = Booking.all.order("sale_id desc") 
        @bookings = Kaminari.paginate_array(@bookings).page(params[:page]).per(20)
    else
        booking = Booking.search(filter,from,to)
        if booking.count > 0
           @bookings = booking 
           @bookings = Kaminari.paginate_array(@bookings).page(params[:page]).per(20)
         else
           @bookings = 0
         end    
    end
    @receipt_no = filter
    @from       = from
    @to         = to
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @bookings }
    end

  end

  # GET /transactions/bookings/1
  # GET /transactions/bookings/1.json
  def show
   
    @booking = Booking.find(params[:id])
    @order = nil
    @order_items = []
    @booking.booking_orders.each do |booking_order|
      @order = Order.find(booking_order.order_id)
      #if (order.status == "new")
        @order_items = @order_items + @order.order_items
      #end
    end
    if @booking.sale_id.present?
      @sale = Sale.find(@booking.sale_id)
    end    

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @booking }
    end
  end

  def update_status
    data = Booking.where("sale_id IS NULL AND booking_status='assign' AND booking_id = ?", params[:booking_id])
    if !data.nil?
      booking = Booking.find(params[:booking_id])
      booking.booking_status = 'moved'
      booking.save!

      render :json => {:status => true, :message => "Update status successfully."}
    else
      render :json => {:status => false, :error_message => "Can't update status!"}
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_transactions_booking
      @transactions_booking = Booking.find(params[:id])
    end
end
