<?php

namespace App\Livewire\Shipment;

use App\Models\Shipment;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public $search = '';
    public $sortField = 'id';
    public $sortDirection = 'desc';
    public $perPage = 10;

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

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

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function delete(Shipment $shipment)
    {
        $shipment->delete();
        session()->flash('message', 'Shipment deleted successfully.');
    }

    public function render()
    {
        $shipments = Shipment::with(['trip', 'customer', 'creator', 'editor'])
            ->where(function ($query) {
                $query->where('description', 'like', '%' . $this->search . '%')
                      ->orWhere('pickup_address', 'like', '%' . $this->search . '%')
                      ->orWhere('delivery_address', 'like', '%' . $this->search . '%')
                      ->orWhereHas('customer', function ($query) {
                          $query->where('name', 'like', '%' . $this->search . '%');
                      });
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate($this->perPage);

        return view('livewire.shipment.index', [
            'shipments' => $shipments,
        ]);
    }
}