<?php
// pages/components/topics_list.php
// Lists all topics with actions opening the global modal
use Components\Router;
use Components\ConfigStore;
use Components\Models\Topic;
use Components\Resources\ResourceList;

$oob = (int) (mh_get('oob', 0, 'int'));
$page = (int)mh_get('page', 1, 'int');
$search = (string)mh_get('search', '', 'string');
$visibility = (string)mh_get('visibility', 'public', 'string');
$perPage = ConfigStore::getListPerPage('topics', 10);

// Build items from model
$items = [];
$total = 0;
if (function_exists('mh_db_query')) {
    $isPublic = ($visibility === 'public') ? 'True' : 'False';
    $paginationResult = Topic::paginate($perPage, $page, $search, ['newsletter_categories_name'], ['is_public' => $isPublic]);
    $total = $paginationResult['total'];
    foreach ($paginationResult['items'] as $t) {
        $id = (int)($t->newsletter_categories_id ?? 0);
        if ($id <= 0) { continue; }
        $name = (string)($t->newsletter_categories_name ?? (\mh_lng('MAILBEEZ_APP_LABEL_TOPIC', 'Topic') . ' ' . $id));
        $isPublic = (string)($t->is_public ?? '');
        $status = ($isPublic === 'True') ? 'Y' : '';

        $formatDate = function ($value) {
            $value = (string)$value;
            $y = substr($value, 0, 4);
            return ($value && $y !== '0000' && $y !== '0001' && $y !== '1000')
                ? date('Y-m-d', strtotime($value))
                : '-';
        };

        $items[] = [
            'id' => $id, 
            'label' => $name,
            'description' => (string)($t->newsletter_categories_description ?? ''),
            'date_added_fmt' => $formatDate($t->date_added ?? ''),
            'last_modified_fmt' => $formatDate($t->last_modified ?? ''),
            'status' => $status,
            'icon' => ['svg' => ($isPublic === 'True') ? \Components\Base::SVG_TAG : \Components\Base::SVG_OUTLINE_TAG, 'color' => 'brand', 'size' => 'sm']
        ];
    }
}

// Update outer attrs
$refreshUrl = Router::url('topics_list', [
    'partial' => 1,
    'search' => $search,
    'page' => $page,
    'visibility' => $visibility,
]);
$containerId = 'topics-list-' . ($visibility === 'private' ? 'private' : 'public');
$outerAttrs = 'id="' . $containerId . '" hx-trigger="topic:created from:body, topic:updated from:body, topic:deleted from:body, list-per-page-updated:topics from:body" hx-get="' . \Components\Base::h($refreshUrl) . '" hx-target="this" hx-swap="outerHTML"';
if ($oob) { $outerAttrs .= ' hx-swap-oob="outerHTML"'; }

ob_start();

$viewBase = Router::url('topic_modal', ['partial' => 1, 'mode' => 'view']);
$editBase = Router::url('topic_modal', ['partial' => 1, 'mode' => 'edit']);
$newBase = Router::url('topic_modal', ['partial' => 1, 'mode' => 'new']);
$topicsTab = ($visibility === 'private') ? 'private' : 'public';
$showCreateFirstTopicAction = (trim($search) === '');

echo ResourceList::render([
    'title' => \mh_lng('MAILBEEZ_APP_LABEL_TOPICS', 'Topics'),
    'table_id' => 'topics',
    'layout' => 'clean',

    'items' => $items,
    'id_key' => 'id',
    'label_key' => 'label',
    'sublabel_key' => 'description',
    'show_header' => true,
    'hide_name_column' => true,
    'columns' => [
        [
            'type' => 'identity',
            'label' => \mh_lng('MAILBEEZ_APP_LABEL_TOPIC', 'Topic'),
        ],
        [
            'key' => 'description',
            'label' => \mh_lng('UI_LABEL_DESCRIPTION', 'Description'),
            'optional' => true,
            'default' => false,
        ],
        [
            'key' => 'date_added_fmt',
            'label' => \mh_lng('UI_TEXT_CREATED', 'Created'),
            'optional' => true,
            'default' => false,
        ],
        [
            'key' => 'last_modified_fmt',
            'label' => \mh_lng('UI_TEXT_MODIFIED', 'Modified'),
            'optional' => true,
            'default' => false,
        ],
    ],
    'outer_attrs' => $outerAttrs,
    'empty_title' => $showCreateFirstTopicAction
        ? \mh_lng('MAILBEEZ_TOPICS_EMPTY_TITLE', 'Create your first topic')
        : \mh_lng('MAILBEEZ_NO_TOPICS_FOUND', 'No topics found.'),
    'empty_text' => $showCreateFirstTopicAction
        ? \mh_lng('MAILBEEZ_TOPICS_EMPTY_TEXT', 'Topics help you organize subscriber preferences and internal segments.')
        : \mh_lng('MAILBEEZ_NO_TOPICS_FOUND', 'No topics found.'),
    'empty_state' => $showCreateFirstTopicAction ? [
        'icon' => \Components\Base::SVG_TAG,
        'icon_color' => 'bg-brand/70 text-white/90',
        'action' => [
            'label' => \mh_lng('MAILBEEZ_CREATE_FIRST_TOPIC', 'Create first topic'),
            'icon' => \Components\Base::SVG_PLUS,
            'iconPosition' => 'front',
            'size' => 'md',
            'variant' => 'primary',
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => \mh_lng('MAILBEEZ_NEW_TOPIC', 'New Topic'),
                'data-size' => '3xl',
                'hx-get' => $newBase,
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
                'hx-vals' => json_encode(['topics_tab' => $topicsTab]),
            ],
        ],
    ] : null,
    'panel_type' => 'drawer',
    'search' => [
        'value' => $search,
        'placeholder' => mh_lng('UI_TEXT_TOPCIS_SEARCH', 'Search topic name...'),
        'target' => '#' . $containerId,
        'url' => Router::url('topics_list', ['partial' => 1, 'visibility' => $visibility]),
        'attrs' => [
            'x-model.debounce.500ms' => 'search',
        ]
    ],
    'pagination' => [
        'total' => $total,
        'per_page' => $perPage,
        'current_page' => $page,
        'url' => Router::url('topics_list', ['partial' => 1, 'visibility' => $visibility]),
        'target' => '#' . $containerId,
    ],
//    'new_action' => [
//        'label' => 'New',
//        'url' => Router::url('topic_modal', ['partial' => 1, 'mode' => 'new']),
//        'attrs' => [
//            'data-title' => 'New Topic',
//            'data-size' => 'xl',
//        ],
//        'variant' => 'primary',
//    ],
    'row_actions_as_menu' => true,
    'menu_trigger' => 'ellipsis',
    'row_actions' => [
        [
            'label' => \mh_lng('UI_BUTTON_VIEW', 'View'),
            'icon' => \Components\Base::SVG_EYE,
            'url' => $viewBase . '&id={id}',
            'attrs' => [ 'data-title' => \mh_lng('MAILBEEZ_VIEW_TOPIC', 'View Topic'), 'data-size' => 'xl' ],
            'variant' => 'secondary',
        ],
        [
            'label' => \mh_lng('UI_BUTTON_EDIT', 'Edit'),
            'icon' => \Components\Base::SVG_EDIT,
            'url' => $editBase . '&id={id}',
            'attrs' => [ 'data-title' => \mh_lng('MAILBEEZ_EDIT_TOPIC', 'Edit Topic'), 'data-size' => 'xl' ],
            'variant' => 'primary',
        ],
    ],
]);

$__html = ob_get_clean();
echo $__html;
