<?php

namespace App\Http\Livewire\Pages\Dischargeport;

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

class DischargeportIndex extends Component
{
    use WithPagination;

    public $action = 'list';
    public $searchBy, $message, $keyword, $perPage = 20, $searchSelected = 'isocode';
    public $totalItems;
    protected $listeners = [
        'showdischargeportListForm',
        'loadPage'
    ];

    public function mount()
    {
        $this->searchBy = [
            'isocode' => 'ISO Code',
            'portname' => 'Port Name',
            'cntrycode' => 'Country Code',
            'flagstatus' => 'Flag Status',
            'lastupdate' => 'Last Update'
        ];
        $this->showdischargeportListForm();
        $this->message = null;
    }

    public function render()
    {
        $query = MasterDischargePort::select(
            'isocode',
            'portname',
            'cntrycode',
            'startdate',
            'finishdate',
            'usrname',
            'flagstatus',
            'lastupdate'
        );

        if ($this->searchSelected && $this->keyword) {
            $query->where($this->searchSelected, 'LIKE', '%' . $this->keyword . '%');
        }

        $results = $query->paginate($this->perPage);
        $this->totalItems = $results->total();
        return view('livewire.pages.dischargeport.dischargeport-index', [
            'results' => $results,
            'action' => $this->action,
        ]);
    }

    public function search()
    {
        $this->resetPage();
    }
    public function updatedPerPage($value)
    {
        $this->adjustPageForNewPerPage();
    }

    public function adjustPageForNewPerPage()
    {
        $lastPage = ceil($this->totalItems / $this->perPage);
        if ($this->page > $lastPage) {
            $this->setPage($lastPage);
        }
    }
    public function showdischargeportListForm()
    {
        $this->action = 'list';
    }

    public function loadPage($page)
    {
        $this->action = $page;
    }
}
