<?php

namespace App\Livewire\Member;

use App\Enums\PointRecordType;
use App\Livewire\Forms\Studio\Loyalty\CustomerForm;
use App\Models\Membership;
use App\Models\PointRecord;
use App\Models\Tier;
use App\Traits\WithToast;
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()
    {
        $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()
    {
        auth()->user()->refresh();

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

    public function save()
    {
        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_points')->first()->id,
                    'tier_points' => 10,
                ]);

                PointRecord::create([
                    'user_id' => auth()->id(),
                    'description' => 'Pendaftaran',
                    'change' => 10,
                    'is_addition' => true,
                    'type' => PointRecordType::TIER,
                ]);
            }
        });

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

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