<?php
namespace Components\Models;

// Ensure legacy constants are defined
if (defined('MH_DIR_FS_CATALOG') && defined('MH_ROOT_PATH')) {
    $legacyFile = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter/classes/mb_newsletter_categories.php';
    if (is_file($legacyFile)) {
        require_once $legacyFile;
    }
}

/**
 * Newsletter Topic descriptions.
 */
class TopicDescription extends BaseModel
{
    protected static string $table = 'TABLE_MAILBEEZ_NEWSLETTER_CATEGORIES_DESCRIPTION';
    protected static string $primaryKey = 'newsletter_categories_id';

    /**
     * Load all translations for a given topic id, keyed by language_id.
     * @return array<int, array> Map of language_id => row
     */
    public static function forTopic(int $topicId): array
    {
        if (self::isDev()) return [];
        $topicId = (int)$topicId;
        if ($topicId <= 0) return [];
        $sql = "SELECT * FROM " . static::table() . " WHERE newsletter_categories_id = " . $topicId . " ORDER BY language_id";
        $q = \mh_db_query($sql);
        $map = [];
        while ($row = \mh_db_fetch_array($q)) {
            $lid = (int)($row['language_id'] ?? 0);
            if ($lid > 0) { $map[$lid] = $row; }
        }
        \mh_db_free_result($q);
        return $map;
    }

    /**
     * Upsert translations for a topic.
     */
    public static function syncForTopic(int $topicId, array $translations): void
    {
        if (self::isDev()) return;
        $topicId = (int)$topicId;
        if ($topicId <= 0) return;
        foreach ($translations as $lid => $vals) {
            $lid = (int)$lid;
            if ($lid <= 0) continue;
            $name = isset($vals['newsletter_categories_name']) ? (string)$vals['newsletter_categories_name'] : '';
            $desc = isset($vals['newsletter_categories_description']) ? (string)$vals['newsletter_categories_description'] : '';

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

            $data = [
                'newsletter_categories_id' => $topicId,
                'language_id' => $lid,
                'newsletter_categories_name' => $name,
                'newsletter_categories_description' => $desc,
            ];
            if ($exists) {
                $update = $data;
                unset($update['newsletter_categories_id'], $update['language_id']);
                \mh_db_perform(static::table(), $update, 'update', "newsletter_categories_id = {$topicId} AND language_id = {$lid}");
            } else {
                \mh_db_perform(static::table(), $data);
            }
        }
    }
}
