<?php

namespace App\Livewire;

use App\Models\LocatorInvoiceValidation;
use Livewire\Component;

class LocatorInvoiceDataTable extends Component
{
    public $plantId;

    public $invoiceNumber;

    public $records = [];
    public bool $showRemoveSerialsModal = false;

    public $matchedSerialNumbersForRemoval;

    protected $listeners = [
        'loadData' => 'loadlocatorInvoiceData',
    ];

    public function loadlocatorInvoiceData($invoiceNumber, $plantId)
    {
        $this->plantId = $plantId;
        $this->invoiceNumber = $invoiceNumber;

        $this->records = LocatorInvoiceValidation::query()
            ->where('plant_id', $plantId)
            ->where('invoice_number', $invoiceNumber)
            ->where(function ($query) {
                $query->where('scanned_status', '=', '')
                      ->orWhereNull('scanned_status');
            })
            ->orderBy('created_at', 'asc')
            // ->orderByDesc('created_at')
            ->get()
            ->map(function ($record) {
                return [
                    'created_at' => $record->created_at,
                    'created_by' => $record->created_by ?? '',
                    'serial_number' => $record->serial_number,
                    'pallet_number' => $record->pallet_number,
                    'locator_number' => $record->locator_number,
                    'scanned_status' => $record->scanned_status,
                    'scanned_at' => $record->scanned_at,
                    'scanned_by' => $record->scanned_by ?? '',
                ];
            })
            ->toArray();
    }
    public function render()
    {
        return view('livewire.locator-invoice-data-table');
    }
}
