<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SetupDonation;
use App\Models\Transaction;

class DonationController extends Controller
{
    public function all()
    {
        $pageTitle = 'All Donations';
        $donations = Transaction::where('remark', 'donation')->searchable(['user:username', 'trx', 'reference'])->filter(['setup_donation_id']);

        $data['today']      = clone $donations;
        $data['this_month'] = clone $donations;
        $data['this_year']  = clone $donations;

        $donations->dateFilter()->with('user', 'donationFor');
        $now   = now();

        $data['today']      = $data['today']->whereDate('created_at', $now->today())->sum('amount');
        $data['this_month'] = $data['this_month']->whereMonth('created_at', $now->month)->whereYear('created_at', $now->year)->sum('amount');
        $data['this_year']  = $data['this_year']->whereYear('created_at', $now->year)->sum('amount');
        $data['all']        = $donations->sum('amount');

        $donations      = $donations->orderBy('id', 'DESC')->paginate(getPaginate());
        $setupDonations = SetupDonation::searchable(['name'])->get();

        if (request()->setup_donation_id) {
            $selectedDonation = $setupDonations->where('id', request()->setup_donation_id)->first();
            $pageTitle        = $selectedDonation->name . ' Donations';
        }

        return view('admin.donation.all', compact('pageTitle', 'donations', 'data', 'setupDonations'));
    }
}
