<?php
// pages/doi_flow.php – Newsletter Double Opt-In (DOI) flow visualization
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\CampaignFlow\FlowBuilder;
use Components\CampaignFlow\FlowViz;
use Components\Base;
use Components\Button;
use Components\ConfigStore;
use Components\Legacy\LegacyRouter;
use Components\Router;
use Components\Ui\Card;
use Components\Ui\FlowHelpers;
use Components\Ui\MarkdownGuide;
use Components\Ui\ModuleIdentity;
use Components\Ui\PageHeader;

$pageKey = 'doi_flow';


// -----------------------------------------------------------------------
// Load optin submodule objects to get admin action routes (edit/preview/test)
// -----------------------------------------------------------------------
$doiDropdownOptin     = ['items' => []]; // DOI email step dropdown
$doiDropdownConfirm   = ['items' => []]; // DOI confirm email step dropdown

$submoduleBase = MH_DIR_FS_CATALOG . MH_ROOT_PATH . 'mailbeez/mb_newsletter/submodules/';

$submoduleFiles = [
    'optin'             => $submoduleBase . 'mb_newsletter_optin.php',
    'optin_customers'   => $submoduleBase . 'mb_newsletter_optin_customers.php',
    'optin_coupon'      => $submoduleBase . 'mb_newsletter_optin_coupon.php',
    'optin_cust_coupon' => $submoduleBase . 'mb_newsletter_optin_customers_coupon.php',
];

// Helper: render a section heading HTML for dropdown subsections
$sectionHeading = function (string $label): string {
    return '<div class="px-4 py-1.5 text-xs font-semibold text-gray-400 uppercase tracking-wider select-none">'
        . Base::h($label, false) . '</div>';
};

// Helper: build dropdown items for a single submodule with a section header
// Note: pass a canonical module override like "mb_newsletter/submodules/mb_newsletter_optin" so
// editor/preview/test routes resolve the correct submodule context (matches winback_advanced pattern).
// Optionally pass coupon config keys so `getAdminActionRoutes()` can add the BeezUI "Configure Coupon" action.
// You can also provide an allowlist of route keys to keep dropdowns focused.
$buildModuleItems = function (
    string $file,
    string $class,
    string $moduleOverride,
    string $sectionLabel,
    ?array $allowRouteKeys = null,
    ?string $couponIdKey = null,
    ?string $couponExpireDaysKey = null
) use ($sectionHeading): array {
    if (!file_exists($file)) {
        return [];
    }
    try {
        require_once $file;
        if (!class_exists($class, false)) {
            return [];
        }
        /** @var \mailbeez_pro $mod */
        $mod = new $class();

        $routes = $mod->getAdminActionRoutes($moduleOverride, $couponIdKey, $couponExpireDaysKey);

        // Filter routes to a focused allowlist (but always keep divider entries).
        if (is_array($allowRouteKeys)) {
            $filtered = [];
            foreach ($routes as $k => $route) {
                if (is_array($route) && !empty($route['divider'])) {
                    $filtered[$k] = $route;
                    continue;
                }
                if (in_array((string)$k, $allowRouteKeys, true)) {
                    $filtered[$k] = $route;
                }
            }
            $routes = $filtered;
        }

        $items = $mod->buildFlowStepDropdownFromAdminRoutes($routes);
        $dropdownItems = is_array($items['items'] ?? null) ? $items['items'] : [];
        if (empty($dropdownItems)) {
            return [];
        }
        return array_merge(
            [['content' => $sectionHeading($sectionLabel)]],
            $dropdownItems
        );
    } catch (\Throwable $e) {
        return [];
    }
};

// Build DOI optin email dropdown (prospects + customers)
$optinProspectItems  = $buildModuleItems(
    $submoduleFiles['optin'],
    'mb_newsletter_optin',
    'mb_newsletter/submodules/mb_newsletter_optin',
    mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects'),
    ['editor', 'preview', 'send_testemail']
);
$optinCustomerItems  = $buildModuleItems(
    $submoduleFiles['optin_customers'],
    'mb_newsletter_optin_customers',
    'mb_newsletter/submodules/mb_newsletter_optin_customers',
    mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers'),
    ['editor', 'preview', 'send_testemail']
);

$doiOptinItems = [];
if (!empty($optinProspectItems)) {
    $doiOptinItems = array_merge($doiOptinItems, $optinProspectItems);
}
if (!empty($optinCustomerItems)) {
    if (!empty($doiOptinItems)) {
        $doiOptinItems[] = ['divider' => true];
    }
    $doiOptinItems = array_merge($doiOptinItems, $optinCustomerItems);
}
if (!empty($doiOptinItems)) {
    $doiDropdownOptin = ['items' => $doiOptinItems];
}

// Build DOI confirm email dropdown (optin_coupon + optin_customers_coupon)
// Include coupon configuration for the DOI confirm email submodules.
$confirmProspectCouponIdKey = 'MAILBEEZ_NEWSLETTER_OPTIN_COUPON_ID';
$confirmProspectCouponExpireKey = 'MAILBEEZ_NEWSLETTER_OPTIN_COUPON_EXPIRE_DAYS';
$confirmCustomerCouponIdKey = 'MAILBEEZ_NEWSLETTER_OPTIN_CUSTOMERS_COUPON_ID';
$confirmCustomerCouponExpireKey = 'MAILBEEZ_NEWSLETTER_OPTIN_CUSTOMERS_COUPON_EXPIRE_DAYS';

$confirmProspectItems  = $buildModuleItems(
    $submoduleFiles['optin_coupon'],
    'mb_newsletter_optin_coupon',
    'mb_newsletter/submodules/mb_newsletter_optin_coupon',
    mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects'),
    ['editor', 'coupon', 'preview', 'send_testemail'],
    $confirmProspectCouponIdKey,
    $confirmProspectCouponExpireKey
);
$confirmCustomerItems  = $buildModuleItems(
    $submoduleFiles['optin_cust_coupon'],
    'mb_newsletter_optin_customers_coupon',
    'mb_newsletter/submodules/mb_newsletter_optin_customers_coupon',
    mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers'),
    ['editor', 'coupon', 'preview', 'send_testemail'],
    $confirmCustomerCouponIdKey,
    $confirmCustomerCouponExpireKey
);

// Helper: derive coupon UI meta (title + icon indicators) for a given submodule
$buildCouponMeta = function (string $file, string $class, string $couponIdKey): array {
    $meta = [
        'title' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_EMAIL_LABEL', 'DOI Confirm Email'),
        'icon_indicators' => [],
    ];
    if (!file_exists($file)) {
        return $meta;
    }
    try {
        require_once $file;
        if (!class_exists($class, false)) {
            return $meta;
        }
        $mod = new $class();
        $couponId = mh_cfg($couponIdKey, '');
        if (is_object($mod) && method_exists($mod, 'get_coupon_type_label')) {
            $label = $mod->get_coupon_type_label($couponId);
            if (is_string($label) && trim($label) !== '') {
                $meta['title'] = $label;
            }
        }
        if (is_object($mod) && method_exists($mod, 'get_icon_indicators')) {
            $ii = $mod->get_icon_indicators($couponId);
            if (is_array($ii)) {
                $meta['icon_indicators'] = $ii;
            }
        }
    } catch (\Throwable $e) {
        return $meta;
    }
    return $meta;
};

$confirmProspectCouponMeta = $buildCouponMeta($submoduleFiles['optin_coupon'], 'mb_newsletter_optin_coupon', $confirmProspectCouponIdKey);
$confirmCustomerCouponMeta = $buildCouponMeta($submoduleFiles['optin_cust_coupon'], 'mb_newsletter_optin_customers_coupon', $confirmCustomerCouponIdKey);

$doiConfirmItems = [];
if (!empty($confirmProspectItems)) {
    $doiConfirmItems = array_merge($doiConfirmItems, $confirmProspectItems);
}
if (!empty($confirmCustomerItems)) {
    if (!empty($doiConfirmItems)) {
        $doiConfirmItems[] = ['divider' => true];
    }
    $doiConfirmItems = array_merge($doiConfirmItems, $confirmCustomerItems);
}
if (!empty($doiConfirmItems)) {
    $doiDropdownConfirm = ['items' => $doiConfirmItems];
}

// -----------------------------------------------------------------------
// Single combined DOI flow (prospects and customers share the same flow shape)
// -----------------------------------------------------------------------
$sitebeezIntegrationCodeUrl = Router::url('sitebeez_integration_code', ['partial' => 1]);
$newsletterSignupUrl = LegacyRouter::url('newsletterSignup');
$newsletterConfirmProspectsUrl = LegacyRouter::url('newsletterConfirm');
$newsletterConfirmCustomersUrl = LegacyRouter::url('newsletterConfirm', ['source' => 'customers']);

$doiConfirmPageDropdown = [
    'items' => [
        [
            'label' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_TITLE', 'DOI Confirm Page')
                . ' - ' . mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects'),
            'icon'  => \Components\Base::SVG_GLOBE,
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'web-preview',
                'data-title' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_TITLE', 'DOI Confirm Page')
                    . ' - ' . mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects'),
                'data-size' => 'full-margin',
                'data-url' => $newsletterConfirmProspectsUrl,
            ],
        ],
        [
            'label' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_TITLE', 'DOI Confirm Page')
                . ' - ' . mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers'),
            'icon'  => \Components\Base::SVG_GLOBE,
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'web-preview',
                'data-title' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_TITLE', 'DOI Confirm Page')
                    . ' - ' . mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers'),
                'data-size' => 'full-margin',
                'data-url' => $newsletterConfirmCustomersUrl,
            ],
        ],
    ],
];
$doiTriggerDropdown = [
    'items' => [
        [
            'label' => mh_lng('UI_DOI_FLOW_TRIGGER_MENU_INTEGRATION_CODE', 'Integration code'),
            'icon'  => \Components\Base::SVG_OUTLINE_CODE,
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'config-modal',
                'data-title' => mh_lng('UI_SITEBEEZ_INTEGRATION_CODE_MODAL_TITLE', 'Site signup integration'),
                'data-size' => '4xl',
                'hx-get' => $sitebeezIntegrationCodeUrl,
                'hx-target' => '#config-modal-body',
                'hx-swap' => 'innerHTML',
            ],
        ],
        [
            'label' => mh_lng('UI_DOI_FLOW_TRIGGER_MENU_NEWSLETTER_SIGNUP', 'Newsletter signup'),
            'icon'  => \Components\Base::SVG_GLOBE,
            'attrs' => [
                'command' => 'show-modal',
                'commandfor' => 'web-preview',
                'data-title' => mh_lng('UI_DOI_FLOW_TRIGGER_MENU_NEWSLETTER_SIGNUP', 'Newsletter signup'),
                'data-size' => 'full-margin',
                'data-url' => $newsletterSignupUrl,
            ],
        ],
        ['divider' => true],
        [
            'label' => mh_lng('UI_DOI_FLOW_TRIGGER_MENU_DOCS_DE', 'Documentation (DE)'),
            'icon'  => \Components\Base::SVG_CHAIN,
            'href'  => 'https://www.mailbeez.de/dokumentation/sitebeez/site_signup',
            'attrs' => [
                'target' => '_blank',
                'rel' => 'noopener noreferrer',
            ],
        ],
        [
            'label' => mh_lng('UI_DOI_FLOW_TRIGGER_MENU_DOCS_EN', 'Documentation (EN)'),
            'icon'  => \Components\Base::SVG_CHAIN,
            'href'  => 'https://www.mailbeez.com/documentation/sitebeez/site_signup',
            'attrs' => [
                'target' => '_blank',
                'rel' => 'noopener noreferrer',
            ],
        ],
    ],
];

$flow = FlowBuilder::make()
    ->trigger('', [
        'stepType' => mh_lng('UI_DOI_FLOW_TRIGGER_SUBTITLE', 'Trigger'),
        'content' => mh_lng('UI_DOI_FLOW_TRIGGER_SIGNUP_FORM_TITLE', 'Signup Form'),
        'icon'      => \Components\Base::SVG_INPUT,
        'color'     => 'blue',
        'dropdown'  => $doiTriggerDropdown,
    ])
    ->wait(mh_lng('UI_DOI_FLOW_WAIT_INSTANT', 'instant'))
    ->branch([
        // DOI prospects
        function (FlowBuilder $b) use ($doiDropdownOptin, $optinProspectItems): void {
            $dropdown = !empty($optinProspectItems) ? ['items' => $optinProspectItems] : $doiDropdownOptin;
            $b
                ->mail('doi_email_prospect', '', [
                    'stepType' => mh_lng('UI_DOI_FLOW_DOI_EMAIL_TITLE', 'DOI Email'),
                    'content' => mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects'),
                    'icon'     => \Components\Base::SVG_MAIL_QUESTION_MARK,
                    'color'    => 'green',
                    'dropdown' => $dropdown,
                ]);
        },
        // DOI customers
        function (FlowBuilder $b) use ($doiDropdownOptin, $optinCustomerItems): void {
            $dropdown = !empty($optinCustomerItems) ? ['items' => $optinCustomerItems] : $doiDropdownOptin;
            $b
                ->mail('doi_email_customers', '', [
                    'stepType' => mh_lng('UI_DOI_FLOW_DOI_EMAIL_TITLE', 'DOI Email'),
                    'content' => mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers'),
                    'icon'     => \Components\Base::SVG_MAIL_QUESTION_MARK,
                    'color'    => 'brand',
                    'dropdown' => $dropdown,
                ])
            ;
        },
    ], ['gap' => 'sm'])
    ->merge([], ['gap' => 'sm'])
    ->wait(
        mh_lng('UI_DOI_FLOW_WAIT_SUBSCRIBER_CLICKS_LINK', 'subscriber clicks link'),
        ['icon' => \Components\Base::SVG_CURSOR_RAYS]
    )
    ->action(mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_TITLE', 'DOI Confirm Page'), [
        'id'       => 'doi_confirm_page',
        'subtitle' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_PAGE_SUBTITLE', 'Landing Page'),
        'icon'     => \Components\Base::SVG_GLOBE,
        'color'    => 'teal',
        'dropdown' => $doiConfirmPageDropdown,
    ])
    ->wait(mh_lng('UI_DOI_FLOW_WAIT_INSTANT', 'instant'))
    ->branch([
        // DOI confirm email: prospects
        function (FlowBuilder $b) use ($doiDropdownConfirm, $confirmProspectItems, $confirmProspectCouponMeta): void {
            $dropdown = !empty($confirmProspectItems) ? ['items' => $confirmProspectItems] : $doiDropdownConfirm;
            $b
                ->mail('doi_confirm_email_prospect', '', [
                    'stepType' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_EMAIL_LABEL', 'DOI Confirm Email'),
                    'content' => mh_lng('UI_DOI_FLOW_PROSPECTS_LABEL', 'Prospects') . ' - ' . (string)($confirmProspectCouponMeta['title']),
                    'icon'     => \Components\Base::SVG_MAIL_CHECK,
                    'color'    => 'green',
                    'dropdown' => $dropdown,
                    'icon_indicators' => $confirmProspectCouponMeta['icon_indicators'] ?? [],
                ]);
        },
        // DOI confirm email: customers
        function (FlowBuilder $b) use ($doiDropdownConfirm, $confirmCustomerItems, $confirmCustomerCouponMeta): void {
            $dropdown = !empty($confirmCustomerItems) ? ['items' => $confirmCustomerItems] : $doiDropdownConfirm;
            $b
                ->mail('doi_confirm_email_customers', '', [
                    'stepType' => mh_lng('UI_DOI_FLOW_DOI_CONFIRM_EMAIL_LABEL', 'DOI Confirm Email'),
                    'content' => mh_lng('UI_DOI_FLOW_CUSTOMERS_LABEL', 'Customers') . ' - ' . (string)($confirmCustomerCouponMeta['title']),
                    'icon'     => \Components\Base::SVG_MAIL_CHECK,
                    'color'    => 'brand',
                    'dropdown' => $dropdown,
                    'icon_indicators' => $confirmCustomerCouponMeta['icon_indicators'] ?? [],
                ])
            ;
        },
    ], ['gap' => 'sm'])
    ->toArray();

$refreshUrl = Router::url('doi_flow', ['partial' => 1]);

$renderFlowBody = function () use ($flow, $refreshUrl): string {
    ob_start();
    ?>
    <div id="doi-flow-body"
         x-cloak
         hx-get="<?php echo Base::h($refreshUrl); ?>"
         hx-trigger="module_config:updated from:body"
         hx-target="#doi-flow-body"
         hx-select="#doi-flow-body"
         hx-swap="outerHTML"
         hx-disinherit="*"
         data-no-global-loader="1"
         x-data="<?= Base::h(FlowHelpers::alpineData(), false); ?>"
         x-init="update(); $nextTick(() => update()); setTimeout(() => update(), 60)"
         @resize.window.debounce.120="update()"
         class="<?= Card::flowClasses() ?>"
    >
            <?= FlowHelpers::renderScrollHints(); ?>
            <div x-ref="scroller" @scroll.passive="update()" class="relative overflow-x-auto overflow-y-hidden">
                <div class="inline-block relative z-10 p-8">
                    <?= FlowViz::render($flow, [
                        'orientation' => 'horizontal',
                        'size'        => 'sm',
                        'editable'    => false,
                        'class'       => '',
                    ]); ?>
                </div>
            </div>
    </div>
    <?php
    return ob_get_clean();
};

$flowBodyHtml = $renderFlowBody();

if ((int)mh_request('partial', 0) === 1) {
    echo $flowBodyHtml;
    return;
}

$doiModuleKey = 'mb_newsletter';
$doiIsOn = ConfigStore::isModuleOn($doiModuleKey);
$doiIdentity = [
    'key'      => $doiModuleKey,
    'title'    => mh_lng('UI_DOI_FLOW_CARD_TITLE', 'Double Opt-In Flow'),
    'desc'     => mh_lng('UI_DOI_FLOW_SUBTITLE', 'Visualisation of the double opt-in flow for newsletter signups'),
    'color'    => 'bg-brand/70 text-white',
    'svg_icon' => Base::SVG_OUTLINE_TOGGLE,
];

ob_start();
?>

<?= PageHeader::render(mh_lng('UI_DOI_FLOW_TITLE', 'Newsletter Double Opt-In'), [
    'subtitle' => mh_lng('UI_DOI_FLOW_SUBTITLE', 'Visualisation of the double opt-in flow for newsletter signups'),
]); ?>

<div class="<?= Card::listStackClass(); ?> mt-8">
    <div
         class="<?= Base::h(Card::baseContainerClass(false)); ?>"
         data-no-global-loader="1" data-no-local-loader="1"
    >
        <div class="flex items-start justify-between p-3">
            <div class="truncate relative flex flex-grow items-center leading-none">
                <?= ModuleIdentity::render($doiIdentity, [
                    'is_on'      => $doiIsOn,
                    'desc_class' => 'text-nowrap text-ellipsis',
                ]); ?>
            </div>
            <div class="shrink-0 self-center flex items-center gap-2">
            </div>
        </div>

        <?= $flowBodyHtml; ?>
    </div>

    <div
        class="<?= Base::h(Card::baseContainerClass(false)); ?>"
        data-no-global-loader="1" data-no-local-loader="1"
    >
        <div class="p-4">
            <?= MarkdownGuide::renderFromFileLocalized('docs/doi_flow_guide.md', [
                'baseDir' => defined('BEEZUI_ROOT') ? (string) BEEZUI_ROOT : getcwd(),
                'headingLevel' => 2,
                'openFirst' => false,
                'title' => mh_lng('UI_DOI_FLOW_GUIDE_TITLE', 'DOI Quick Guide'),
                'idPrefix' => 'doi-flow-guide',
                'showControls' => false,
            ]); ?>
        </div>
    </div>
</div>

<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
