<?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';

} 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') {
                $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;
