<?php
namespace Components\Models;

/**
 * Coupon descriptions (common across all platforms)
 */
class CouponDescription extends BaseModel
{
    protected static string $table = 'TABLE_COUPONS_DESCRIPTION';
    // Note: real schema uses a composite key (coupon_id, language_id).
    // For simplicity, we keep coupon_id as the primary key for lookups; ensure language_id
    // is provided in attributes for inserts.
    protected static string $primaryKey = 'coupon_id';

    protected static string $blueprint = 'coupon_description.yaml';

    /**
     * Load all translations for a given coupon id, keyed by language_id.
     * @return array<int, array> Map of language_id => row
     */
    public static function forCoupon(int $couponId): array
    {
        if (self::isDev()) return [];
        $couponId = (int)$couponId;
        if ($couponId <= 0) return [];
        $sql = "SELECT * FROM " . static::table() . " WHERE coupon_id = " . $couponId . " 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 coupon. $translations format:
     *   [ language_id => ['coupon_name'=>..., 'coupon_description'=>...] ]
     */
    public static function syncForCoupon(int $couponId, array $translations): void
    {
        if (self::isDev()) return;
        $couponId = (int)$couponId;
        if ($couponId <= 0) return;
        foreach ($translations as $lid => $vals) {
            $lid = (int)$lid;
            if ($lid <= 0) continue;
            $name = isset($vals['coupon_name']) ? (string)$vals['coupon_name'] : '';
            $desc = isset($vals['coupon_description']) ? (string)$vals['coupon_description'] : '';
            // Trim to schema limits
            if (strlen($name) > 32) { $name = substr($name, 0, 32); }

            // Does row exist?
            $checkSql = "SELECT COUNT(*) AS c FROM " . static::table() . " WHERE coupon_id = {$couponId} 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 = [
                'coupon_id' => $couponId,
                'language_id' => $lid,
                'coupon_name' => $name,
                'coupon_description' => $desc,
            ];
            if ($exists) {
                // Update by composite key
                $update = $data;
                unset($update['coupon_id'], $update['language_id']);
                \mh_db_perform(static::table(), $update, 'update', "coupon_id = {$couponId} AND language_id = {$lid}");
            } else {
                \mh_db_perform(static::table(), $data);
            }
        }
    }
}
