<?php
// pages/components/newsletter_item_deepcopy.php
// Deep copy a Newsletter root item (flow) into another campaign (flow collection)

use Components\Router;
use Components\Newsletter\PageConfig;
use Components\Base;
use Components\Models\NewsletterItem;
use Components\Support\Htmx;

$id = (int) mh_get('id', 0, 'int');
$method = (string) \mh_server('REQUEST_METHOD', 'GET');

$error = '';
$result = null; // deepCopy return structure

// Try to load current item for default selection
$itemName = '';
$currentCampaignId = 0;
try {
    if ($id > 0 && class_exists(NewsletterItem::class)) {
        $model = NewsletterItem::find($id);
        if ($model) {
            $arr = $model->toArray();
            $itemName = (string)($arr['newsletter_item_name'] ?? ('#' . $id));
            $currentCampaignId = (int)($arr['newsletter_campaign_id'] ?? 0);
        }
    }
} catch (\Throwable $e) { /* ignore */ }

if ($method === 'POST' && $id > 0) {
    // Read target from POST payload (HTMX form submission)
    $targetCampaignId = (int) mh_post('target_campaign_id', 0, 'int');
    if ($targetCampaignId <= 0) {
        $error = 'Please select a target collection.';
    } elseif (!class_exists('mb_newsletter_items')) {
        $error = 'Legacy newsletter API not available.';
    } else {
        try {
            $result = \mb_newsletter_items::deepCopy($id, $targetCampaignId);
            if (!$result || !is_array($result) || (int)($result['root_new_id'] ?? 0) <= 0) {
                $error = 'Deep copy failed.';
            }
        } catch (\Throwable $e) {
            $error = 'Error: deep copy failed.';
        }
    }
}

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

ob_start();
?>
<div class="space-y-4">
  <?php if ($method === 'POST' && $error === '' && $result): ?>
    <div class="text-sm text-green-700 bg-green-50 rounded p-3">
      Flow was copied to the selected collection.
    </div>
  <?php else: ?>
    <div class="text-sm text-gray-800">

        NOT WORKING CORRECTLY - smart list configurations are not copied.
        <br>
        review and improve \mb_newsletter_items::deepCopy

        - read smart list configurations directly from database

      Select the target collection to copy this flow into.
    </div>

    <?php if ($itemName !== ''): ?>
      <div class="rounded border border-gray-200 bg-gray-50 p-3 text-xs text-gray-700">
        Flow: <?php echo Base::h($itemName); ?> (ID #<?php echo (int)$id; ?>)
      </div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
      <div class="text-sm text-red-700 bg-red-50 rounded p-2"><?php echo Base::h($error); ?></div>
    <?php endif; ?>

    <?php
    $campaignOptions = [];
    try { $campaignOptions = NewsletterItem::campaignOptions(); } catch (\Throwable $e) { $campaignOptions = []; }
    $action = Router::url('newsletter_item_deepcopy', ['partial' => 1, 'id' => $id]);
    ?>
    <form
        hx-post="<?php echo Base::h($action); ?>"
        hx-target="<?= $panelTarget ?>"
        hx-swap="innerHTML"
        class="space-y-3"
    >
      <?= MH_POST_TOKEN ?>
      <label class="block text-xs font-medium text-gray-700 dark:text-gray-200">Target collection</label>
      <select name="target_campaign_id" class="w-full rounded-md border border-gray-300 bg-white px-2 py-1.5 text-sm text-gray-900 shadow-sm focus:border-brand focus:outline-none focus:ring-1 focus:ring-brand dark:bg-slate-800 dark:text-gray-100 dark:border-white/10">
        <option value="">— Select —</option>
        <?php foreach ($campaignOptions as $cid => $opt):
            if (!(is_int($cid) || (is_string($cid) && ctype_digit($cid)))) {
                continue;
            }
            $cid = (int)$cid;
            $label = is_array($opt) ? (string)($opt['label'] ?? ('Campaign ' . $cid)) : (string)$opt;
            $sel = ($cid === $currentCampaignId) ? ' selected' : '';
            ?>
            <option value="<?php echo (int)$cid; ?>"<?php echo $sel; ?>><?php echo Base::h($label); ?></option>
        <?php endforeach; ?>
      </select>

      <div class="flex justify-end gap-2 pt-2">
        <button type="button" class="inline-flex items-center rounded-md border border-gray-200 bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
                onclick="try{document.getElementById('<?= $panelId ?>').close()}catch(e){}">Cancel</button>
        <button type="submit" class="inline-flex items-center rounded-md bg-brand px-3 py-1.5 text-xs font-medium text-white hover:bg-brand/90">Copy</button>
      </div>
    </form>
  <?php endif; ?>
</div>
<?php
// On success: use HX-Trigger events and close the panel via helper script
if ($method === 'POST' && $error === '' && $result) {
    try {
        $newId = (string) ((int) ($result['root_new_id'] ?? 0));
        if ($newId !== '0') {
            // Refine PageConfig from request
            $pageConfig = PageConfig::fromRequest();
            // Optional: load new item to refine mode if needed, but usually request is enough
            if (class_exists(NewsletterItem::class)) {
                $newItem = NewsletterItem::find((int)$newId);
                if ($newItem) {
                    $type = $newItem->scheduleTypeCode();
                    if ($type === 'automation') {
                        $pageConfig = new PageConfig(PageConfig::MODE_AUTOMATION);
                    } elseif ($type === 'bulk_mail' || $type === 'scheduled_window') {
                        $pageConfig = new PageConfig(PageConfig::MODE_NEWSLETTER);
                    }
                }
            }

            // Fire resource-specific created event (Pattern A)
            try { Htmx::trigger($pageConfig->getEventName('newsletter_item:created'), ['id' => $newId]); } catch (\Throwable $e) { /* ignore */ }
            // Also emit a generic updated for consumers that only listen to :updated
            try { Htmx::trigger($pageConfig->getEventName('newsletter_item:updated'), ['id' => $newId]); } catch (\Throwable $e) { /* ignore */ }
            try { Htmx::flushTriggers(); } catch (\Throwable $e) { /* ignore */ }
        }
    } catch (\Throwable $e) { /* ignore */ }
    // Close the modal using standardized helper
    Htmx::parentClose();
}

echo ob_get_clean();
?>
