<?php

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

return new class extends Migration
{
    private $oldSrc = '/storage/photos/shares/logo.png';

    private $newSrc = 'https://boutique.jardinenvie.com/img/logo.png';

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $this->replaceLogoInAllTemplates($this->oldSrc, $this->newSrc);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $this->replaceLogoInAllTemplates($this->newSrc, $this->oldSrc);
    }

    private function replaceLogoInAllTemplates(string $from, string $to): void
    {
        $templates = DB::table('mail_templates')->get();

        foreach ($templates as $template) {
            $translations = json_decode($template->html_template, true);

            if (! $translations) {
                continue;
            }

            $changed = false;

            foreach ($translations as $lang => $html) {
                $updated = str_replace($from, $to, $html);
                if ($updated !== $html) {
                    $translations[$lang] = $updated;
                    $changed = true;
                }
            }

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