<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\Subscription;
use App\Services\Subscriptions\SubscriptionService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SubscriptionController extends Controller
{
    public function index(Request $request): View
    {
        $filters = $request->only(['q', 'plan_id', 'status', 'billing_cycle']);

        $subscriptions = Subscription::query()
            ->with(['business.owner', 'plan', 'payments' => fn ($query) => $query->latest()])
            ->when($filters['q'] ?? null, function (Builder $query, string $search): void {
                $query->whereHas('business', function (Builder $query) use ($search): void {
                    $query->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            })
            ->when($filters['plan_id'] ?? null, fn (Builder $query, string $planId) => $planId !== 'all' ? $query->where('plan_id', $planId) : null)
            ->when($filters['status'] ?? null, fn (Builder $query, string $status) => $status !== 'all' ? $query->where('status', $status) : null)
            ->when($filters['billing_cycle'] ?? null, fn (Builder $query, string $cycle) => $cycle !== 'all' ? $query->where('billing_cycle', $cycle) : null)
            ->latest('starts_at')
            ->paginate(15)
            ->withQueryString();

        return view('super-admin.subscriptions.index', [
            'subscriptions' => $subscriptions,
            'plans' => Plan::query()->orderBy('sort_order')->get(),
            'filters' => $filters,
        ]);
    }

    public function show(Subscription $subscription, SubscriptionService $subscriptionService): View
    {
        $subscription->load(['business.owner', 'plan', 'payments' => fn ($query) => $query->latest()]);

        return view('super-admin.subscriptions.show', [
            'subscription' => $subscription,
            'usageLimits' => $subscriptionService->usage($subscription->business, $subscription),
            'payments' => $subscription->payments,
        ]);
    }
}
