<?php

declare(strict_types=1);

namespace App\Modules\Messaging;

/**
 * MessageTemplateService — Replaces placeholders, renders event parameters
 * dynamically, and composes personalized guest messages.
 *
 * No SQL database queries, no HTML generation.
 *
 * @package Inveetaire
 * @ref     PILOT-006
 */
class MessageTemplateService
{
    /**
     * Compile template placeholders into a personalized message string.
     *
     * @param string     $templateText
     * @param array      $guest
     * @param array      $workspace
     * @param array|null $invitation
     * @param array      $allEvents
     * @param array      $assignedEventIds
     * @param string     $personalUrl
     * @return string
     */
    public function compileMessage(
        string $templateText,
        array $guest,
        array $workspace,
        ?array $invitation,
        array $allEvents,
        array $assignedEventIds,
        string $personalUrl
    ): string {
        // 1. Filter and sort assigned events for this guest
        $assignedEvents = [];
        foreach ($allEvents as $event) {
            // If explicit assigned events list is empty, default to all events
            if (empty($assignedEventIds) || in_array((int) $event['id'], $assignedEventIds, true)) {
                $assignedEvents[] = $event;
            }
        }

        // Sort chronologically by date
        usort($assignedEvents, function (array $a, array $b) {
            return strtotime($a['event_date']) <=> strtotime($b['event_date']);
        });

        // 2. Build Holy and Reception strings dynamically
        $holyText = '';
        $receptionText = '';

        foreach ($assignedEvents as $event) {
            $nameLower = strtolower($event['event_name']);
            $isHoly = (strpos($nameLower, 'holy') !== false) || (strpos($nameLower, 'akad') !== false) || (strpos($nameLower, 'nikah') !== false) || (strpos($nameLower, 'ceremony') !== false);
            $isReception = (strpos($nameLower, 'reception') !== false) || (strpos($nameLower, 'resepsi') !== false) || (bool) $event['is_primary'];

            $evtDate = new \DateTime($event['event_date']);
            $dateStr = $evtDate->format('Y-m-d');
            $timeStr = $evtDate->format('H:i');
            $venueStr = $event['venue_name'];
            if (!empty($event['venue_address'])) {
                $venueStr .= ' (' . $event['venue_address'] . ')';
            }

            if ($isHoly && $holyText === '') {
                $holyText = "Holy Matrimony:\nDate: {$dateStr}\nTime: {$timeStr} UTC\nVenue: {$venueStr}";
            }
            if ($isReception && $receptionText === '') {
                $receptionText = "Reception:\nDate: {$dateStr}\nTime: {$timeStr} UTC\nVenue: {$venueStr}";
            }
        }

        // 3. Compile display names
        $groom = $invitation['groom_display_name'] ?? $workspace['groom_name'];
        $bride = $invitation['bride_display_name'] ?? $workspace['bride_name'];
        $couple = "{$groom} & {$bride}";

        $wedDate = new \DateTime($workspace['wedding_date']);
        $weddingDateFormatted = $wedDate->format('l, d F Y');

        $replacements = [
            '{{guest_name}}'            => $guest['full_name'],
            '{{bride_name}}'            => $bride,
            '{{groom_name}}'            => $groom,
            '{{couple_name}}'           => $couple,
            '{{invitation_url}}'        => $personalUrl,
            '{{holy_information}}'      => $holyText,
            '{{reception_information}}' => $receptionText,
            '{{wedding_date}}'          => $weddingDateFormatted,
            '{{workspace_name}}'        => $workspace['slug']
        ];

        // 4. Overwrite recognized placeholders only
        $message = $templateText;
        foreach ($replacements as $key => $value) {
            $message = str_replace($key, $value, $message);
        }

        return $message;
    }
}
