<?php

namespace App\Services\Registries;

use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;

class TechnicalCertificatesImportService extends RegistryImportService {

    public function test() {
        var_dump($this->registry);
    }

    public function import() {
        $nodes = $this->dom->find('table tbody tr')->toArray();
        foreach ($nodes as $node) {
            list($product_name, $product_purpose, $producer, $links, $active_since, $active_till) = $node->find('td')->toArray();
            $number = null;
            $asset = null;
            $conclusionAsset = null;
            $active_since = $active_since->text ? Date::create($active_since->text) : null;
            $active_till = $active_till->text ? Date::create($active_till->text) : null;
            foreach ($links->find('a')->toArray() as $link) {
                if (trim($link->text) === 'Техническое заключение') {
                    $conclusionAsset = $this->download($link->href, 'registries/ts/conclusions');
                } else {
                    $number = $link->text;
                    $asset = $this->download($link->href, 'registries/ts/certificates');
                }
            }
            if (!$number) $number = trim($links->text);
            $entry = $this->registry->entries()->firstOrCreate(['name' => trim($product_name->text), 'category_id' => 0]);
            $entry->update(['number' => $number, 'asset_id' => $asset->id ?? null, 'active_since' => $active_since, 'active_till' => $active_till]);
            $data = ['developer-name' => Str::limit(Str::replace('&quot;', '"', trim($producer->text)), 495), 'product-purpose' => trim($product_purpose->text), 'technical-conclusion' => $conclusionAsset];
            $entry->properties->setValues($data);
        }
    }


}