class ClientsController < AdminBaseController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

  # GET /clients
  # GET /clients.json
  def index
    if not current_user.allowed?(:view_clients)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @q = Client.ransack(params[:q])
    @q.sorts = "id DESC" if @q.sorts.empty?
    @clients = @q.result.page(params[:page])
  end

  # GET /clients/1
  # GET /clients/1.json
  def show
  end

  # GET /clients/new
  def new
    @client = Client.new
  end

  # GET /clients/1/edit
  def edit
    if not current_user.allowed?(:edit_clients)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end
  end

  # POST /clients
  # POST /clients.json
  def create
    if not current_user.allowed?(:create_clients)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @client = Client.new(client_params)

    respond_to do |format|
      if @client.save
        format.html { redirect_to clients_path, info: 'Client was successfully created.' }
        format.json { render :show, status: :created, location: @client }
      else
        format.html { render :new }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /clients/1
  # PATCH/PUT /clients/1.json
  def update
    if not current_user.allowed?(:edit_clients)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    respond_to do |format|
      if @client.update(client_params)
        format.html { redirect_to clients_url, info: 'Client was successfully updated.' }
        format.json { render :show, status: :ok, location: @client }
      else
        format.html { render :edit }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /clients/1
  # DELETE /clients/1.json
  def destroy
    if not current_user.allowed?(:destroy_clients)
      redirect_to "/admin", alert: "你没有权限进入此页面!" and return
    end

    @client.destroy
    respond_to do |format|
      format.html { redirect_to clients_url, info: 'Client was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_client
      @client = Client.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def client_params
      params.require(:client).permit(:name, :contact)
    end
end
