<?php
// pages/components/newsletter_audience_selection_modal.php

use Components\Support\Htmx;
use Components\Router;
use Components\Legacy\LegacyRouter;
use Components\Base;
use Components\Button;
use Components\Models\Audience;
use Components\Resources\ItemListPresentation;
use Components\Form\BaseField;
use Components\Support\Format;
use Components\Ui\Tabs;
use Components\Form\SearchInput;

ob_start();

$pageMode = \mh_get('page_mode', 'newsletter', 'string');
if ($pageMode === 'newsletter') { $pageMode = (string)\mh_post('page_mode', 'newsletter'); }

$campaignId = (int)\mh_get('newsletter_campaign_id', 0, 'int');
if ($campaignId <= 0) { $campaignId = (int)\mh_post('newsletter_campaign_id', 0); }

$date = \mh_get('date', '', 'string');
if ($date === '') { $date = (string)\mh_post('date', ''); }

$step = \mh_get('step', 'existing', 'string');
if ($step === 'existing') { $step = (string)\mh_post('step', 'existing'); }

$templateId = \mh_get('template_id', '', 'string');
if ($templateId === '') { $templateId = (string)\mh_post('template_id', ''); }

// Initial kind/tab
$kind = \mh_get('kind', '', 'string');
if ($kind === '') { $kind = (string)\mh_post('kind', ''); }

$skipTemplate = (int)\mh_get('skip_template', 0, 'int');
if (!$skipTemplate) { $skipTemplate = (int)\mh_post('skip_template', 0); }

// Helper to build the final newsletter item modal URL
$getFinalUrl = function($listId = null) use ($pageMode, $campaignId, $templateId, $skipTemplate, $date) {
    $params = [
        'partial' => 1,
        'mode' => 'new',
        'page_mode' => $pageMode,
    ];
    if ($date !== '') {
        $params['date'] = $date;
    }
    if ($campaignId > 0) {
        $params['newsletter_campaign_id'] = $campaignId;
    }
    if ($listId !== null) {
        $params['newsletter_list_id'] = is_numeric($listId) ? (int)$listId : $listId; // allow {id} placeholder
    }

    if ($skipTemplate) {
        $params['skip_template'] = 1;
    }

    if ($templateId !== '' && $templateId !== null && $templateId !== 'null' && $templateId !== 'undefined') {
        $params['template_id'] = $templateId;
        return Router::url('newsletter_item_modal', $params);
    }

    return Router::url('newsletter_template_selection_modal', $params);
};

$panelId = Htmx::resolvePanelId();
$panelTarget = '#' . $panelId . '-body';
$panelFooter = '#' . $panelId . '-footer';

if ($step === 'existing') {
    // Show a list of audiences
    $customerLists = Audience::typeCustomers($pageMode);
    $prospectLists = Audience::typeProspects($pageMode);
    $favoriteLists = Audience::allByKind('favorite', false, $pageMode);

    $processLists = function($lists, $kindSuffix = '') {
        $items = [];
        foreach ($lists as $list) {
            $id = (int)$list->newsletter_list_id;
            $icon = is_callable([$list, 'icon']) ? $list->icon() : ['svg' => Base::SVG_USERS, 'color' => 'indigo', 'size' => 'sm'];

            $sublineSuffixHtml = '';
            try {
                $rc = (array)$list->getResultCountCache(Audience::RESULT_COUNT_CACHE_TTL);
                $cachedVal = $rc['value'] ?? null;
                $isValid = (bool)($rc['is_valid'] ?? false);

                $label = ($cachedVal !== null) ? (string)Format::humanNumber((int)$cachedVal, ['decimals' => 1, 'trim_zeros' => true]) : '...';

                $sublineSuffixHtml = Audience::countAnchorHtml($id, [
                    'label' => $label,
                    'intersect' => !$isValid,
                    'force' => !$isValid,
                    'lazy' => true
                ]);
            } catch (\Throwable $e) { $sublineSuffixHtml = ''; }

            $starHtml = '';
            try {
                $starHtml = Audience::renderFavoriteStarHtml($list, false, $kindSuffix !== '' ? ('-' . $kindSuffix) : '', true);
            } catch (\Throwable $e) { $starHtml = ''; }

            $items[] = [
                'id' => $id,
                'name' => $list->getLabel(),
                'title_after_html' => $starHtml,
                'subtitle' => method_exists($list, 'getSourceTitle') ? (string)$list->getSourceTitle() : '',
                'icon' => $icon,
                'subline_suffix_html' => $sublineSuffixHtml,
            ];
        }
        return $items;
    };

    $customerItems = $processLists($customerLists, 'customers');
    $prospectItems = $processLists($prospectLists, 'prospects');
    $favoriteItems = $processLists($favoriteLists, 'favorites');

    $audienceTabItems = [];
    if (!empty($favoriteItems)) {
        $audienceTabItems[] = ['value' => 'favorites', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_FAVORITES', 'Favorites'), 'icon' => Base::SVG_STAR];
    }
    if (!empty($customerItems)) {
        $audienceTabItems[] = ['value' => 'customers', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_CUSTOMERS', 'Customers')];
    }
    if (!empty($prospectItems)) {
        $audienceTabItems[] = ['value' => 'prospects', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_PROSPECTS', 'Prospects')];
    }

    // Always show at least the customers tab if it's the only one or if everything's empty
    if (empty($audienceTabItems)) {
        $audienceTabItems[] = ['value' => 'customers', 'label' => \mh_lng('MAILBEEZ_AUDIENCE_GROUP_CUSTOMERS', 'Customers')];
    }

    // Default kind logic
    if ($kind === '') {
        $kind = !empty($favoriteItems) ? 'favorites' : 'customers';
    }
    ?>
    <div x-data="{ activeTab: '<?= $kind; ?>', searchQuery: '' }">
        <script>
            (function() {
                var m = document.getElementById('<?= $panelId; ?>');
                if (m) {
                    m.setAttribute('data-title', <?= json_encode(\mh_lng('UI_AUDIENCE_SELECTION_EXISTING_DESC', 'Select or Create Audience')); ?>);
                    m.setAttribute('data-size', '5xl');
                }
            })();
        </script>

        <?= \Components\Newsletter\WizardSteps::renderStepper(\Components\Newsletter\WizardSteps::STEP_AUDIENCE); ?>
        
        <div class="flex items-end justify-between border-b border-divider mb-4 gap-4">
            <div class="flex-1">
                <div class="hidden sm:block">
                    <?= Tabs::desktopNavOnly('activeTab', $audienceTabItems); ?>
                </div>
                <div class="sm:hidden pb-2">
                    <?= Tabs::mobile('activeTab', $audienceTabItems, ['ariaLabel' => \mh_lng('UI_AUDIENCE_SELECT_TAB', 'Select audience tab')]); ?>
                </div>
            </div>

            <div class="flex items-center gap-2 pb-2">
                <?= SearchInput::render('search', '', [
                    'placeholder' => \mh_lng('UI_SEARCH_AUDIENCE', 'Search audience...'),
                    'model' => 'searchQuery',
                    'size' => 'sm',
                ]); ?>

                <?= Button::render(\mh_lng('UI_NEW', 'New'), [
                    'variant' => 'secondary',
                    'icon' => \Components\Base::SVG_PLUS,
                    'iconPosition' => 'front',
                    'size' => 'sm',
                    'class' => 'shrink-0',
                    'attrs' => [
                        'hx-get' => Router::url('audience_list_modal', [
                            'partial' => 1,
                            'mode' => 'new',
                            'return_to' => 'audience_created',
                            'page_mode' => $pageMode,
                            'newsletter_campaign_id' => $campaignId,
                            'template_id' => $templateId,
                            'date' => $date,
                            'skip_template' => $skipTemplate,
                        ]),
                        'hx-target' => $panelTarget,
                        'hx-push-url' => 'false',
                        ':hx-vals' => "JSON.stringify({ filter_type: String(activeTab) })",
                    ],
                ]); ?>
            </div>
        </div>

        <div class="min-h-[60vh] overflow-y-auto">
            <div x-show="activeTab === 'favorites'" :x-cloak="activeTab !== 'favorites'">
                <?= ItemListPresentation::render([
                    'items' => $favoriteItems,
                    'columns' => 2,
                    'js_search' => true,
                    'search_model' => 'searchQuery',
                    'id_key' => 'id',
                    'row_actions' => [
                        [
                            'label' => \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select'),
                            'url' => $getFinalUrl('{id}'),
                            'variant' => 'primary',
                            'icon' => Base::SVG_CHEVRON_RIGHT,
                            'attrs' => [
                                'hx-target' => $panelTarget,
                                'hx-swap' => 'innerHTML',
                                'hx-push-url' => 'false',
                            ],
                        ],
                    ],
                ]); ?>
            </div>
            <div x-show="activeTab === 'customers'" :x-cloak="activeTab !== 'customers'">
                <?= ItemListPresentation::render([
                    'items' => $customerItems,
                    'columns' => 2,
                    'js_search' => true,
                    'search_model' => 'searchQuery',
                    'id_key' => 'id',
                    'row_actions' => [
                        [
                            'label' => \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select'),
                            'url' => $getFinalUrl('{id}'),
                            'variant' => 'primary',
                            'icon' => Base::SVG_CHEVRON_RIGHT,
                            'attrs' => [
                                'hx-target' => $panelTarget,
                                'hx-swap' => 'innerHTML',
                                'hx-push-url' => 'false',
                            ],
                        ],
                    ],
                ]); ?>
            </div>
            <div x-show="activeTab === 'prospects'" :x-cloak="activeTab !== 'prospects'">
                <?= ItemListPresentation::render([
                    'items' => $prospectItems,
                    'columns' => 2,
                    'js_search' => true,
                    'search_model' => 'searchQuery',
                    'id_key' => 'id',
                    'row_actions' => [
                        [
                            'label' => \mh_lng('UI_BUTTON_TEMPLATE_SELECT', 'Select'),
                            'url' => $getFinalUrl('{id}'),
                            'variant' => 'primary',
                            'icon' => Base::SVG_CHEVRON_RIGHT,
                            'attrs' => [
                                'hx-target' => $panelTarget,
                                'hx-swap' => 'innerHTML',
                                'hx-push-url' => 'false',
                            ],
                        ],
                    ],
                ]); ?>
            </div>
        </div>
    </div>

    <template x-teleport="<?= $panelFooter ?>">
        <div class="flex">

        <div class="flex-1"></div>
        <?= Button::render(\mh_lng('UI_BUTTON_CANCEL', 'Cancel'), [
            'variant' => 'ghost',
            'size' => 'md',
            'attrs' => [
                'command' => 'close',
                'commandfor' => $panelId,
            ]
        ]); ?>
        </div>
        </template>
    <?php
}

$__html = ob_get_clean();
echo $__html;
