<?php


namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Entry;
use Illuminate\Support\Facades\Log;

use function Livewire\str;

class RemediateBlogS3Images extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:remediate-blog-s3-images';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $stringToFind = 'src="http://127.0.0.1:8000/storage';
        $stringToReplace = 'src="https://your-s3-bucket-here/yours-site-static-media-dir-here';

        Log::info('RemediateBlogS3Images command executed.');
        foreach (Entry::all() as $entry) {

            $this->info('Entry ID: ' . $entry->id);
            if (str_contains($entry->content, $stringToFind)) {
                $this->info(' - Found occurrence in entry ID: ' . $entry->id);
                // Extract all image srcs that match the pattern
                preg_match_all('/src=\"http:\/\/127.0.0.1:8000\/storage([^\"]*)/', $entry->content, $matches);
                if (!empty($matches[0])) {
                    foreach ($matches[0] as $i => $foundUrl) {
                        $this->info('   - Found image src: ' . $foundUrl);
                        // Compute the replacement for this specific image
                        $relativePath = $matches[1][$i] ?? '';
                        $newUrl = 'src="https://your-s3-bucket-here/yours-site-static-media-dir-here' . $relativePath;
                        $this->info('   - Will replace with: ' . $newUrl);
                    }
                }
                $updatedContent = \str_replace($stringToFind, $stringToReplace, $entry->content);
                // uncomment the following when your sure about the changes
                // $entry->content = $updatedContent;
                // $entry->save();
                // $this->info(' - Updated entry ID: ' . $entry->id);
            }
        }
    }
}
