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
  def index
    @pagy, @donations = pagy(Donation.completed.order('paid_at desc'))

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

  # GET /donations/1
  def show
  end

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

  # GET /donations/1/edit
  def edit
  end

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

    if @donation.paid_at == nil
      @donation.errors.add(:paid_at, message: "is required")
      render :new, status: :unprocessable_entity and return
    end

    if @donation.save
      redirect_to admin_donation_url(@donation), flash: {
        success: 'Donation was successfully created.'
      }
    else
      render :new, status: :unprocessable_entity
    end
  end

  # PUT /donations/1
  def update
    if @donation.update(donation_params)
      redirect_to admin_donation_url(@donation), flash: {
        success: 'Donation was successfully updated.'
      }
    else
      render :edit, status: :unprocessable_entity
    end
  end

  # DELETE /donations/1
  def destroy
    @donation.destroy

    redirect_to admin_donations_url, flash: {
      success: 'Donation was successfully destroyed.'
    }
  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, :donation_method,
        :amount_sats, :fiat_amount, :fiat_currency,
        :public_name, :paid_at)
    end

    def set_current_section
      @current_section = :donations
    end
end
