<?php
namespace Components\Models;

/**
 * Manufacturers model.
 */
class Manufacturer extends BaseModel
{
    protected static string $table = 'manufacturers';
    protected static string $primaryKey = 'manufacturers_id';
    protected static string $blueprint = 'manufacturer.yaml';

    public static function isReadOnly(): bool
    {
        return true;
    }

    public function validateBeforeSave(array $data, array $submitted = [], array $context = []): array
    {
        $message = 'Manufacturers are read-only.';
        if (function_exists('mh_lng')) {
            $message = (string)mh_lng('UI_MANUFACTURER_READ_ONLY', $message);
        }

        return [
            'manufacturers_name' => [$message],
        ];
    }

    /**
     * @return array<Product>
     */
    public function products(): array
    {
        return $this->hasMany(Product::class, 'manufacturers_id', static::pk());
    }

    public static function getNewDefaults(): array
    {
        return [
            'manufacturers_name' => '',
            'manufacturers_image' => '',
            'manufacturers_url' => [],
        ];
    }

    public function augmentFormValues(array $values): array
    {
        $id = (int)($values[static::pk()] ?? ($this->{static::pk()} ?? 0));
        if ($id > 0) {
            $rows = ManufacturerInfo::forManufacturer($id);
            $urls = [];
            foreach ($rows as $languageId => $row) {
                $urls[(int)$languageId] = (string)($row['manufacturers_url'] ?? '');
            }
            $values['manufacturers_url'] = $urls;
        } else {
            $values['manufacturers_url'] = [];
        }

        return $values;
    }

    protected function filterAttributesForSave(array $data): array
    {
        unset($data['manufacturers_url']);

        if (array_key_exists('manufacturers_name', $data)) {
            $data['manufacturers_name'] = trim((string)$data['manufacturers_name']);
        }

        if (array_key_exists('manufacturers_image', $data)) {
            $image = trim((string)$data['manufacturers_image']);
            $data['manufacturers_image'] = ($image === '') ? null : $image;
        }

        foreach (['date_added', 'last_modified'] as $dateColumn) {
            if (array_key_exists($dateColumn, $data) && trim((string)$data[$dateColumn]) === '') {
                $data[$dateColumn] = null;
            }
        }

        return parent::filterAttributesForSave($data);
    }

    public function afterSave(array $post): void
    {
        if (static::isReadOnly()) {
            return;
        }

        $id = (int)($this->{static::pk()} ?? 0);
        if ($id <= 0) {
            return;
        }

        $urls = $post['manufacturers_url'] ?? [];
        if (!is_array($urls)) {
            $languageId = (int)($_SESSION['languages_id'] ?? 1);
            $urls = [$languageId => (string)$urls];
        }

        $map = [];
        foreach ($urls as $languageId => $url) {
            $languageId = (int)$languageId;
            if ($languageId <= 0) {
                continue;
            }

            $url = trim((string)$url);
            if ($url === '') {
                continue;
            }

            $map[$languageId] = [
                'manufacturers_url' => $url,
            ];
        }

        if (!empty($map)) {
            ManufacturerInfo::syncForManufacturer($id, $map);
        }
    }
}
