class Admin::DonationsController < Admin::BaseController
  before_action :set_donation, only: [:show, :edit, :update, :destroy]
  before_action :set_current_section, only: [:index, :show, :new, :edit]

  # GET /donations
  # GET /donations.json
  def index
    @pagy, @donations = pagy(Donation.all.order('created_at desc'))

    @stats = {
      overall_sats: @donations.all.sum("amount_sats"),
      donor_count: Donation.distinct.count(:user_id)
    }
  end

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

  # GET /donations/new
  def new
    @donation = Donation.new
  end

  # GET /donations/1/edit
  def edit
  end

  # POST /donations
  # POST /donations.json
  def create
    @donation = Donation.new(donation_params)

    respond_to do |format|
      if @donation.save
        format.html do
          redirect_to admin_donation_url(@donation), flash: {
            success: 'Donation was successfully created.'
          }
        end
        format.json { render :show, status: :created, location: @donation }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @donation.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /donations/1
  # PATCH/PUT /donations/1.json
  def update
    respond_to do |format|
      if @donation.update(donation_params)
        format.html do
          redirect_to admin_donation_url(@donation), flash: {
            success: 'Donation was successfully updated.'
          }
        end
        format.json { render :show, status: :ok, location: @donation }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @donation.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /donations/1
  # DELETE /donations/1.json
  def destroy
    @donation.destroy
    respond_to do |format|
      format.html do redirect_to admin_donations_url, flash: {
        success: 'Donation was successfully destroyed.'
      }
      end
      format.json { head :no_content }
    end
  end

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

    # Only allow a list of trusted parameters through.
    def donation_params
      params.require(:donation).permit(:user_id, :amount_sats, :amount_eur, :amount_usd, :public_name, :paid_at)
    end

    def set_current_section
      @current_section = :donations
    end
end
