class UserPagesController < ApplicationController

  before_action :authenticate_user!
  before_action :set_plan, only: [:home, :meals, :routines, :measurements, :photos]
  before_action :set_user

  def home
    if !current_user.profile_completed?
      flash[:notice] = "Antes de comenzar, necesitamos saber algunos datos sobre tí"
      redirect_to "/editar_perfil"
    # else
    #   redirect_to "/progreso"
    end
  end

  def photos
    @user = current_user
    @last = @user.photos.order(created_at: :asc).last
  end

  def measurements
  end

  def update_photo
    @photo = Photo.new(photo_params)
    if @photo.save
      redirect_to "/progreso"
    else
      render :edit
    end
  end

  def update
    if @user.update(user_params)
      @user.avatar.recreate_versions! if user_params[:avatar]
      @user.save!
      redirect_to "/home"
    else
      render :edit
    end
  end

  def password
    @user = current_user
  end

  def update_password
    if current_user.update(password: params[:user][:password], password_confirmation: params[:user][:password_confirmation])
      flash[:notice] = "Contraseña Actualizada"
      bypass_sign_in(current_user)
      redirect_to "/home"
    else
      render :password
    end
  end

  def trainer
    @trainers = User.trainers
    if !current_user.coach.nil? && current_user.plan_active
      redirect_to "/home"
    end
  end

  def update_trainer
    # Si el usuario no ha seleccionado a su entrenador o no tiene plan activo, entonces procedemos a cambiar
    if current_user.coach.nil? || !current_user.plan_active
      update_coach
    else
      # if current_user.subscription_active
        redirect_to "/home"
      # else
      #   update_coach
      # end
    end
  end

  def historial
    @medical_history = current_user.medical_history
    @medical_history = MedicalHistory.create(user: current_user) if @medical_history.nil?
  end
  
  def update_history
    if current_user.medical_history.update(medical_history_params)
      redirect_to "/home"
    else
      render :edit
    end
  end

  def update_composition
    if @user.update(user_params)
      @user.side.recreate_versions! if user_params[:side]
      @user.back.recreate_versions! if user_params[:back]
      @user.front.recreate_versions! if user_params[:front]
      redirect_to "/historial"
    else
      render :edit
    end
  end

  def meals
    @meals = @plan.meals if @plan
  end

  def routines
    @recommendations = Speech.find_by_key_url('training_recommendations')
    @day = 1
    @day = params[:dia].to_i if params[:dia]
    @day = 1 if @day <= 0
    if @plan
      @routines = @plan.routines.order(number: :asc)
      @day = @routines.count if @day > @routines.count
      @routine = @routines[@day-1]
    end
  end

  def plans
    if !current_user.plan_active
      redirect_to "/home"
    end
  end

  def destroy
    current_user.messages.delete_all
    current_user.plans.delete_all
    current_user.cards.delete_all
    current_user.destroy
    redirect_to "/", notice: "Su perfil ha sido eliminado"
  end

  private

  def update_coach
    coach = User.find_by_safe_url(params[:user][:coach_id])
    current_user.update(coach_id: coach.id)
    redirect_to "/composicion"
  end

  def set_user
    @user = current_user
  end

  def set_plan
    @mensaje = Message.where(user_id: current_user.id, status: "new", emisor_id: 8).order(created_at: :desc).last
    @message = Message.new(user_id: @mensaje.emisor.safe_url, hide_message: @mensaje.id) if @mensaje
    if current_user.plan_active
      @plan = current_user.plan_active
      if @plan
        if @plan.week >= 3
          @trace_days = @plan.current_day if @plan.trace_comments.blank?
          flash[:notice] = @plan.adjust if !@plan.adjust.blank?
        end
      end
    end
  end

  def photo_params
    params.require(:photo).permit(:user_id, :side, :back, :front, :weight)
  end

  def user_params
    params.require(:user).permit(
      #perfil 
      :full_name, :height, :sex, :avatar, :tel, :dob, :kg, :tmb, :corporal_fat,
      # fotos
      :back, :front, :side)
  end

  def medical_history_params
    params.require(:medical_history).permit(:diseases, :medicines, :injuries, :stress, :regimen, :vegetables, :soda, :alcohol, :dislikes, :likes, :habitual_feed, :supplementation, :steroids, :exercise, :training_age, :available_days, :training_days, :novelty_program, :physical_stress, :recover, :force, :external_recover, :sleep_hours, :training_place, :injuries_detail, :stress_detail, :alcohol_detail, images: [])
  end
 
end