<?php

namespace Modules\Admin\App\Imports;

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

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

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

            $requestArray = [
                'c_uso_cfdi' => $row[0],
                'descripcion' => $row[1],
                'aplica_para_tipo_persona_fisica' => $row[2],
                'aplica_para_tipo_persona_moral' => $row[3],
                'fecha_inicio_de_vigencia' => $row[4] ?
                    Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[4])) :
                    null,
                'fecha_fin_de_vigencia' => $row[5] ?
                    Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row[5])) :
                    null,
                'regimen_fiscal_receptor' => $row[6],
            ];

            $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_uso_cfdi')->upsert(
                $batchData,
                [
                    'c_uso_cfdi',
                ],
                [
                    'descripcion',
                    'aplica_para_tipo_persona_fisica',
                    'aplica_para_tipo_persona_moral',
                    'fecha_inicio_de_vigencia',
                    'fecha_fin_de_vigencia',
                    'regimen_fiscal_receptor',
                ]
            );
        } catch (\Exception $e) {
            echo "Error in batch: " . $e->getMessage() . "\n";

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