<?php

namespace App\Livewire\Store;

use App\Models\GuestCustomer;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.store')]
#[Title('Akun Saya')]
class Account extends Component
{
    // ── Mode tampilan ─────────────────────────────────────────────────────
    public bool $editing = false;

    // ── Form fields ───────────────────────────────────────────────────────
    public string $name    = '';
    public string $phone   = '';
    public string $address = '';

    // ── Lifecycle ─────────────────────────────────────────────────────────

    /**
     * Dipanggil dari JS setelah localStorage di-load.
     * Hanya isi jika belum ada data dari DB (DB lebih prioritas).
     */
    #[On('guest-profile:loaded')]
    public function fillFromLocalStorage(array $data): void
    {
        if (empty($this->name)    && ! empty($data['name']))    $this->name    = $data['name'];
        if (empty($this->phone)   && ! empty($data['phone']))   $this->phone   = $data['phone'];
        if (empty($this->address) && ! empty($data['address'])) $this->address = $data['address'];
    }

    public function mount(): void
    {
        $this->loadGuest();
    }

    private function loadGuest(): void
    {
        $guest = $this->getGuest();
        if ($guest) {
            $this->name    = $guest->name;
            $this->phone   = $guest->phone;
            $this->address = $guest->address;
        }
    }

    private function getGuest(): ?GuestCustomer
    {
        return GuestCustomer::forSession(session()->getId())->latest()->first();
    }

    // ── Actions ───────────────────────────────────────────────────────────

    public function clearLocalStorage(): void
    {
        $this->dispatch('guest-profile:clear');
        $this->dispatch('notify', type: 'success', message: 'Data tersimpan berhasil dihapus.');
    }

    public function startEdit(): void
    {
        $this->loadGuest();
        $this->editing = true;
    }

    public function cancelEdit(): void
    {
        $this->loadGuest();
        $this->editing = false;
    }

    public function save(): void
    {
        $this->validate([
            'name'    => ['required', 'string', 'max:150'],
            'phone'   => ['required', 'string', 'max:20'],
            'address' => ['required', 'string', 'min:5'],
        ], [
            'name.required'    => 'Nama wajib diisi.',
            'phone.required'   => 'Nomor WA wajib diisi.',
            'address.required' => 'Alamat wajib diisi.',
            'address.min'      => 'Alamat terlalu pendek.',
        ]);

        GuestCustomer::updateOrCreate(
            ['session_id' => session()->getId()],
            [
                'name'    => $this->name,
                'phone'   => $this->phone,
                'address' => $this->address,
            ]
        );

        $this->editing = false;
        $this->dispatch('notify', type: 'success', message: 'Data diri berhasil disimpan.');

        // Perbarui localStorage agar data baru tersedia tanpa isi ulang
        $this->dispatch('guest-profile:save', data: [
            'name'    => $this->name,
            'phone'   => $this->phone,
            'address' => $this->address,
        ]);
    }

    // ── Render ────────────────────────────────────────────────────────────

    public function render()
    {
        $guest        = $this->getGuest();
        $storeName    = \App\Models\Setting::get('store_name', config('app.name'));
        $waAdmin      = \App\Models\Setting::get('wa_admin');
        $waNumber     = $waAdmin
            ? preg_replace('/^0/', '62', preg_replace('/[^0-9]/', '', $waAdmin))
            : null;
        $orderCount   = $guest ? $guest->orders()->count() : 0;

        return view('livewire.store.account', compact(
            'guest', 'storeName', 'waNumber', 'orderCount'
        ));
    }
}
