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

    def model
      Institution
    end

    def permits
      [:name, :acronym, :correlative, :avatar, :address, :responsible_unit, :email, :phone, :whatsapp, :facebook, :twitter]
    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 new
      @item = model.new

      init_form
      breadcrumbs_for(:new)
      render template: 'panel/institutions/form'
    end

    def create
      @item = model.new item_params
      set_uniq_institution!
      return redirect_to(edit_url, flash: { saved: true }) if @item.save

      init_form
      breadcrumbs_for(:new)
      render template: 'panel/institutions/form'
    end

    def edit
      init_form
      breadcrumbs_for(:edit)

      render template: 'panel/institutions/form'
    end

    def update
      respond_to do |format|
        format.json { super }
        format.html do
          return redirect_to(edit_url, flash: { saved: true }) if
            @item.update_attributes(item_params)

          breadcrumbs_for(:edit)
          init_form
          render template: 'panel/institutions/form'
        end
      end
    end

    def settings
      institution = Institution.find params[:id]
      redirect_to panel_institutions_url and return unless institution

      institution.settings.mon = params[:mon]
      institution.settings.tue = params[:tue]
      institution.settings.wed = params[:wed]
      institution.settings.thu = params[:thu]
      institution.settings.fri = params[:fri]
      institution.settings.sat = params[:sat]
      institution.settings.holidays = params[:days]
      institution.settings.response_days = params[:response_days]
      redirect_to edit_panel_institution_url, flash: {saved: true}
    end

    def unlock
      institution = Institution.find params[:id]
      redirect_to panel_institutions_url and return if institution.can_edit?
      institution.update_column(:can_edit, true)
      institution.schedule_can_edit_closure
      redirect_to panel_institutions_url and return
    end

  end
end
