# frozen_string_literal: true
module Panel
  #
  class ManagementCategoriesController < PanelController
    include Panel::Crud
    include Panel::Multiple

    def model
      ManagementCategory
    end

    def permits
      [:kind, :name, :institution_id, :classification]
    end

    def exportable_fields
      []
    end

    def create
      @item = model.new item_params
      set_uniq_institution! if current_user.one_institution?
      if @item.save
        return redirect_to(edit_url, flash: { saved: true })
      end
      init_form
      breadcrumbs_for(:new)
      render template: 'concerns/panel/form'
    end

    def update
      @item.attributes = item_params
      if @item.save
        return redirect_to(edit_url, flash: { saved: true })
      end
      init_form
      breadcrumbs_for(:edit)
      render template: 'concerns/panel/form'
    end

    def item_params
      perms = params.require(:item).permit(permits)
      perms
    end

    def respond_to_json
      @q = model.accessible_by(current_ability)
      @q = @q.ransack(params[:filter])
      @c = @q.result.paginate(page: params[:page], per_page: params[:count])

      render json: json_result(@c)
    end

    def init_form
      if current_user.has_role?("admin")
        @institutions = Institution.order(Institution.acts_as_label)
      else
        @institutions = Institution.where("id IN (?)", current_user.institution_ids)
      end
    end

    def json_methods
      [ :institution_name, :kind_s ]
    end

    def respond_to_html
      add_breadcrumb t('home'), panel_root_url
      add_breadcrumb humanized_model_name(:many), index_url
      # render template: 'concerns/panel/index'
    end


  end
end
