<?php

namespace App\Livewire\Member;

use App\Livewire\Forms\Studio\Loyalty\CustomerForm;
use App\Models\Membership;
use App\Models\Tier;
use App\Traits\Components\WithToast;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Ringkasan')]
#[Layout('components.layouts.member')]
class Overview extends Component
{
    use WithToast;

    public CustomerForm $form;

    public bool $hasMemberData = false;

    public bool $isVerified = false;

    public function mount(): void
    {
        $this->hasMemberData = auth()->user()->customer()->exists();

        $this->isVerified = auth()->user()->hasVerifiedEmail();

        $this->form->user_id = request()->routeIs('member.overview') ? auth()->id() : null;
    }

    public function checkEmailVerification(): void
    {
        auth()->user()->refresh();

        $this->isVerified = auth()->user()->hasVerifiedEmail();
    }

    public function save(): void
    {
        DB::transaction(function () {
            $this->form->store();

            $this->hasMemberData = true;

            if (! auth()->user()->membership()->exists()) {
                Membership::create([
                    'user_id' => auth()->id(),
                    'tier_id' => Tier::orderBy('min_spending')->first()->id,
                ]);
            }
        });

        $this->toast('Selamat, Anda telah menjadi member sekarang.');
    }

    public function render(): View
    {
        return view('livewire.member.overview');
    }
}
