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

use Components\Resources\Controllers\CrudController;
use Components\Models\NewsletterItem;

ob_start();

mh_load_modules_language_files(MH_DIR_MODULE, 'mb_newsletter');

// 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;
}

echo CrudController::handle([
    'modelClass'    => NewsletterItem::class,
    'selfRoute'     => 'newsletter_item_modal',
    'event_prefix'  => 'newsletter_item',
    'autoclose'     => true,
    'field_presets' => $fieldPresets,
    'on_save' => function ($model, $postAll, $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) {
            $savedCampaignId = (int)($model->newsletter_campaign_id ?? 0);
            $group = $savedCampaignId > 0 ? 'campaign-' . $savedCampaignId : '';
            // 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('newsletter_item:collections:refresh', $group !== '' ? ['group' => $group] : ['id' => (string)$targetId]);
        } else {
            // Edit: refresh the row, flow diagram, and collections counts.
//            \Components\Support\Htmx::trigger('newsletter_item:updated', ['id' => (string)$targetId]);
            \Components\Support\Htmx::trigger('newsletter_item:expandable:refresh', ['id' => (string)$targetId]);
            \Components\Support\Htmx::trigger('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) {
            $targetId = (int)($model->newsletter_campaign_id ?? 0);

            \Components\Support\Htmx::trigger('newsletter_item:deleted', ['id' => (string)$targetId]);
            \Components\Support\Htmx::trigger('newsletter_item:created', ['id' => (string)$targetId]);
        }

        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();
echo $__html;
