<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Actions;

use Closure;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Collection as BasicCollection;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Seka\Portal\Modul\Terminy\Entities\Registracia\ValueObjects\ZoznamZvolenychMoznostiUdalostiValueObject;
use Seka\Portal\Modul\Terminy\Entities\Udalost\ValueObjects\MoznostUdalostiValueObject;

/**
 * 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',
            'zvolene_moznosti_registracie',
        ];

        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 ?: null,
                    $registracia->updated_at->format('d.m.Y H:i:s'),
                    self::makeTextFromOptions($registracia->moznosti),
                ];

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

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

    private static function makeTextFromOptions(BasicCollection $moznosti): string
    {
        $data = '';

        $moznosti->each(function (ZoznamZvolenychMoznostiUdalostiValueObject $list) use (&$data) {
            $sub = [];

            collect($list->getMoznosti())->each(function (MoznostUdalostiValueObject $option) use (&$sub) {
                $sub[] = $option->getPopis();
            });

            $data .= $list->getNazov() . ':' . implode(',', $sub) .';';
        });

        return $data;
    }
}
