<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Actions;

use Closure;
use Illuminate\Database\Eloquent\Collection;

/**
 * Class RegistrationsCsvFactory
 *
 * @package Seka\Portal\Modul\Terminy\Actions
 */
final class RegistrationsCsvFactory
{
    /**
     * @param \Illuminate\Database\Eloquent\Collection $registracie
     *
     * @return \Closure
     */
    public static function make(Collection $registracie): Closure
    {
        $columns = [
            'pek_cislo',
            'pek_nazov',
            'registracia_meno',
            'registracia_priezvisko',
            'registracia_vytvoril',
            'registracia_poznamka',
            'registracia_datum_a_cas',
        ];

        return function() use ($registracie, $columns) {
            $file = fopen('php://output', 'w');

            fputcsv($file, $columns);

            foreach($registracie as $registracia) {
                /** @var \Seka\Portal\Modul\Terminy\Entities\Registracia\Registracia $registracia **/
                fputcsv(
                    $file,
                    [
                        $registracia->pracovisko->kod,
                        $registracia->pracovisko->nazov,
                        $registracia->pouzivatel ? $registracia->pouzivatel->meno : $registracia->meno,
                        $registracia->pouzivatel ? $registracia->pouzivatel->priezvisko : $registracia->priezvisko,
                        $registracia->vytvoril->cele_meno,
                        $registracia->poznamka,
                        $registracia->updated_at,
                    ]
                );
            }

            fclose($file);
        };
    }
}
