<?php
// pages/components/newsletter_items_list.php
// Flows list for NewsletterItems using the new ItemList design with expandable rows
use Components\Models\NewsletterItem;
use Components\Resources\ItemList;

$oob = (int) (mh_get('oob', 0, 'int'));
$outerAttrs = 'id="newsletter-items-list"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

$selectedGroup = mh_get('group', '', 'string');
$selectedCampaignId = null;
if ($selectedGroup && strpos($selectedGroup, 'campaign-') === 0) {
    $selectedCampaignId = (int)substr($selectedGroup, strlen('campaign-'));
}

// Build items from model (roots with followups), optionally filtered by campaign
$items = [];
if (function_exists('mh_db_query')) {
    foreach (NewsletterItem::all() as $it) {
        $id = (int)($it->newsletter_item_id ?? 0);
        if ($id <= 0) { continue; }
        if ($selectedCampaignId !== null && (int)($it->newsletter_campaign_id ?? 0) !== $selectedCampaignId) {
            continue;
        }
        $name = (string)($it->newsletter_item_name ?? ('Item ' . $id));
        $status = (string)($it->status ?? '');
        $items[] = [
            'id' => $id,
            'name' => $name,
            'status' => $status,
            'icon' => $it->icon ?? [ 'svg' => \Components\Base::SVG_MAIL, 'color' => 'bg-indigo-500 text-white', 'variant' => 'solid', 'shape' => 'square' ],
            '__model' => $it,
        ];
    }
}

// Expandable content will be lazy-loaded via ItemList's expand_lazy_url option

echo ItemList::render(NewsletterItem::itemListOptions([
    'title' => ($selectedGroup && $selectedGroup !== 'all') ? 'Flows in Collection' : 'All Flows',
    'items' => $items,
    'outer_attrs' => $outerAttrs,
]));
