<?php
namespace Components\Models;

class ReviewDescription extends BaseModel
{
    protected static string $table = 'TABLE_REVIEWS_DESCRIPTION';
    protected static string $primaryKey = 'reviews_id';

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

        $sql = "SELECT * FROM " . static::table() . " WHERE reviews_id = " . (int)$reviewId;
        $q = \mh_db_query($sql);

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

        return $items;
    }

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

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

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

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

            $payload = [
                'reviews_id' => (int)$reviewId,
                'languages_id' => $lid,
                'reviews_text' => $value,
            ];

            if ($exists) {
                \mh_db_perform(
                    static::table(),
                    ['reviews_text' => $value],
                    'update',
                    "reviews_id = " . (int)$reviewId . " AND languages_id = " . $lid
                );
            } else {
                \mh_db_perform(static::table(), $payload, 'insert');
            }
        }
    }
}
