<?php

use App\Enums\SubscriptionPlan;
use App\Enums\SubscriptionStatus;
use App\Models\Subscription;
use Flux\Flux;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

return new #[Title('Subscriptions')] class extends Component {
    use WithPagination;

    #[Url(as: 'status')]
    public string $statusFilter = 'all';

    #[Url(as: 'plan')]
    public string $planFilter = 'all';

    #[Url(as: 'q')]
    public string $search = '';

    #[Url(as: 'per_page')]
    public int $perPage = 50;

    /**
     * Reset pagination whenever the status filter changes.
     */
    public function updatingStatusFilter(): void
    {
        $this->resetPage();
    }

    /**
     * Reset pagination whenever the plan filter changes.
     */
    public function updatingPlanFilter(): void
    {
        $this->resetPage();
    }

    /**
     * Reset pagination whenever the search term changes.
     */
    public function updatingSearch(): void
    {
        $this->resetPage();
    }

    /**
     * Reset pagination whenever the per-page selection changes.
     */
    public function updatingPerPage(): void
    {
        $this->resetPage();
    }

    /**
     * Update a subscription's order status from the listing page.
     */
    public function updateStatus(int $subscriptionId, string $status): void
    {
        $validated = Validator::make(['status' => $status], [
            'status' => ['required', 'string', Rule::enum(SubscriptionStatus::class)],
        ])->validate();

        Subscription::query()->whereKey($subscriptionId)->firstOrFail()->update([
            'order_status' => SubscriptionStatus::from($validated['status']),
        ]);

        Flux::toast(variant: 'success', text: __('Status updated successfully!'));
    }

    /**
     * @return LengthAwarePaginator<int, Subscription>
     */
    #[Computed]
    public function subscriptions(): LengthAwarePaginator
    {
        return Subscription::query()
            ->when($this->normalizedStatus() !== 'all', fn ($query) => $query->where('order_status', $this->normalizedStatus()))
            ->when($this->normalizedPlan() !== 'all', fn ($query) => $query->where('plan', $this->normalizedPlan()))
            ->when($this->search !== '', function ($query) {
                $query->where(function ($query) {
                    $query->where('full_name', 'like', "%{$this->search}%")
                        ->orWhere('email', 'like', "%{$this->search}%")
                        ->orWhere('phone', 'like', "%{$this->search}%")
                        ->orWhere('order_id', 'like', "%{$this->search}%");
                });
            })
            ->orderByDesc('created_at')
            ->paginate($this->normalizedPerPage());
    }

    /**
     * Stats are computed over the whole table, unaffected by the current
     * filter/search.
     *
     * @return array<string, int|float>
     */
    #[Computed]
    public function stats(): array
    {
        return [
            'total' => Subscription::query()->count(),
            'pending' => Subscription::query()->where('order_status', SubscriptionStatus::Pending)->count(),
            'active' => Subscription::query()->where('order_status', SubscriptionStatus::Active)->count(),
            'cancelled' => Subscription::query()->where('order_status', SubscriptionStatus::Cancelled)->count(),
            'mrr' => (float) Subscription::query()->where('order_status', SubscriptionStatus::Active)->sum('plan_price'),
        ];
    }

    /**
     * Any unrecognised status value silently falls back to "all".
     */
    private function normalizedStatus(): string
    {
        return $this->statusFilter === 'all' || SubscriptionStatus::tryFrom($this->statusFilter) !== null
            ? $this->statusFilter
            : 'all';
    }

    /**
     * Any unrecognised plan value silently falls back to "all".
     */
    private function normalizedPlan(): string
    {
        return $this->planFilter === 'all' || SubscriptionPlan::tryFrom($this->planFilter) !== null
            ? $this->planFilter
            : 'all';
    }

    /**
     * Any unrecognised per-page value falls back to the default of 50.
     */
    private function normalizedPerPage(): int
    {
        return in_array($this->perPage, [25, 50, 100], true) ? $this->perPage : 50;
    }

    protected function view($data = [])
    {
        return app('view')->file('/Users/dineshmali/code/pushpvatikaflorist1/storage/framework/views/livewire/views/b7753918.blade.php', $data);
    }
}; 