<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Address;
use App\Models\User;

class AdminAddresses extends Component
{
    use WithPagination;

    public $search = '';
    public $sortField = 'id';
    public $sortDirection = 'desc';
    public $showAddModal = false;
    public $showDeleteModal = false;
    public $newAddresses = '';
    public $deletingAddressId = null;

    protected $queryString = ['search', 'sortField', 'sortDirection'];

    protected $paginationTheme = 'bootstrap';

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortDirection = 'asc';
        }
        $this->sortField = $field;
    }

    public function addAddresses()
    {
        $this->validate([
            'newAddresses' => 'required|string',
        ]);

        $addresses = array_filter(array_map('trim', explode("\n", $this->newAddresses)));
        
        foreach ($addresses as $address) {
            Address::create([
                'address' => $address,
            ]);
        }

        $this->newAddresses = '';
        $this->showAddModal = false;
        session()->flash('message', 'Addresses added successfully.');
    }

    public function confirmDelete($addressId)
    {
        $this->deletingAddressId = $addressId;
        $this->showDeleteModal = true;
    }

    public function deleteAddress()
    {
        if ($this->deletingAddressId) {
            Address::find($this->deletingAddressId)->delete();
            $this->showDeleteModal = false;
            $this->deletingAddressId = null;
            session()->flash('message', 'Address deleted successfully.');
        }
    }

    public function render()
    {
        $query = Address::with('user')
            ->when($this->search, function ($query) {
                $query->where(function ($q) {
                    $q->where('address', 'like', '%' . $this->search . '%')
                      ->orWhereHas('user', function ($q) {
                          $q->where('name', 'like', '%' . $this->search . '%');
                      });
                });
            })
            ->orderBy($this->sortField, $this->sortDirection);

        return view('livewire.admin-addresses', [
            'addresses' => $query->paginate(10),
        ]);
    }
}
