<?php

namespace App\Domains\Event\Actions\GenerateIcal;

class GenerateIcalCommand
{
    public function __construct(public GenerateIcalRequest $request)
    {
    }

    public function execute(): GenerateIcalResponse
    {
        $participant = $this->request->participant;
        $event = $participant->event;

        $uid = $participant->identifier . '@' . app('tenant')->slug;
        $dtStart = $event->start_date->format('Ymd');
        $dtEnd = $event->end_date->copy()->addDay()->format('Ymd');
        $now = now()->format('Ymd\THis\Z');
        $summary = $this->escapeIcal($event->name);
        $location = $this->escapeIcal(trim($event->postal_code . ' ' . $event->location));
        $description = $this->escapeIcal('Teilnahme als: ' . $participant->getOfficialName());

        $icalContent = implode("\r\n", [
                'BEGIN:VCALENDAR',
                'VERSION:2.0',
                'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE',
                'CALSCALE:GREGORIAN',
                'METHOD:PUBLISH',
                'BEGIN:VEVENT',
                'UID:' . $uid,
                'DTSTAMP:' . $now,
                'DTSTART;VALUE=DATE:' . $dtStart,
                'DTEND;VALUE=DATE:' . $dtEnd,
                'SUMMARY:' . $summary,
                'LOCATION:' . $location,
                'DESCRIPTION:' . $description,
                'END:VEVENT',
                'END:VCALENDAR',
            ]) . "\r\n";

        $filename = 'veranstaltung-' . $participant->event()->first()->name . '.ics';

        return new GenerateIcalResponse($icalContent, $filename);
    }

    private function escapeIcal(string $value): string
    {
        return str_replace(
            ['\\', ';', ',', "\n"],
            ['\\\\', '\\;', '\\,', '\\n'],
            $value
        );
    }
}
