<?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\Base;
use Components\Router;

$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' => '👉 Nudges 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) {
    try { Htmx::trigger('newsletter_item:expandable:refresh', ['id' => (string) $flowId]); } catch (\Throwable $e) { /* ignore */ }
}

// 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.
    try {
        $action = Router::url('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 custom radio card grid (not using RadioCards::render)
    // Supports optional inline SVG icons via $presets[...]['svg']
    ob_start();
    ?>
    <fieldset class="">
        <legend class="block text-sm/6 font-medium text-foreground">Choose a follow-up preset</legend>
        <p class="mt-1 text-xs text-secondary">Pick when and how to follow up based on recipient behavior. You can adjust details later.</p>

        <div class="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
            <?php foreach ($presets as $key => $p):
                $id = 'preset_' . preg_replace('/[^a-z0-9_\-]/i', '_', (string)$key);
                $label = (string)($p['label'] ?? $key);
                $desc  = (string)($p['description'] ?? '');
                $meta  = (string)($p['meta'] ?? '');
                $svg   = isset($p['svg']) ? (string)$p['svg'] : '';
                $checked = ($key === $defaultPresetKey);
            ?>
            <div>
                <input class="sr-only peer" type="radio" name="preset" id="<?php echo Base::h($id); ?>" value="<?php echo Base::h($key); ?>" <?php echo $checked ? 'checked' : ''; ?> />
                <label for="<?php echo Base::h($id); ?>" class="block h-full cursor-pointer rounded-lg border border-gray-200 dark:border-surface-700 bg-white dark:bg-surface-800 p-4 shadow-sm ring-1 ring-inset ring-gray-200 dark:ring-surface-700 hover:ring-brand peer-checked:ring-2 peer-checked:ring-brand peer-checked:border-transparent transition">
                    <div class="flex items-start gap-3">
                        <?php if ($svg !== ''): ?>
                            <div class="mt-0.5 size-6 shrink-0 text-brand" aria-hidden="true">
                                <?php echo $svg; // trusted inline SVG from code-defined presets ?>
                            </div>
                        <?php endif; ?>
                        <div class="min-w-0">
                            <div class="text-sm font-medium text-foreground"><?php echo Base::h($label); ?></div>
                            <?php if ($desc !== ''): ?>
                                <div class="mt-0.5 text-xs text-secondary"><?php echo Base::h($desc); ?></div>
                            <?php endif; ?>
                            <?php if ($meta !== ''): ?>
                                <div class="mt-2 text-[11px] text-muted-foreground"><?php echo Base::h($meta); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </label>
            </div>
            <?php endforeach; ?>
        </div>
    </fieldset>
    <?php
    $fieldset = ob_get_clean();

    ?>
    <div class="p-4">
        <form method="post"
              hx-post="<?php echo Base::h($action); ?>"
              hx-target="#config-modal-body"
              hx-swap="innerHTML">
            <?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 */ }
    echo Htmx::closePanelScript('config-modal');
} else {
    echo $__html;
}
?>
