<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\UserSubscription;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PaymentsController extends Controller
{
    public function index(Request $request): View
    {
        $payments = UserSubscription::with('user:id,name,email')
            ->when($request->filled('source'), fn (Builder $query) => $query->where('source', $request->string('source')))
            ->when($request->filled('plan'), fn (Builder $query) => $query->where('plan', $request->string('plan')))
            ->when($request->filled('status'), function (Builder $query) use ($request) {
                if ($request->string('status')->value() === 'paid') {
                    $query->where('amount_paid', '>', 0);
                    return;
                }

                if ($request->string('status')->value() === 'voucher') {
                    $query->where('source', 'voucher');
                    return;
                }

                if ($request->string('status')->value() === 'expired') {
                    $query->whereNotNull('expires_at')->where('expires_at', '<', now());
                }
            })
            ->when($request->filled('q'), function (Builder $query) use ($request) {
                $term = $request->string('q')->value();
                $query->where(function (Builder $inner) use ($term) {
                    $inner->where('transaction_id', 'like', "%{$term}%")
                        ->orWhere('voucher_code', 'like', "%{$term}%")
                        ->orWhereHas('user', fn (Builder $userQuery) => $userQuery
                            ->where('email', 'like', "%{$term}%")
                            ->orWhere('name', 'like', "%{$term}%"));
                });
            })
            ->latest()
            ->paginate(25)
            ->withQueryString();

        $stats = [
            'gross_revenue' => UserSubscription::where('amount_paid', '>', 0)->sum('amount_paid'),
            'paid_transactions' => UserSubscription::where('amount_paid', '>', 0)->count(),
            'voucher_redemptions' => UserSubscription::where('source', 'voucher')->count(),
            'active_paid' => UserSubscription::where('amount_paid', '>', 0)
                ->where('is_active', true)
                ->where(fn (Builder $query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now()))
                ->count(),
        ];

        $revenueBySource = UserSubscription::selectRaw('source, COALESCE(SUM(amount_paid), 0) as total')
            ->groupBy('source')
            ->orderByDesc('total')
            ->pluck('total', 'source');

        return view('admin.payments.index', compact('payments', 'stats', 'revenueBySource'));
    }
}
