<?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 {
        $previousNames = $client->previousNames
            ->map(fn($n) => $n->fullName)
            ->filter();

        $alsoKnownAs     = $previousNames->join(', ');
        $nameInCare      = $previousNames->join(', ');
        $legalNameChange = $previousNames->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,
            '%name_in_care%'      => $nameInCare,
            '%client_legal_name_change%' => $legalNameChange,
            '%client_address%'           => $client->currentAddress?->getFullAddress(),
            '%care_settings%'            => $careSettingsValue,
            '%approx_dates%'             => $approxDatesValue,
            '%approximate_dates%'        => $approxDatesValue,
            '%client_reference%'         => $client->displayId,
        ], $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>",
        ];
    }
}