<?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';

    /**
     * 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);
    }
}
