<?php

namespace App\Services;

use App\Models\Client\Client;
use App\Models\Dsar\DsarType;

class PlaceholderService {

    public function replace(string $content, array $placeholders): string {
        return str_replace(array_keys($placeholders), array_values($placeholders), $content);
    }

    public function forDsar(DsarType $type, Client $client, array $extra = []): array {
        $alsoKnownAs = $client->previousNames
            ->map(fn($n) => $n->fullName)
            ->filter()
            ->join(', ');

        // Load care settings with their institutions for the %care_settings% / %approx_dates% placeholders
        $careSettings = $client->claim
            ?->careSettings()->with('institution')->get()
            ?? collect();

        [$careSettingsValue, $approxDatesValue] = $this->buildCareSettingPlaceholders($careSettings);

        return array_merge([
            '%client_name%'       => $client->fullName,
            '%client_dob%'     => $client->date_of_birth?->formatted('d/m/Y') ?? '',
            '%client_also_known_as%'     => $alsoKnownAs,
            '%care_settings%'     => $careSettingsValue,
            '%approx_dates%'      => $approxDatesValue,
            '%approximate_dates%' => $approxDatesValue,
        ], $extra);
    }

    /**
     * Build parallel HTML lists for %care_settings% and %approx_dates%.
     * Returns [careSettingsHtml, approxDatesHtml].
     */
    private function buildCareSettingPlaceholders(\Illuminate\Support\Collection $careSettings): array {
        if ($careSettings->isEmpty()) {
            return ['', ''];
        }

        $settingItems = '';
        $dateItems    = '';

        foreach ($careSettings as $cs) {
            $name  = e($cs->institution?->display_name ?? 'Unknown');
            $dates = e($cs->dates ?? 'Unknown');

            $settingItems .= "<li>{$name}</li>";
            $dateItems    .= "<li>{$name}: {$dates}</li>";
        }

        return [
            "<ul>{$settingItems}</ul>",
            "<ul>{$dateItems}</ul>",
        ];
    }
}
