<?php
namespace Components\Models;

require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter.php');

class NewsletterCampaign extends BaseModel
{
    protected static string $table = 'TABLE_MAILBEEZ_NEWSLETTER_CAMPAIGNS';
    protected static string $primaryKey = 'newsletter_campaign_id';

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

    public static function all(string $applicability = ''): array
    {
        if (self::isDev()) return [];

        $where = '1=1';
        $app = strtolower(trim($applicability));
        if (in_array($app, ['newsletter', 'automation'], true)) {
            $where = "(newsletter_campaign_applicability = 'both' OR newsletter_campaign_applicability = '" . \mh_db_input($app) . "')";
        }

        $sql = "SELECT * FROM " . static::table() . " WHERE {$where} ORDER BY " . static::pk() . " DESC";
        $q = \mh_db_query($sql);

        $items = [];
        while ($row = \mh_db_fetch_array($q)) {
            $items[] = new static($row);
        }
        \mh_db_free_result($q);

        return $items;
    }

    public static function getNewDefaults(): array
    {
        return [
            'newsletter_campaign_applicability' => 'both',
            'newsletter_campaign_archived' => false,
        ];
    }

    public function augmentFormValues(array $values): array
    {
        $boolKeys = ['newsletter_campaign_archived'];
        foreach ($boolKeys as $k) {
            if (array_key_exists($k, $values)) {
                $v = $values[$k];
                $values[$k] = ($v === 'True' || $v === '1' || $v === 'on' || $v === true);
            }
        }
        return $values;
    }

    /**
     * Return a badge representing the applicability of this campaign.
     *
     * @return string HTML for the badge
     */
    public function getApplicabilityBadgeHtml(): string
    {
        $applicability = (string)($this->attributes['newsletter_campaign_applicability'] ?? 'both');
        if ($applicability === 'both') {
            return '';
        }

        $label = '';
        $type = 'gray';
        if ($applicability === 'newsletter') {
            $label = \mh_lng('MAILBEEZ_AUDIENCE_APPLICABILITY_NEWSLETTER', 'Newsletter');
            $type = 'info';
        } elseif ($applicability === 'automation') {
            $label = \mh_lng('MAILBEEZ_AUDIENCE_APPLICABILITY_AUTOMATION', 'Automation');
            $type = 'brand';
        }

        if ($label === '') {
            return '';
        }

        return \Components\Ui\Badge::render($type, $label, [
            'variant' => 'soft',
            'inner_class' => 'px-1.5 py-0.5 text-[10px] uppercase font-bold leading-none'
        ]);
    }

    /**
     * Map toggle/checkbox values ('on'/'') to TINYINT-compatible values ('1'/'0')
     * before persisting to the database.
     */
    protected function filterAttributesForSave(array $data): array
    {
        $data = parent::filterAttributesForSave($data);

        $boolColumns = ['newsletter_campaign_archived'];
        foreach ($boolColumns as $col) {
            if (array_key_exists($col, $data)) {
                $v = $data[$col];
                if ($v === 'on' || $v === 'True' || $v === '1' || $v === true) {
                    $data[$col] = '1';
                } else {
                    $data[$col] = '0';
                }
            }
        }

        return $data;
    }

    /**
     * Accessor: return a campaign color utility token.
     *
     * - If `newsletter_campaign_color` is set, return it.
     * - Otherwise, pick a deterministic fallback from `Palette::colorTokensForChoice()`.
     */
    public function newsletter_campaign_color(): string
    {
        $dot = '';
        try {
            $dot = (string)($this->attributes['newsletter_campaign_color'] ?? '');
        } catch (\Throwable $e) {
            $dot = '';
        }

        if ($dot !== '') {
            return $dot;
        }

        $cid = 0;
        try {
            $cid = (int)($this->attributes['newsletter_campaign_id'] ?? 0);
        } catch (\Throwable $e) {
            $cid = 0;
        }

        $tokens = [];
        try {
            $tokens = \Components\Support\Palette::colorTokensForChoice();
        } catch (\Throwable $e) {
            $tokens = [];
        }

        $idx = abs($cid) % max(1, count($tokens));
        return (string)($tokens[$idx] ?? 'bg-gray-500');
    }

    /**
     * Relation: a campaign has many newsletter items (default/root items only)
     * Returns only items of type ITEM_TYPE_DEFAULT (excludes follow-up items).
     * @return array<NewsletterItem>
     */
    public function items(): array
    {
        // Fetch all related items, then filter out follow-ups
        $all = $this->hasMany(NewsletterItem::class, 'newsletter_campaign_id');
        if (!$all) { return []; }

        // Only include items with type ITEM_TYPE_DEFAULT (exclude follow-ups)
        $filtered = array_filter($all, function ($item) {
            return $item instanceof NewsletterItem && $item->isInitial();
        });

        // Reindex array to have sequential numeric keys
        return array_values($filtered);
    }
}
