<?php

namespace App\Livewire;

use App\Models\PalletValidation;
use Livewire\Component;

class SerialLocatorDataTable extends Component
{

    public $plantId;

    public $locatorNumber;

    public $serialNumber;

    public $hasSearched = false;

    public $locatorNo;


    public $locators = [];

    protected $listeners =
    [
        'loadData' => 'loadLocatorData',
        'open-confirm-modal' => 'openConfirmModal',
        'open-confirm-serial' => 'openConfirmSerial',
    ];

    public function openConfirmModal($locatorNo, $plantId)
    {
        $this->locatorNo = $locatorNo;
        $this->plantId = $plantId;

        $this->dispatch('open-modal', id: 'confirm-process-modal');
    }

    public function openConfirmSerial($locatorNo, $plantId)
    {
        $this->locatorNo = $locatorNo;
        $this->plantId = $plantId;

        $this->dispatch('open-modal', id: 'confirm-process-serial');
    }

    public function loadLocatorData($scanLocator, $scanSno, $plantId)
    {

        $this->hasSearched = true;
        $this->locatorNumber = $scanLocator;
        $this->serialNumber = $scanSno;
        $this->plantId = $plantId;
        $this->locators = [];

        // $query = PalletValidation::query()->where('plant_id', $plantId)
        // ->whereNull('pallet_number')
        // ->orWhere('pallet_number', '=','');
        $query = PalletValidation::query()
        ->where('plant_id', $plantId)
        ->where(function($q) {
            $q->whereNull('pallet_number')
              ->orWhere('pallet_number', '=', '');
        });



        if ($scanLocator && $scanSno)
        {
            $query->where('locator_number', $scanLocator)
                ->where('serial_number', $scanSno);
        }
        elseif ($scanLocator)
        {
            $query->where('locator_number', $scanLocator);
        }
        elseif ($scanSno)
        {
            $query->where('serial_number', $scanSno);
        }
        else
        {
            $this->locators = collect();
            return;
        }
        $this->locators = $query->orderByDesc('created_at')->get();

        //dd($this->locators);
    }
    public function render()
    {
        return view('livewire.serial-locator-data-table');
    }
}
