<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $this->transformTemplate(function ($html) {
            // Add name before delivery address
            $html = str_replace(
                '{{livraison_adresse}}',
                '{{#livraison_nom}}{{livraison_nom}}<br />{{/livraison_nom}}{{livraison_adresse}}',
                $html
            );

            // Add name before billing address
            $html = str_replace(
                '{{facturation_adresse}}',
                '{{#facturation_nom}}{{facturation_nom}}<br />{{/facturation_nom}}{{facturation_adresse}}',
                $html
            );

            return $html;
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $this->transformTemplate(function ($html) {
            $html = str_replace(
                '{{#livraison_nom}}{{livraison_nom}}<br />{{/livraison_nom}}{{livraison_adresse}}',
                '{{livraison_adresse}}',
                $html
            );

            $html = str_replace(
                '{{#facturation_nom}}{{facturation_nom}}<br />{{/facturation_nom}}{{facturation_adresse}}',
                '{{facturation_adresse}}',
                $html
            );

            return $html;
        });
    }

    private function transformTemplate(callable $transform): void
    {
        $template = DB::table('mail_templates')
            ->where('mailable', 'App\\Mail\\ConfirmationCommande')
            ->first();

        if (! $template) {
            return;
        }

        $translations = json_decode($template->html_template, true);

        foreach ($translations as $lang => $html) {
            $translations[$lang] = $transform($html);
        }

        DB::table('mail_templates')
            ->where('id', $template->id)
            ->update(['html_template' => json_encode($translations, JSON_UNESCAPED_UNICODE)]);
    }
};
