<?php
namespace Components\Models;

class CategoryDescription extends BaseModel
{
    protected static string $table = 'categories_description';
    protected static string $primaryKey = 'categories_id';

    /**
     * Load all category names for one category, keyed by language id.
     *
     * @return array<int, array<string, mixed>>
     */
    public static function forCategory(int $categoryId): array
    {
        if (self::isDev() || $categoryId <= 0) {
            return [];
        }

        $sql = "SELECT * FROM " . static::table() . " WHERE categories_id = " . (int)$categoryId . " ORDER BY language_id";
        $q = \mh_db_query($sql);

        $items = [];
        while ($row = \mh_db_fetch_array($q)) {
            $lid = (int)($row['language_id'] ?? 0);
            if ($lid > 0) {
                $items[$lid] = $row;
            }
        }
        \mh_db_free_result($q);

        return $items;
    }

    /**
     * Upsert per-language category name rows.
     *
     * @param array<int|string, mixed> $byLanguage
     */
    public static function syncForCategory(int $categoryId, array $byLanguage): void
    {
        if (self::isDev() || $categoryId <= 0 || empty($byLanguage)) {
            return;
        }

        foreach ($byLanguage as $languageId => $value) {
            $lid = (int)$languageId;
            if ($lid <= 0) {
                continue;
            }

            if (is_array($value)) {
                $name = trim((string)($value['categories_name'] ?? ''));
            } else {
                $name = trim((string)$value);
            }
            if ($name === '') {
                continue;
            }

            $existsQ = \mh_db_query(
                "SELECT categories_id FROM " . static::table() .
                " WHERE categories_id = " . (int)$categoryId .
                " AND language_id = " . $lid .
                " LIMIT 1"
            );
            $exists = \mh_db_fetch_array($existsQ);
            \mh_db_free_result($existsQ);

            if ($exists) {
                \mh_db_perform(
                    static::table(),
                    ['categories_name' => $name],
                    'update',
                    "categories_id = " . (int)$categoryId . " AND language_id = " . $lid
                );
            } else {
                \mh_db_perform(static::table(), [
                    'categories_id' => (int)$categoryId,
                    'language_id' => $lid,
                    'categories_name' => $name,
                ], 'insert');
            }
        }
    }
}
