<?php

namespace App\Services\Registries;

use App\Models\Objects\Values\HtmlValue;
use App\Models\Objects\Values\StringValue;
use App\Models\Objects\Values\TextValue;
use App\Models\Publications\Publication;
use App\Models\Registries\Entry;
use Illuminate\Support\Str;

class CleanerService {
    public function __construct() {
    }

    public function clean() {
        //$this->cleanPublications();
        //$this->cleanRegistryEntries();
        $this->cleanStringValues();
        $this->cleanTextValues();
        $this->cleanHtmlValues();
    }

    public function cleanPublications() {
        $items = Publication::all();
        foreach ($items as $item) {
            $item->update(['name' => $this->cleanString($item->name), 'excerpt' => $this->cleanString($item->excerpt)]);
        }
    }

    public function cleanRegistryEntries() {
        $items = Entry::all();
        foreach ($items as $item) {
            $item->update(['name' => $this->cleanString($item->name)]);
        }
    }

    public function cleanStringValues() {
        $items = StringValue::all();
        foreach ($items as $item) {
            $item->update(['value' => $this->cleanString($item->value)]);
        }
    }
    public function cleanTextValues() {
        $items = TextValue::all();
        foreach ($items as $item) {
            $item->update(['value' => $this->cleanString($item->value)]);
        }
    }
    public function cleanHtmlValues() {
        $items = HtmlValue::all();
        foreach ($items as $item) {
            $item->update(['value' => $this->cleanString($item->value)]);
        }
    }


    public function cleanString(?string $string): ?string {
        if ($string) {
            $string = Str::replace('&quot;', '"', $string);
            $string = Str::replace('&#40', '«', $string);
            $string = Str::replace('&#41', '»', $string);
            $string = trim(Str::replace('(***)', '', $string));
        }
        return $string;
    }

}