<?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);

        // Section 7a "Further Information" care-background fields
        $fi = $client->claim?->furtherInformation;
        $addressPriorToCare = collect([
            $fi?->address_prior_line_1,
            $fi?->address_prior_line_2,
            $fi?->address_prior_line_3,
            $fi?->address_prior_postcode,
        ])->filter()->join(', ');

        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,
            '%name_before_care%'         => $fi?->name_before_care ?? '',
            '%mothers_name%'             => $fi?->mothers_name ?? '',
            '%fathers_name%'             => $fi?->fathers_name ?? '',
            '%address_prior_to_care%'    => $addressPriorToCare,
            '%client_address%'           => $client->currentAddress?->getFullAddress(),
            '%care_settings%'            => $careSettingsValue,
            '%approx_dates%'             => $approxDatesValue,
            '%approximate_dates%'        => $approxDatesValue,
            '%client_reference%'         => $client->displayId,
            '%dsar_reference%'           => $extra['dsar_reference'] ?? '',
        ], $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>",
        ];
    }
}