<?php
// pages/components/audience_list_modal.php
// Thin wrapper delegating to generic CRUD controller for Audience Lists

use Components\Resources\Controllers\CrudController;
use Components\Models\Audience;
use Components\Router;
use Components\Support\Htmx;

ob_start();

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

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

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

$pageConfig = \Components\Newsletter\PageConfig::fromRequest();
$pageMode = $pageModeRaw ?: $pageConfig->mode;

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

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

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

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

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

$isNewsletterFlow = ($campaignId > 0 || in_array($returnTo, ['audience_created', 'audience_item_create']));

// Helper to build the final newsletter item modal URL
$getFinalUrl = function($listId = null) use ($isNewsletterFlow, $pageMode, $campaignId, $templateId, $skipTemplate, $date) {
    if (!$isNewsletterFlow) {
        return null;
    }

    $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'] = (int)$listId; }
    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);
};

if ($step === 'created') {
    $listId = (int)\mh_get('list_id', 0, 'int');
    $headerHtml = '';
    if ($isNewsletterFlow) {
        $headerHtml = \Components\Newsletter\WizardSteps::renderStepper(\Components\Newsletter\WizardSteps::STEP_AUDIENCE);
    } else {
        $headerHtml = \Components\Audience\WizardSteps::renderStepper(\Components\Audience\WizardSteps::STEP_CONFIRMATION);
    }

    require BEEZUI_ROOT . '/pages/components/audience_created_success_step.php';

    // The audience has just been created; sync the client-side Alpine store so the
    // underlying audience page switches to the Flow view right away (server-side
    // persistence already happened on save via ConfigStore::setViewMode).
    echo \Components\Ui\FlowHelpers::forceFlowView('audience', false);

} else {
    if ($returnTo !== '') {
        $modalTitle = \mh_lng('UI_AUDIENCE_SELECTION_CREATE', 'Create new audience');
        if (\mh_get('fields', '') === 'segmentation') {
            $modalTitle = \mh_lng('UI_AUDIENCE_CONFIGURE_SEGMENTATION', 'Configure segmentation');
        }
        ?>
        <script>
            (function() {
                var m = document.getElementById('<?= $panelId; ?>');
                if (m) {
                    m.setAttribute('data-title', <?= json_encode($modalTitle); ?>);
                    m.setAttribute('data-size', '3xl');
                }
            })();
        </script>
        <?php
    }

    $headerHtml = '';
    if ($isNewsletterFlow) {
        $headerHtml = \Components\Newsletter\WizardSteps::renderStepper(\Components\Newsletter\WizardSteps::STEP_AUDIENCE);
    } else if (\mh_get('mode') === 'new') {
        $headerHtml = \Components\Audience\WizardSteps::renderStepper(\Components\Audience\WizardSteps::STEP_BASE_DATA);
    }

    $submitLabel = null;
    $submitIcon = '';
    if (\mh_get('mode') === 'new') {
        $submitLabel = \mh_lng('UI_CREATE_AUDIENCE', 'create audience');
        $submitIcon = \Components\Base::SVG_CHEVRON_RIGHT;
    }

    echo CrudController::handle([
        'modelClass'   => Audience::class,
        'selfRoute'    => 'audience_list_modal',
        'header_html'  => $headerHtml,
        'submit_label' => $submitLabel,
        'submit_icon'  => $submitIcon,

        'event_prefix' => 'audience_lists',
        'autoclose' => '0',
        'no_render_after_save' => '1',
        'field_presets' => [
            'page_mode' => $pageModeRaw,
            'newsletter_list_applicability' => ($pageModeRaw === 'automation' || $pageModeRaw === 'newsletter') ? $pageModeRaw : 'both',
        ],
        'on_save' => function($model, $postAll, $id) use ($isNewsletterFlow, $returnTo, $pageMode, $campaignId, $templateId, $panelTarget, $date, $skipTemplate, $panelId) {
            /** @var Audience $model */
            foreach ($model->newsletterItems() as $item) {
                \Components\Models\NewsletterItem::invalidateFlowCacheById((int)$item->newsletter_items_id);
            }

            if (\mh_get('mode', 'new') === 'new') {
                // A newly created audience should always present the Flow view (not
                // Performance) on the underlying audience page, mirroring the trigger
                // and newsletter creation flows. The Flow view is persisted as the
                // 'journey' view mode (see FlowHelpers toggle).
                try {
                    \Components\ConfigStore::setViewMode('audience', 'journey');
                } catch (\Throwable $e) {
                    // Persistence is best-effort; the page still defaults to the Flow view.
                }

                $url = Router::url('audience_list_modal', [
                    'partial' => 1,
                    'step' => 'created',
                    'list_id' => $id,
                    'return_to' => $returnTo,
                    'page_mode' => $pageMode,
                    'newsletter_campaign_id' => $campaignId,
                    'template_id' => $templateId,
                    'date' => $date,
                    'skip_template' => $skipTemplate,
                ]);

                \Components\Support\Htmx::pushUrl('false');
                \Components\Support\Htmx::location([
                    'path' => $url,
                    'target' => $panelTarget,
                    'push' => 'false',
                    'history' => false,
                ]);
            } else {
                if ($returnTo === 'audience_item_create') {
                    $params = [
                        'partial' => 1,
                        'mode' => 'new',
                        'page_mode' => $pageMode,
                        'newsletter_list_id' => $id,
                        'newsletter_campaign_id' => $campaignId,
                        'date' => $date,
                    ];
                    if ($templateId !== '' && $templateId !== null && $templateId !== 'null' && $templateId !== 'undefined') {
                        $params['template_id'] = $templateId;
                        $url = Router::url('newsletter_item_modal', $params);
                    } else {
                        $url = Router::url('newsletter_template_selection_modal', $params);
                    }

                    \Components\Support\Htmx::pushUrl('false');
                    \Components\Support\Htmx::location([
                        'path' => $url,
                        'target' => $panelTarget,
                        'push' => 'false',
                        'history' => false,
                    ]);
                } else {
                    \Components\Support\Htmx::command('close', ['commandfor' => $panelId]);
                }
            }
        },
    ]);
}

$__html = ob_get_clean();
echo $__html;
