# -*- encoding : utf-8 -*-

class Admin::PCommercialObjectivesController < ApplicationController
  layout "admin"
  before_action :auth_admin

  before_action :admin_space

  def admin_space
    @admin_space = "statistiques"
  end

  def index
    @p_commercial_objectives = PCommercialObjective.all

    @p_commercial_objectives = sort_by_sorting(@p_commercial_objectives, "id DESC")
    respond_to do |format|
      format.html{

        params[:search][:per_page] = params[:search][:per_page] || 100
        per_page = params[:search][:per_page]
        page = (params[:page] and params[:page] != "") ? params[:page] : 1
        @p_commercial_objectives = @p_commercial_objectives.page(page).per(per_page)

      }
    end
  end

  def show
    @p_commercial_objective = PCommercialObjective.find(params[:id])



  end

  def new
    if params[:start_at]
      year = params[:start_at]
    else
      year = Date.today.year
    end


    @p_commercial_objective = PCommercialObjective.generate_for(year)

    @p_commercial_objective.p_commercial_id = params[:p_commercial_id]

  end

  def edit
    @p_commercial_objective = PCommercialObjective.find(params[:id])

  end

  def create
    @p_commercial_objective = PCommercialObjective.new(params.require(:p_commercial_objective).permit!)

    if @p_commercial_objective.save
      redirect_to admin_p_commercial_objective_path(@p_commercial_objective)

    else
      render action: "new"

    end

  end


  def update
    @p_commercial_objective = PCommercialObjective.find(params[:id])


    if @p_commercial_objective.update_attributes(params.require(:p_commercial_objective).permit!)
      redirect_to admin_p_commercial_objective_path(@p_commercial_objective)

    else
     render action: "edit"

    end

  end


  def destroy
    @p_commercial_objective = PCommercialObjective.find(params[:id])
    @p_commercial_objective.destroy

  end
end
