<?php
// pages/components/newsletter_item_create_followup.php
// Creates a follow-up Newsletter Item using legacy mb_newsletter_items::copy(...) and refreshes the flow

use Components\Support\Htmx;
use Components\Newsletter\PageConfig;
use Components\Base;
use Components\Router;
use Components\Models\NewsletterItem;
use Components\Form\RadioCards;
require_once(MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter.php');

$newsletterId = (int) mh_get('newsletter_id', 0, 'int');
$campaignId   = (int) mh_get('campaign_id', 0, 'int');
// flow_id equals the rootId for the expandable flow we need to refresh
$flowId       = (int) mh_get('flow_id', 0, 'int');

$error = '';
$insertId = 0;

// Define meaningful presets for follow-up creation
// Each preset provides: label, description, event, condition
$presets = [
    'non_openers_2d' => [
        'label' => 'Remind non-openers in 2 days',
        'description' => 'Send a gentle reminder to recipients who did not open the original email after 2 days.',
        'event' => 'date_sent',
        'condition' => 'opened',
        'delay_days' => 2,
        'meta' => 'Delay: 2 days · Event: Not opened',
    ],
    'opened_no_click_3d' => [
        'label' => 'Nudge opens without clicks (3 days)',
        'description' => 'Target recipients who opened but didn’t click any link after 3 days.',
        'event' => 'opened',
        'condition' => 'clicked',
        'delay_days' => 3,
        'meta' => 'Delay: 3 days · Event: Opened · Condition: No clicks',
    ],
    'no_purchase_7d' => [
        'label' => 'No purchase after 7 days',
        'description' => 'Follow up after a week if no purchase has been made.',
        'event' => 'clicked',
        'condition' => 'ordered',
        'delay_days' => 7,
        'meta' => 'Delay: 7 days · Event: No order',
    ]
];

$defaultPresetKey = 'non_openers_2d';

// Optional direct params for Smart List trigger (for backward compatibility)
$smartlistEvent = (string) mh_get('smartlist_event', '');
$smartlistCondition = (string) mh_get('smartlist_condition', '');
$presetKey = (string) mh_post('preset', '');
// Optional delay in days; if not provided, presets or backend default (5 days) will apply
$smartlistDelayDays = (int) mh_get('smartlist_delay_days', -1, 'int');

// If a preset was chosen, map it to event/condition
if ($presetKey !== '' && isset($presets[$presetKey])) {
    $smartlistEvent = (string)($presets[$presetKey]['event'] ?? $smartlistEvent);
    $smartlistCondition = (string)($presets[$presetKey]['condition'] ?? $smartlistCondition);
    if (isset($presets[$presetKey]['delay_days'])) {
        $smartlistDelayDays = (int) $presets[$presetKey]['delay_days'];
    }
}

// Only attempt to create when we have a defined event (either from preset or direct params)
$didAttemptCreate = false;
try {
    if ($newsletterId <= 0 || $campaignId <= 0) {
        $error = 'Missing or invalid parameters (newsletter_id, campaign_id).';
    } elseif ($smartlistEvent !== '' || $smartlistCondition !== '') {
        $didAttemptCreate = true;
        if (!class_exists('mb_newsletter_items') || !class_exists('mb_newsletter')) {
            $error = 'Legacy newsletter classes not available.';
        } else {
            // Create follow-up using legacy API
            $insertId = (int) \mb_newsletter_items::copy(
                $newsletterId,
                $campaignId,
                \mb_newsletter::ITEM_TYPE_FOLLOWUP,
                (string)$smartlistEvent,
                (string)$smartlistCondition,
                ($smartlistDelayDays >= 0 ? (int)$smartlistDelayDays : null)
            );
            if ($insertId <= 0) {
                $error = 'Failed to create follow-up.';
            }
        }
    }
} catch (\Throwable $e) {
    $error = 'Error: unable to create follow-up.';
}

// Queue HTMX trigger for the expandable flow refresh when successful
if ($didAttemptCreate && $error === '' && $flowId > 0) {
    NewsletterItem::invalidateFlowCacheById((int)$flowId);
    $pageConfig = PageConfig::fromRequest();
    if (class_exists(NewsletterItem::class)) {
        $root = NewsletterItem::find($flowId);
        if ($root) {
            $type = $root->scheduleTypeCode();
            if ($type === 'automation') {
                $pageConfig = new PageConfig(PageConfig::MODE_AUTOMATION);
            } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
                $pageConfig = new PageConfig(PageConfig::MODE_NEWSLETTER);
            }
        }
    }
    try { Htmx::trigger($pageConfig->getEventName('newsletter_item:expandable:refresh'), ['id' => (string) $flowId]); } catch (\Throwable $e) { /* ignore */ }
}

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

// Capture minimal inline HTML response for the modal body
ob_start();
if ($didAttemptCreate) {
    if ($error !== '') {
        ?>
        <div class="p-4">
            <div class="rounded-md bg-red-50 text-red-800 text-sm px-3 py-2"><?php echo Base::h($error); ?></div>
            <div class="mt-3 text-xs text-secondary">newsletter_id=#<?php echo (int)$newsletterId; ?>, campaign_id=#<?php echo (int)$campaignId; ?>, flow_id=#<?php echo (int)$flowId; ?></div>
        </div>
        <?php
    }
} else {
    // No attempt yet -> render preset selection form
    // Prefer routing to this component explicitly to avoid posting to a full page URL
    // which can cause the entire page to be swapped into the modal body.
    $pageConfig = PageConfig::fromRequest();
    try {
        $action = $pageConfig->getBaseUrl('newsletter_item_create_followup', [
            'partial' => 1,
            'newsletter_id' => (int)$newsletterId,
            'campaign_id' => (int)$campaignId,
            'flow_id' => (int)$flowId,
        ]);
    } catch (\Throwable $e) {
        $action = isset($_SERVER['REQUEST_URI']) ? (string)$_SERVER['REQUEST_URI'] : '';
    }

    // Build standardized RadioCards options
    $radioOptions = [];
    foreach ($presets as $key => $p) {
        $radioOptions[$key] = [
            'label' => (string)($p['label'] ?? $key),
            'description' => (string)($p['description'] ?? ''),
            'meta' => (string)($p['meta'] ?? ''),
        ];
    }

    $fieldset = RadioCards::render(
        'preset',
        'Choose a follow-up preset',
        $radioOptions,
        $defaultPresetKey,
        [
            'help' => 'Pick when and how to follow up based on recipient behavior. You can adjust details later.',
            'grid' => ['base' => 1, 'sm' => 2],
        ]
    );

    ?>
    <div class="p-4">
        <form method="post"
              hx-post="<?php echo Base::h($action); ?>"
              hx-target="<?= $panelTarget ?>"
              hx-swap="innerHTML">
            <?php echo MH_POST_TOKEN; ?>
            <?php echo $fieldset; ?>
            <input type="hidden" name="newsletter_id" value="<?php echo (int)$newsletterId; ?>" />
            <input type="hidden" name="campaign_id" value="<?php echo (int)$campaignId; ?>" />
            <input type="hidden" name="flow_id" value="<?php echo (int)$flowId; ?>" />

            <div class="mt-4 flex items-center justify-between">
                <div class="text-xs text-gray-500 dark:text-gray-400">Follow-ups are created as part of the current flow.</div>
                <button type="submit" class="inline-flex items-center rounded-md bg-brand px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand/90 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand">
                    Create follow-up
                </button>
            </div>
        </form>
    </div>
    <?php
}

// Finalize response: on success, emit HX-Trigger header, close the modal and produce no body output
$__html = ob_get_clean();
if ($didAttemptCreate && $error === '') {
    try { Htmx::flushTriggers(); } catch (\Throwable $e) { /* ignore */ }
    Htmx::parentClose();
} else {
    echo $__html;
}
?>
