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

    def model
      Branch
    end

    def permits
      [:name, :address, :institution_id]
    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 edit
      init_form
      breadcrumbs_for(:edit)

      render template: 'panel/branches/form'
    end

    def new
      @item = model.new

      init_form
      breadcrumbs_for(:new)
      render template: 'panel/branches/form'
    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: 'panel/branches/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: 'panel/branches/form'
    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 settings
      branch = Branch.find params[:id]
      redirect_to panel_branches_url and return unless branch

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

    def unlock
      branch = Branch.find params[:id]
      redirect_to panel_branches_url and return if branch.can_edit?
      branch.update_column(:can_edit, true)
      branch.schedule_can_edit_closure
      redirect_to panel_branches_url and return
    end

    private
    def json_methods
      [ :institution_name ]
    end

  end
end
