<?php

namespace App\Livewire\Studio\Loyalty;

use App\Enums\RedemptionStatus;
use App\Models\Redemption;
use App\Traits\Authorization\WithAuthorization;
use App\Traits\Components\WithConfirmation;
use App\Traits\Components\WithToast;
use Flux\Flux;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Str;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Verifikasi Penukaran')]
class RedemptionVerification extends Component
{
    use WithAuthorization, WithConfirmation, WithToast;

    public string $searchCode = '';

    public ?Redemption $foundRedemption = null;

    public function search(): void
    {
        $this->canOrAbort('view redemption');

        $this->foundRedemption = Redemption::where('code', Str::upper(Str::trim($this->searchCode)))
            ->with(['user', 'user.customer', 'reward'])
            ->first();

        if (! $this->foundRedemption) {
            $this->toast('Kode penukaran tidak ditemukan.', 'Gagal', 'danger');
        } else {
            // Force refresh status if expired
            $this->foundRedemption->isExpired();
        }
    }

    public function verify($id = null): void
    {
        $this->canOrAbort('update redemption');

        if ($this->foundRedemption->status !== RedemptionStatus::WAITING_PICKUP) {
            $this->toast('Penukaran ini sudah diproses sebelumnya.', 'warning');

            return;
        }

        if ($this->foundRedemption->isExpired()) {
            $this->toast('Kode penukaran ini sudah kadaluarsa.', 'error');

            return;
        }

        $this->foundRedemption->update([
            'status' => RedemptionStatus::PICKED_UP,
            'verified_at' => now(),
            'verified_by' => auth()->id(),
        ]);

        $this->toast('Penukaran hadiah berhasil diverifikasi!');

        $this->foundRedemption->refresh();

        Flux::modals()->close();
    }

    public function render(): View
    {
        return view('livewire.studio.loyalty.redemption', [
            'pageTitle' => 'Verifikasi Penukaran',
        ]);
    }
}
