<?php
namespace Components\Models;

class ProductDescription extends BaseModel
{
    protected static string $table = 'TABLE_PRODUCTS_DESCRIPTION';
    protected static string $primaryKey = 'products_id';

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

        $sql = "SELECT * FROM " . static::table() . " WHERE products_id = " . (int)$productId . " 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 product description rows.
     *
     * @param array<int|string, array<string, mixed>> $byLanguage
     */
    public static function syncForProduct(int $productId, array $byLanguage): void
    {
        if (self::isDev() || $productId <= 0 || empty($byLanguage)) {
            return;
        }

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

            $name = trim((string)($values['products_name'] ?? ''));
            $description = (string)($values['products_description'] ?? '');
            $url = trim((string)($values['products_url'] ?? ''));

            if ($name === '' && trim($description) === '' && $url === '') {
                continue;
            }

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

            $payload = [
                'products_id' => (int)$productId,
                'language_id' => $lid,
                'products_name' => $name,
                'products_description' => $description,
                'products_url' => $url,
            ];

            if ($exists) {
                \mh_db_perform(
                    static::table(),
                    [
                        'products_name' => $name,
                        'products_description' => $description,
                        'products_url' => $url,
                    ],
                    'update',
                    "products_id = " . (int)$productId . " AND language_id = " . $lid
                );
            } else {
                \mh_db_perform(static::table(), $payload, 'insert');
            }
        }
    }
}
