class HomeController < ApplicationController
  # layout "application", except: [:index, :show]
  skip_before_action :authenticate, only: [:index, :show, :create, :update, :destroy]  

  def index
    # @employees = Employee.all_emp_except_waiter.order("name asc")
    @employees = Employee.all.order("name asc")
     @login_form = LoginForm.new()
    render "layouts/login_dashboard", layout: false
  end

  def show
    @login_form = LoginForm.new()
    @login_form.emp_id = params[:emp_id]
    render "layouts/login", layout: false
  end

  def update
    @login_form = LoginForm.new()
    @login_form.emp_id = params[:emp_id]
    @login_form.password = params[:login_form][:password]
    @employee = Employee.login(@login_form.emp_id, @login_form.password)

    if @employee != nil
      session[:session_token] = @employee.token_session
      route_by_role(@employee)
    else
      flash[:notice] ="Invalid PIN for Employee. Please try again!"
      render :show 
    end    
  end

  def create
    @login_form = LoginForm.new()
    @login_form.emp_id = params[:login_form][:emp_id]
    @login_form.password = params[:login_form][:password]
    @employee = Employee.login(@login_form.emp_id, @login_form.password)

    if @employee != nil
      if @employee.role == "administrator"
        session[:session_token] = @employee.token_session
        redirect_to dashboard_path
      elsif @employee.role == "cashier"
        session[:session_token] = @employee.token_session
        route_by_role(@employee)
      elsif @employee.role == "manager"
        session[:session_token] = @employee.token_session
        redirect_to dashboard_path
      elsif @employee.role == "supervisor" || @employee.role == "waiter"
        session[:session_token] = @employee.token_session
        redirect_to origami_root_path
      elsif @employee.role == "account"
        session[:session_token] = @employee.token_session
        redirect_to reports_dailysale_index_path
      else
         render :index
      end
    else
      redirect_to origami_root_path, :notice => "Username and Password doesn't match!"
    end

  end

  def dashboard
    @shop = Shop.first

    today = DateTime.now.strftime('%Y-%m-%d')
    @orders = Sale::where("payment_status='new' and sale_status='bill' and DATE_FORMAT(receipt_date,'%Y-%m-%d') = '#{today}'").count()
    @sales = Sale::where("payment_status='paid' and sale_status='completed' and DATE_FORMAT(receipt_date,'%Y-%m-%d') = '#{today}'").count()

    @top_products = Sale.top_products(today).sum('i.qty')
    @bottom_products = Sale.bottom_products(today).sum('i.qty')
    @hourly_sales = Sale.hourly_sales(today).sum(:grand_total)
    # .group_by_hour(:created_at, :time_zone => 'Asia/Rangoon',format: '%I:%p')
    # .sum(:grand_total)
    @employee_sales = Sale.employee_sales(today)
                    .sum('(CASE WHEN sp.payment_method="cash" THEN (sp.payment_amount - sales.amount_changed) ELSE sp.payment_amount END)')
    @inventories    = StockJournal.inventory_balances(today).sum(:balance)

    @total_sale     = Sale.total_sale(today)
    @total_count    = Sale.total_count(today)
    @total_card     = Sale.total_card_sale(today)
    @total_credit   = Sale.credit_payment(today)

    @sale_data = Array.new
    @total_payment_methods = Sale.total_payment_methods(today)

    @total_payment_methods.each do |payment|
      if payment.payment_method == "mpu" || payment.payment_method == "visa" || payment.payment_method == "master" || payment.payment_method == "jcb"
        pay = Sale.payment_sale('card', today)
        @sale_data.push({'card' => pay.payment_amount})
      else 
        pay = Sale.payment_sale(payment.payment_method, today)
        @sale_data.push({payment.payment_method => pay.payment_amount})
      end
    end
    @summ_sale              = Sale.summary_sale_receipt(today)
    @total_customer         = Sale.total_customer(today)
    @total_dinein           = Sale.total_dinein(today)
    @total_takeaway         = Sale.total_takeaway(today)
    @total_other_customer   = Sale.total_other_customer(today)
    @total_membership       = Sale.total_membership(today)

    @total_order            = Sale.total_order(today)
    @total_accounts         = Sale.total_account(today)
    @account_data = Array.new
    @total_accounts.each do |account|
      acc = Sale.account_data(account.account_id, today)
      if !acc.nil?
        @account_data.push({account.title => acc.cnt_acc, account.title + '_amount' => acc.total_acc})
      end
    end

    @top_items         = Sale.top_items(today)
    @total_foc_items   = Sale.total_foc_items(today) 
  end

  def destroy
    # clear in employee session
    Employee.logout(session[:session_token])
    session[:session_token] = nil
    # redirect_to root_path
    render :json => {:status=> "Success", :url => root_path }.to_json
  end

  private

  # Never trust parameters from the scary internet, only allow the white list through.
  def settings_home_params
    params.require(:login_form).permit(:emp_id, :password)
  end

  def route_by_role(employee)
    if employee.role == "administrator"
      # redirect_to dashboard_path
      shift = ShiftSale.current_open_shift(employee.id)
      if !shift.nil?
        redirect_to origami_root_path
      else
        redirect_to dashboard_path
       end
    elsif employee.role == "cashier"
      #check if cashier has existing open cashier
      shift = ShiftSale.current_open_shift(employee.id)
      if !shift.nil?
        redirect_to origami_root_path
      else
        redirect_to new_origami_shift_path
       end
    elsif employee.role == "manager"
      redirect_to dashboard_path
    elsif employee.role == "waiter"
      redirect_to oqs_root_path
    elsif employee.role == "crm"
      redirect_to crm_root_path
    elsif @employee.role == "supervisor"
        redirect_to origami_root_path
    elsif @employee.role == "account"
        redirect_to reports_dailysale_index_path
    end
  end
end
