<?php
// pages/components/newsletter_campaigns_list.php
// Collections sidebar for NewsletterCampaigns using the new CollectionsList design
use Components\Router as R;
use Components\Models\NewsletterCampaign;
use Components\Resources\CollectionsList;

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

$selectedGroup = mh_get('group', '', 'string');

// Build collections (campaigns) with counts and colors
$collections = [];
$palette = ['#6b7280', '#6366f1', '#10b981', '#f59e0b', '#ef4444', '#8b5cf6', '#14b8a6', '#84cc16'];
$totalCount = 0;
if (function_exists('mh_db_query')) {
    foreach (NewsletterCampaign::all() as $campaign) {
        $cid = (int)($campaign->newsletter_campaign_id ?? 0);
        if ($cid <= 0) { continue; }
        $name = (string)($campaign->newsletter_campaign_name ?? ('Campaign ' . $cid));
        $items = $campaign->items();
        $count = is_array($items) ? count($items) : 0;
        $totalCount += $count;
        $collections[] = [
            'id' => $cid,
            'slug' => 'campaign-' . $cid,
            'name' => $name,
            'color' => $palette[$cid % count($palette)],
            'count' => $count,
        ];
    }
}
// Prepend an "All" virtual collection
array_unshift($collections, [
    'id' => 0,
    'slug' => 'all',
    'name' => 'All',
    'color' => '#9ca3af',
    'count' => $totalCount,
]);

echo CollectionsList::render([
    'items' => $collections,
    'selected_slug' => $selectedGroup !== '' ? $selectedGroup : 'all',
    'page_key' => 'newsletter',
    'outer_attrs' => $outerAttrs,
    'new_action' => [
        'label' => 'New',
        'url' => R::url('newsletter_campaign_modal', ['partial' => 1, 'mode' => 'new']),
        'attrs' => [ 'data-title' => 'New Campaign', 'data-size' => 'xl' ],
        'variant' => 'primary',
    ],
]);