<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Actions;

use Closure;
use Illuminate\Database\Eloquent\Collection;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

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

        return function() use ($registracie, $header) {
            $line = 1;
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            $sheet->fromArray($header, NULL, 'A'.$line++);

            foreach($registracie as $registracia) {
                /** @var \Seka\Portal\Modul\Terminy\Entities\Registracia\Registracia $registracia **/
                $data = [
                    $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->format('d.m.Y H:i:s'),
                ];

                $sheet->fromArray($data, NULL, 'A'.$line++);
            }

            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');
        };
    }
}
