class ReportsController < ApplicationController

  before_action :user_is_employee?
  before_action :set_dates, except: :actives
  layout "admin"

  def index
    @plans = Plan.where(created_at: @from..@to)
    @trainers = User.where(id: @plans.pluck(:trainer_id).uniq)
    @users = User.where(id: @plans.pluck(:user_id))
    @new_users = @users.where(created_at: @from..@to)
    @recurrent_users = @users.where.not(id: [@new_users.pluck(:id)] )
    @medical_histories = MedicalHistory.all
  end
    
  def show
    @medical_histories = MedicalHistory.all
    @trainer = User.find_by_safe_url(params[:id])
    @plans = Plan.where(created_at: @from..@to)
    @users = User.where(id: @plans.pluck(:user_id))

    @new_users = @users.where(created_at: @from..@to)
    @recurrent_users = @users.where.not(id: [@new_users.pluck(:id)] )
  end

  def actives
    @today = Date.today
    @from = params[:from] ? params[:from].to_date : @today - 6.months
    @to = params[:to] ? params[:to].to_date : @today
    #
    @plans = Plan.where(created_at: @from..@to)
    @users = User.where(id: @plans.pluck(:user_id)).order(last_plan: :asc)
    @new_users = @users.where(created_at: @from..@to)
    @recurrent_users = @users.where.not(id: [@new_users.pluck(:id)] )
  end

  private 

  def set_dates
    @from = Date.today.beginning_of_month.beginning_of_day
    @to = Date.today.end_of_day
    if params[:dates]
      dates = params[:dates].split("-")
      @from = dates[0].to_date.beginning_of_day
      @to = dates[1].to_date.end_of_day
    end
  end

end
