<?php

namespace App\Helpers;

use Illuminate\Support\Facades\Log;
use Iterator;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception;
use League\Csv\InvalidArgument;
use League\Csv\Reader;
use League\Csv\Writer;

class CsvHelper
{
    public static function getRecords($filePath): Iterator {
        $csv = Reader::createFromPath(resource_path($filePath));
        try {
            $csv->setDelimiter("|");
            $csv->setEnclosure("'");
            $csv->setHeaderOffset(0);
            return $csv->getRecords();
        } catch (InvalidArgument|Exception $e) {
            Log::error($e->getMessage());
            return null;
        }
    }

    public static function generarCsv($filePath, $contenido, $headers = null): void
    {
        try {
            $writer = Writer::createFromPath(resource_path($filePath), 'w');
            if ($headers) {
                $writer->insertOne($headers);
            }
            $writer->insertAll($contenido);
        } catch (CannotInsertRecord $e) {
            Log::error($e->getMessage(), $e->getTrace());
        }
    }
}