<?php

namespace App\Livewire;

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

class InvoiceReworkDataTable extends Component
{
    public $plantId;

    public $invoiceNumber;

    public $palletNumber;

    public $reworkTyp;

    public bool $isOpen = false;

    public $records = [];

    public $showConfirmationModal = false;

    public $invoiceNo;

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

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

        if ($reworkType == 'invoice')
        {
            $this->records = LocatorInvoiceValidation::query()->where('plant_id', $plantId)->where('invoice_number', $invoiceNumber)->orderBy('created_at', 'asc')->get()// ->orderByDesc('created_at')
                ->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();
        }
        else if ($reworkType == 'pallet')
        {
            $this->records = PalletValidation::query()->where('plant_id', $plantId)->where('pallet_number', $palletNumber)->orderBy('scanned_at', 'asc')->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();
        }
        else
        {
            $this->records = [];
        }
    }
    public function render()
    {
        return view('livewire.invoice-rework-data-table');
    }
}
