<?php
// pages/components/newsletter_item_modal.php
// Thin wrapper delegating to generic CRUD controller for NewsletterItem

use Components\Models\NewsletterCampaign;
use Components\Models\NewsletterItem;
use Components\Models\Audience;
use Components\Resources\Controllers\CrudController;
use Components\Support\Htmx;
use Components\Newsletter\PageConfig;

ob_start();

mh_load_modules_language_files(MH_DIR_MODULE, 'mb_newsletter');

$pageConfig =  PageConfig::fromRequest();

// Support passing template_id to handle content initialization on create
$templateId = (string)\mh_get('template_id', '');
if ($templateId === '') { $templateId = (string)\mh_post('template_id', ''); }

$templatesTab = (string)\mh_get('templates_tab', 'gallery', 'string');
if ($templatesTab === '') { $templatesTab = (string)\mh_post('templates_tab', 'gallery'); }

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

// Safeguard: if we are in "new" mode but missing a template_id, redirect back to template selection
if (\mh_get('mode') === 'new' && $templateId === '') {
    $url = \Components\Router::url('newsletter_template_selection_modal', [
        'partial' => 1,
        'page_mode' => $pageConfig->mode,
        'newsletter_list_id' => (int)\mh_get('newsletter_list_id'),
        'newsletter_campaign_id' => (int)\mh_get('newsletter_campaign_id'),
        'templates_tab' => $templatesTab,
        'date' => $date,
    ]);
    \Components\Support\Htmx::location([
        'path' => $url,
        'target' => '#' . \Components\Support\Htmx::resolvePanelId() . '-body',
        'push' => 'false',
        'history' => false,
    ]);
    exit;
}

$id = (int)\mh_get('id', 0, 'int');
if ($id > 0 && class_exists(NewsletterItem::class)) {
    try {
        $model = NewsletterItem::find($id);
        if ($model) {
            $type = $model->scheduleTypeCode();
            if ($type === 'automation') {
                $pageConfig = new PageConfig( PageConfig::MODE_AUTOMATION);
            } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
                $pageConfig = new PageConfig( PageConfig::MODE_NEWSLETTER);
            }
        }
    } catch (\Throwable $e) { /* ignore */
    }
}

$headerHtml = '';
$modalTitle = (\mh_get('mode') === 'new')
    ? $pageConfig->creation_modal_title
    : ($pageConfig->mode === PageConfig::MODE_AUTOMATION ? \mh_lng('UI_EDIT_AUTOMATION', 'Edit Automation') : \mh_lng('UI_EDIT_NEWSLETTER', 'Edit Newsletter'));

if (\mh_get('mode') === 'new') {

$headerHtml .= '
<script>
    (function() {
        var m = document.getElementById(\'' . Htmx::resolvePanelId() . '\');
        if (m) {
            m.setAttribute(\'data-title\', ' . json_encode($modalTitle) . ');
            m.setAttribute(\'data-size\', \'4xl\');
        }
    })();
</script>
';
}

if (\mh_get('mode') === 'new') {
    $headerHtml .= \Components\Newsletter\WizardSteps::renderStepper(\Components\Newsletter\WizardSteps::STEP_DETAILS);
}

// Support presetting the campaign when creating from a specific campaign collection
$fieldPresets = [];
$presetCampaignId = (int)\mh_get('newsletter_campaign_id', 0, 'int');
if ($presetCampaignId > 0) {
    $fieldPresets['newsletter_campaign_id'] = (string)$presetCampaignId;
}
$presetListId = (int)\mh_get('newsletter_list_id', 0, 'int');
if ($presetListId > 0) {
    $fieldPresets['newsletter_list_id'] = (string)$presetListId;
}

if ($date !== '') {
    $fieldPresets['start_mode'] = 'date';
    $fieldPresets['newsletter_item_start'] = $date;
}

$backToTemplateSelectionAttrs = null;
if (\mh_get('mode') === 'new') {
    $backToTemplateSelectionAttrs = [
        'hx-get' => \Components\Router::url('newsletter_template_selection_modal', [
            'partial' => 1,
            'page_mode' => $pageConfig->mode,
            'newsletter_campaign_id' => $presetCampaignId,
            'newsletter_list_id' => $presetListId,
            'template_id' => $templateId,
            'templates_tab' => $templatesTab,
            'date' => $date,
        ]),
        'hx-target' => '#config-modal-body',
        'hx-push-url' => 'false',
    ];
}

if (\mh_get('mode') === 'new') {
    $lc = strtolower((string)\mh_session('language_code', 'en'));
    $ts = time();
    $pattern = ($lc === 'de') ? 'd. MMM yyyy HH:mm' : 'MMM d, yyyy HH:mm';
    $timestamp = '';
    if (class_exists('\\IntlDateFormatter')) {
        try {
            $localeMap = ['de' => 'de_DE', 'en' => 'en_US'];
            $icuLocale = $localeMap[$lc] ?? ($lc ?: 'en_US');
            $idf = new \IntlDateFormatter($icuLocale, \IntlDateFormatter::NONE, \IntlDateFormatter::NONE, date_default_timezone_get(), null, $pattern);
            $timestamp = $idf->format($ts);
        } catch (\Throwable $e) { /* ignore */ }
    }
    if (!$timestamp) {
        $timestamp = ($lc === 'de') ? date('j. M Y H:i', $ts) : date('M j, Y H:i', $ts);
    }

    if ($presetListId > 0) {
        $aud = Audience::find($presetListId);
        $audLabel = $aud ? $aud->getLabel() : ('#' . $presetListId);

        if ($pageConfig->mode === \Components\Newsletter\PageConfig::MODE_AUTOMATION) {
            $fieldPresets['newsletter_item_name'] = sprintf(\mh_lng('MAILBEEZ_NEWSLETTER_ITEM_DEFAULT_NAME_AUTOMATION_WITH_LIST'), $audLabel, $timestamp);
        } else {
            $fieldPresets['newsletter_item_name'] = sprintf(\mh_lng('MAILBEEZ_NEWSLETTER_ITEM_DEFAULT_NAME_WITH_LIST'), $audLabel, $timestamp);
        }
    } else {
        if ($pageConfig->mode === \Components\Newsletter\PageConfig::MODE_AUTOMATION) {
            $fieldPresets['newsletter_item_name'] = sprintf(\mh_lng('MAILBEEZ_NEWSLETTER_ITEM_DEFAULT_NAME_AUTOMATION'), $timestamp);
        } else {
            $fieldPresets['newsletter_item_name'] = sprintf(\mh_lng('MAILBEEZ_NEWSLETTER_ITEM_DEFAULT_NAME'), $timestamp);
        }
    }
}

$group = (string)\mh_get('group', '', 'string');
$listId = (int)\mh_get('list_id', 0, 'int');
$scheduleType = (string)\mh_get('schedule_type', '', 'string');

$saveSucceeded = false;
$savedId = 0;
$savedCampaignId = 0;

$subAction = (string)\mh_get('sub_action', '', 'string');
$submitLabel = null;
$submitIcon = '';
if ($subAction === 'move') {
    $submitLabel = \mh_lng('UI_MOVE', 'Move');
} elseif ($subAction === 'archive') {
    $submitLabel = \mh_lng('UI_ARCHIVE', 'Archive');
} elseif (\mh_get('mode') === 'new') {
    $submitLabel = ($pageConfig->mode === \Components\Newsletter\PageConfig::MODE_AUTOMATION)
        ? \mh_lng('UI_CREATE_AUTOMATION_FLOW', 'create automation flow')
        : \mh_lng('UI_CREATE_NEWSLETTER_FLOW', 'create newsletter flow');
    $submitIcon = \Components\Base::SVG_CHEVRON_RIGHT;
}

echo CrudController::handle([
    'modelClass'    => NewsletterItem::class,
    'selfRoute'     => 'newsletter_item_modal',
    'event_prefix'  => $pageConfig->getEventName('newsletter_item'),
    'autoclose'     => \mh_get('mode') !== 'new',
    'field_presets' => $fieldPresets,
    'submit_label'  => $submitLabel,
    'submit_icon'   => $submitIcon,
    'cancel_label'  => $backToTemplateSelectionAttrs ? \mh_lng('UI_PREVIOUS', 'Back') : null,
    'cancel_attrs'  => $backToTemplateSelectionAttrs,
    'split_footer_actions' => \mh_get('mode') === 'new',
    'oobListParams' => array_merge(['page_mode' => $pageConfig->mode],
        $group !== '' ? ['group' => $group] : [],
        $listId > 0 ? ['list_id' => $listId] : [],
        $scheduleType !== '' ? ['schedule_type' => $scheduleType] : []
    ),
    'header_html'   => $headerHtml,
    'on_save' => function ($model, $postAll, $id) use ($pageConfig, $templateId, &$saveSucceeded, &$savedId, &$savedCampaignId) {
        $saveSucceeded = true;
        $savedId = (int)$id;
        NewsletterItem::invalidateFlowCacheById((int)$id);

        // Resolve the target flow id (root) for event broadcasting.
        // Prefer ui_event_id/flow_id when provided (e.g., child item edits),
        // otherwise fall back to the edited item's own id (root case).
        $uiEventId = (int) \mh_get('ui_event_id', 0, 'int');
        if ($uiEventId <= 0) { $uiEventId = (int) \mh_get('flow_id', 0, 'int'); }
        if ($uiEventId <= 0) {
            $uiEventId = (int) (\mh_post('ui_event_id', 0) ?? 0);
            if ($uiEventId <= 0) { $uiEventId = (int) (\mh_post('flow_id', 0) ?? 0); }
        }
        $targetId = $uiEventId > 0 ? $uiEventId : (int) $id;

        // On create: skip row/flow refresh (nothing to refresh yet) and instead
        // navigate the collections list to the campaign the new item was saved to.
        // On edit: refresh the row and flow, then update the collections counts.
        $isNewItem = ((int)(\mh_post('id', 0) ?? 0) <= 0) || (\mh_get('mode', '', 'string') === 'new');
        if ($isNewItem && $model instanceof NewsletterItem) {
            // If a template was selected, initialize the content
            if ($templateId !== '') {
                $model->initializeFromTemplate($templateId);
            }

            $currentSavedCampaignId = (int)($model->newsletter_campaign_id ?? 0);
            $savedCampaignId = $currentSavedCampaignId;
            $group = $currentSavedCampaignId > 0 ? 'campaign-' . $currentSavedCampaignId : '';
            // Refresh collections list and, via the group param, trigger items-list navigation
            // client-side. Do NOT fire newsletter_item:updated / expandable:refresh — no row exists yet.
            // \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), $group !== '' ? ['group' => $group] : ['id' => (string)$targetId]);

            // Add campaign_id to the created event so newsletter.php can navigate to it
            \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:created'), [
                'id' => (string)$id,
                'campaign_id' => (string)$currentSavedCampaignId
            ]);
        } else {
            // Edit: refresh the row, flow diagram, and collections counts.
            \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => (string)$targetId]);
            \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string)$targetId]);
            \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:collections:refresh'), ['id' => (string)$targetId]);
        }

        // Emit an OOB status badge fragment when explicitly requested or when
        // saving the dedicated schedule editor subset (fields=schedule_config).
        $flagRawGet  = (string) \mh_get('updateStatusBadge', '');
        $flagRawPost = (string) \mh_post('updateStatusBadge', '');
        $flagRaw = $flagRawGet !== '' ? $flagRawGet : $flagRawPost;
        $flag = in_array(strtolower(trim($flagRaw)), ['1', 'true', 'on', 'yes'], true);

        $fieldsParamGet  = (string) \mh_get('fields', '', 'string');
        $fieldsParamPost = (string) \mh_post('fields', '');
        $fieldsParam = $fieldsParamGet !== '' ? $fieldsParamGet : $fieldsParamPost;
        $isScheduleSubset = (strtolower(trim($fieldsParam)) === 'schedule_config');
        $isMoveSubset = (strtolower(trim($fieldsParam)) === 'newsletter_campaign_id');

        // When moving to a different collection, refresh the item list so the item
        // appears under the correct collection (fire deleted + created to remove from old
        // and trigger the list to re-render).
        if ($isMoveSubset) {
            $targetCampaignId = (int)($model->newsletter_campaign_id ?? 0);
            $campaign = ($model instanceof NewsletterItem) ? $model->campaign() : null;
            $isArchived = $campaign instanceof NewsletterCampaign && (bool)$campaign->newsletter_campaign_archived;

            // Trigger collections list refresh to update counts. Both side-bar and items-list listen to 'deleted'.
            \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:deleted'), ['id' => (string)$targetCampaignId]);

            // If the target collection is an archive, do no navigate to it, but stay in the current collection
            // and refresh to make the moved item disappear (the 'deleted' event above already handles the list refresh).
            // Navigation in newsletter.php is triggered by 'newsletter_item:created' with a 'campaign_id' param.
            if (!$isArchived) {
                \Components\Support\Htmx::trigger($pageConfig->getEventName('newsletter_item:created'), [
                    'id'          => (string)$targetCampaignId,
                    'campaign_id' => (string)$targetCampaignId
                ]);
            }
        }

        if ($flag || $isScheduleSubset) {
            $item = ($model instanceof NewsletterItem) ? $model : null;
            if (!$item && (int)$id > 0) {
                $item = NewsletterItem::find((int)$id);
            }
            if ($item) {
                echo NewsletterItem::renderStatusBadgeOob($item);
            }
        }
    },
]);

$__html = ob_get_clean();

if ($saveSucceeded && \mh_get('mode') === 'new') {
    // A newly created automation/newsletter should always present the Flow view
    // (not Performance) on the underlying page, mirroring the trigger-install behavior.
    // Map the page mode to its view-mode context / Alpine store id.
    $viewModeContext = ($pageConfig->mode === \Components\Newsletter\PageConfig::MODE_AUTOMATION)
        ? 'trigger'
        : 'newsletter';

    // Show success screen instead of CrudController output
    ob_start();
    $_GET['newsletter_item_id'] = $savedId;
    $_GET['campaign_id'] = $savedCampaignId;
    include BEEZUI_ROOT . '/pages/components/newsletter_item_created_success.php';
    // Persist the Flow view and sync the client-side Alpine store so the underlying
    // page switches to the Flow view right away once the success screen is shown.
    echo \Components\Ui\FlowHelpers::forceFlowView($viewModeContext);
    $__html = ob_get_clean();
}

echo $__html;
