<?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 function mount(): void
    {
        $this->hasMemberData = auth()->user()->customer()->exists();

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

    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
    {
        $user = auth()->user();
        $referralCode = $user->referralCode;

        if (! $referralCode && $this->hasMemberData) {
            $referralCode = $user->referralCode()->create([
                'code' => strtoupper(str()->random(8)),
            ]);
        }

        $message = 'Halo! Ayo bergabung di Yadi Parfum dan dapatkan keuntungan eksklusif. Gunakan kode referral saya: '.($referralCode?->code ?? '').' saat mendaftar! '.url('/auth/register');
        $whatsappUrl = 'https://wa.me/?text='.urlencode($message);

        return view('livewire.member.overview', [
            'whatsappUrl' => $whatsappUrl,
        ]);
    }
}
