<?php

namespace Modules\Admin\App\Imports;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class SATColoniaImport implements ToCollection
{
    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        $batchSize = 1000;
        $batchData = [];
        $processedRows = 0;

        foreach ($collection as $key => $row) {
            if ($key < 5 || !$row[1]) {
                continue;
            }

            $requestArray = [
                'c_colonia' => $row[0],
                'c_codigo_postal' => $row[1],
                'nombre_del_asentamiento' => $row[2],
            ];

            $batchData[] = $requestArray;
            $processedRows++;

            if (count($batchData) >= $batchSize) {
                $this->insertBatch($batchData);
                $batchData = [];
            }
        }

        if (!empty($batchData)) {
            $this->insertBatch($batchData);
        }

        echo "\n\033[32mImport completed: Processed $processedRows rows.\033[0m\n";
    }

    private function insertBatch(array $batchData)
    {
        try {
            DB::table('sat_colonia')->upsert(
                $batchData,
                [
                    'c_colonia',
                    'c_codigo_postal',
                ],
                [
                    'nombre_del_asentamiento',
                ]
            );
        } catch (\Exception $e) {
            echo "Error in batch: " . $e->getMessage() . "\n";

            foreach ($batchData as $row) {
                echo "Row data: " . json_encode($row) . "\n";
            }
        }
    }
}
