<?php

namespace App\Livewire;

use App\Models\InvoiceDataValidation;
use App\Models\InvoiceOutValidation;
use App\Models\PalletValidation;
use Livewire\Component;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\InvoicePendingReasonExport;
use App\Models\Plant;

class InvoicePending extends Component
{

    public $plantId;

    public $invoicePending = [];

    protected $listeners = [
        'loadData' => 'loadInvoiceData',
        'emptyData' => 'loadInvoiceEmptyData',
        'loadData1' => 'exportPendingReason',
    ];

    public function loadInvoiceEmptyData()
    {
        $this->invoicePending = [];
    }

    public function loadInvoiceData($plantId)
    {
        $this->plantId = $plantId;

        $distributions = InvoiceDataValidation::whereNotNull('distribution_channel_desc')
            ->distinct()
            ->pluck('distribution_channel_desc')
            ->filter(fn ($v) => trim($v) != '')
            ->values()
            ->toArray();

        $distributions[] = '';

        $pendingInvoices = collect();

        foreach ($distributions as $distribution) {

            $invoices = InvoiceDataValidation::where('plant_id', $plantId)
                ->where('distribution_channel_desc', $distribution)
                ->select(
                    'id',
                    'document_number',
                    'customer_trade_name',
                    'location',
                    'remark',
                    'created_at',
                    'created_by',
                    'updated_at',
                    'updated_by'
                )
                ->get()
                ->unique('document_number')
                ->filter(fn ($inv) =>
                    !empty($inv->document_number) &&
                    !str_contains($inv->document_number, '-')
                );

            if (trim($distribution) == '') {
                $invoices = $invoices->filter(fn ($inv) =>
                    str_starts_with($inv->document_number, '7')
                );
            }

            if ($invoices->isEmpty()) {
                continue;
            }

            $invoiceNumbers = $invoices->pluck('document_number')
                ->map(fn ($n) => preg_replace('/\s+/', '', strtoupper($n)))
                ->toArray();

            $wentOut = InvoiceOutValidation::whereIn('qr_code', $invoiceNumbers)
                ->distinct()
                ->pluck('qr_code')
                ->map(fn ($n) => preg_replace('/\s+/', '', strtoupper($n)))
                ->toArray();

            $pending = $invoices->filter(function ($inv) use ($wentOut) {
                $doc = preg_replace('/\s+/', '', strtoupper($inv->document_number));
                return !in_array($doc, $wentOut, true);
            });

            $pendingInvoices = $pendingInvoices->merge($pending);
        }

        $plantCode = Plant::find($this->plantId)->code ?? '';

        $this->invoicePending = $pendingInvoices
            ->unique('document_number')
            ->map(function ($record) use ($plantCode) {
                return [
                    'plant_id' => $plantCode ?? '',
                    'document_number' => $record->document_number ?? '',
                    'customer_trade_name' => $record->customer_trade_name ?? '',
                    'location'          => $record->location ?? '',
                    'remark'            => $record->remark ?? '',
                ];
            })
            ->values()
            ->toArray();
    }

    public function exportPendingReason()
    {
        return Excel::download(
            new InvoicePendingReasonExport($this->invoicePending),
            'invoice_pending_reason.xlsx'
        );
    }

    public function render()
    {
        return view('livewire.invoice-pending');
    }
}
