<?php

namespace App\Livewire\Resources;

use App\Services\Models\CartService;
use Illuminate\Support\Facades\Log;
use Livewire\Attributes\On;
use Livewire\Component;

class UserAddresses extends Component
{
    public bool $selection = false;
    public $selectedAddress = null;
    public $addresses;

    public function __construct()
    {
        $this->addresses = $this->getUserAddresses() ?? [];
    }

    private function getUserAddresses()
    {
        return auth()->user()->addresses;
    }

    public function deleteAddress(int $id): bool
    {
        try {
            auth()->user()->addresses()->where('id', $id)->delete();
        } catch (\Throwable $th) {
            Log::error("properly trying to remove address with id of  ($id) after being deleted");
        }

        return true;
    }

    #[On('new-address-created')]
    public function updatedList()
    {
        $this->addresses = $this->getUserAddresses() ?? [];
    }

    #[On('address-selected')]
    public function updatedSelectedAddress($addressId)
    {
        $this->selectedAddress = $addressId;
        $cart = (new CartService)->updateCartAddress($addressId);
    }
    public function render()
    {
        return view('livewire.resources.user-addresses');
    }
}
