<?php
namespace Components\Models;

/**
 * Manufacturers per-language data model.
 */
class ManufacturerInfo extends BaseModel
{
    protected static string $table = 'manufacturers_info';
    protected static string $primaryKey = 'manufacturers_id';

    /**
     * Load all info rows for one manufacturer, keyed by language id.
     *
     * @return array<int, array>
     */
    public static function forManufacturer(int $manufacturerId): array
    {
        if (self::isDev()) return [];

        $manufacturerId = (int)$manufacturerId;
        if ($manufacturerId <= 0) {
            return [];
        }

        $sql = "SELECT * FROM " . static::table() . " WHERE manufacturers_id = " . $manufacturerId . " ORDER BY languages_id";
        $q = \mh_db_query($sql);
        $map = [];
        while ($row = \mh_db_fetch_array($q)) {
            $languageId = (int)($row['languages_id'] ?? 0);
            if ($languageId > 0) {
                $map[$languageId] = $row;
            }
        }
        \mh_db_free_result($q);

        return $map;
    }

    /**
     * Upsert per-language manufacturer URLs.
     */
    public static function syncForManufacturer(int $manufacturerId, array $urls): void
    {
        if (self::isDev()) return;

        $manufacturerId = (int)$manufacturerId;
        if ($manufacturerId <= 0) {
            return;
        }

        foreach ($urls as $languageId => $values) {
            $languageId = (int)$languageId;
            if ($languageId <= 0) {
                continue;
            }

            $url = trim((string)($values['manufacturers_url'] ?? ''));
            if ($url === '') {
                continue;
            }

            $checkSql = "SELECT COUNT(*) AS c FROM " . static::table() . " WHERE manufacturers_id = {$manufacturerId} AND languages_id = {$languageId}";
            $q = \mh_db_query($checkSql);
            $row = \mh_db_fetch_array($q);
            \mh_db_free_result($q);
            $exists = (int)($row['c'] ?? 0) > 0;

            $data = [
                'manufacturers_id' => $manufacturerId,
                'languages_id' => $languageId,
                'manufacturers_url' => $url,
                'url_clicked' => 0,
                'date_last_click' => null,
            ];

            if ($exists) {
                $update = ['manufacturers_url' => $url];
                \mh_db_perform(static::table(), $update, 'update', "manufacturers_id = {$manufacturerId} AND languages_id = {$languageId}");
            } else {
                \mh_db_perform(static::table(), $data);
            }
        }
    }
}
