<?php

namespace App\Livewire\Studio\Loyalty\Voucher;

use App\Models\Voucher;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use App\Traits\Notification\WithSubscribeNotification;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Voucher')]
class Index extends Component
{
    use WithAuthorization, WithConfirmation, WithSubscribeNotification, WithToast;

    public array $stats = [];

    public function mount(): void
    {
        $hasNotification = request()->get('notification');

        if ($hasNotification) {
            $this->js(<<<'JS'
                const url = new URL(window.location);
                url.search = '';
                window.history.replaceState({}, '', url);
            JS);

            $this->toast($hasNotification);
        }

        $this->stats = [
            [
                'title' => 'Total Voucher',
                'value' => Voucher::count(),
            ],
            [
                'title' => 'Voucher Aktif',
                'value' => Voucher::query()->active()->count(),
            ],
            [
                'title' => 'Voucher Tidak Aktif',
                'value' => Voucher::query()->inactive()->count(),
            ],
            [
                'title' => 'Voucher Akan Datang',
                'value' => Voucher::query()->upcoming()->count(),
            ],
        ];
    }

    public function delete(Voucher $voucher): void
    {
        $this->canOrAbort('delete voucher');

        $voucher->delete();

        $this->dispatch('refreshDatatable');

        $this->toast('Voucher berhasil dihapus.');
        Flux::modals()->close();
    }

    public function render(): View
    {
        return view('livewire.studio.loyalty.voucher.index', [
            'pageTitle' => 'Voucher',
        ]);
    }
}
