<?php

namespace App\Imports;

use App\Models\InvoiceDataValidation;
use App\Models\Plant;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class InvoicePendingReasonImport implements ToCollection
{
    /**
    * @param Collection $collection
    */

    public array $errors = [];

    public array $missingPlantCodes = [];
    public array $missingDocNo = [];
    public array $plantCodeEmpty = [];
    public array $docNoEmpty = [];
    public array $remarkEmpty = [];

    public array $duplicateExcelDocs = [];

    private array $seenExcelKeys = [];

    public array $validRows = [];

    public function collection(Collection $collection)
    {
        $rows = $collection;
        // foreach ($rows->skip(1) as $row) {

        //     $plantCode        = trim($row[0] ?? '');
        //     $documentNumber = trim($row[1] ?? '');
        //     $remark         = trim($row[2] ?? '');

        //     if (! $plantCode || ! $documentNumber || ! $remark) {
        //         continue;
        //     }

        //     $plantId = Plant::where('code', $plantCode)->value('id');

        //     InvoiceDataValidation::where('plant_id', $plantId)
        //         ->where('document_number', $documentNumber)
        //         ->update([
        //             'remark'     => $remark,
        //             'updated_at' => now(),
        //         ]);
        // }

        foreach ($rows->skip(1) as $index => $row) {

            $rowNo = $index + 2;

            $plantCode      = trim($row[0] ?? '');
            $documentNumber = trim($row[1] ?? '');
            $remark         = trim($row[2] ?? '');

            if (! $plantCode) {
                $this->plantCodeEmpty[] = [
                    'row' => $rowNo,
                    'reason' => "Plant Code can't be empty!",
                ];
                continue;
            }
            else if (! $documentNumber) {
                $this->docNoEmpty[] = [
                    'row' => $rowNo,
                    'reason' => "Document number can't be empty!",
                ];
                continue;
            }

            //Excel-level duplicate check
            $key = $plantCode . '|' . $documentNumber;

            if (isset($this->seenExcelKeys[$key])) {
                $this->duplicateExcelDocs[$key][] = $rowNo;

                $this->errors[] = [
                    'row' => $rowNo,
                    'reason' => "Duplicate Document Number in Excel ({$plantCode} - {$documentNumber})",
                ];
                continue;
            }

            $this->seenExcelKeys[$key] = true;

            $plantId = Plant::where('code', $plantCode)->value('id');

            if (! $plantId) {
                $this->missingPlantCodes[$plantCode] = true;

                $this->errors[] = [
                    'row' => $rowNo,
                    'reason' => "Plant code not found: {$plantCode}",
                ];
                continue;
            }

            $invoiceExists = InvoiceDataValidation::where('plant_id', $plantId)
                ->where('document_number', $documentNumber)
                ->first();

            if (! $invoiceExists) {
                $this->missingDocNo[$documentNumber] = true;

                $this->errors[] = [
                    'row' => $rowNo,
                    'reason' => "Document number not found: {$documentNumber}",
                ];
                continue;
            }

            // dd($row['document_number'], bin2hex($row['document_number']));

            $this->validRows[] = [
                'plant_id' => $plantId,
                'document_number' => $documentNumber,
                'remark' => $remark,
            ];
        }

    }
}
