<?php

namespace App\Domains\Event\Actions\GenerateIcalForDeadline;

class GenerateIcalForDeadlineCommand {
    public function __construct(public GenerateIcalForDeadlineRequest $request)
    {
    }
    public function execute(): GenerateIcalForDeadlineResponse
    {
        $event = $this->request->event;

        $deadlineDate = $event->registration_final_end->copy()->subDays(2);
        $dtDate = $deadlineDate->format('Ymd');
        $now = now()->format('Ymd\THis\Z');
        $summary = $this->escapeIcal('Zahlungsfrist: ' . $event->name);
        $description = $this->escapeIcal(
            'Bitte überweise den Teilnahmebeitrag für "' . $event->name . '" bis zu diesem Datum.'
        );

        $icalContent = implode("\r\n", [
                'BEGIN:VCALENDAR',
                'VERSION:2.0',
                'PRODID:-//' . app('tenant')->name . '//Veranstaltungskalender//DE',
                'CALSCALE:GREGORIAN',
                'METHOD:PUBLISH',
                'BEGIN:VEVENT',
                'UID:payment-deadline-' . $event->identifier . '@' . app('tenant')->slug,
                'DTSTAMP:' . $now,
                'DTSTART;VALUE=DATE:' . $dtDate,
                'DTEND;VALUE=DATE:' . $dtDate,
                'SUMMARY:' . $summary,
                'DESCRIPTION:' . $description,
                'END:VEVENT',
                'END:VCALENDAR',
            ]) . "\r\n";

        $filename = 'zahlungsziel-' . $event->name . '.ics';

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

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