<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Terminy\Http\Controllers\Backend\Udalosti;

use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Seka\Portal\Modul\Terminy\Actions\RegistrationsXlsxFactory;
use Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost;
use Seka\Portal\Modul\Terminy\Http\Controllers\Controller;
use Symfony\Component\HttpFoundation\StreamedResponse;

/**
 * Class RegistracieUdalostiController
 *
 * @package Seka\Portal\Modul\Terminy\Http\Controllers\Backend\Udalosti
 */
final class RegistracieUdalostiController extends Controller
{
    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function index(int $udalostId): View
    {
        /** @var \Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost $udalost */
        $udalost = Udalost::withTrashed()->findOrFail($udalostId);
        $pracoviska = \App\Models\Pracovisko\Pracovisko::query()->orderBy('kod')->get();
        $pocetRegistracii = $udalost->registracie()->count();

        return view(
            'Terminy::pages.backend.udalosti.registracie.index',
            compact('udalost', 'pracoviska', 'pocetRegistracii'),
        );
    }

    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function delete(int $udalostId, int $registraciaId): RedirectResponse
    {
        /** @var \Seka\Portal\Modul\Terminy\Entities\Udalost\Udalost $udalost */
        $udalost = Udalost::withTrashed()->findOrFail($udalostId);
        $registracia = $udalost->registracie()->findOrFail($registraciaId);
        $registracia->delete();

        flash()->overlay('Registrácia bola úspešne zrušená')->success();

        return redirect()->back();
    }

    /**
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     */
    public function export(RegistrationsXlsxFactory $xlsxFactory, int $udalostId): StreamedResponse
    {
        /** @var Udalost $udalost */
        $udalost = Udalost::query()
            ->with('registracie.pouzivatel')
            ->findOrFail($udalostId);

        $filename = mb_strtoupper(
            sprintf(
                '%s_%s_registracie.xlsx',
                $udalost->druh->value,
                $udalost->datum_od->format('Y-m-d_H-i'),
            ),
        );

        $headers = [
            "Content-type" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "Content-Disposition" => "attachment; filename=$filename",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0",
        ];

        $callback = $xlsxFactory::make($udalost->registracie);

        return response()->stream($callback, 200, $headers);
    }
}
