<?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 = [
            'rezervovane_na_login',
            'rezervovane_na_meno',
            'rezervaciu_vytvoril',
            'rezervacia_poznamka',
            'rezervacia_vytvorena_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->pouzivatel ? $registracia->pouzivatel->login : '',
                        $registracia->pouzivatel ? $registracia->pouzivatel->meno : $registracia->cele_meno,
                        $registracia->vytvoril->meno,
                        $registracia->poznamka,
                        $registracia->updated_at,
                    ]
                );
            }

            fclose($file);
        };
    }
}
