<?php
// pages/trigger.php (renamed from campaigns.php)
require_once BEEZUI_ROOT . '/components/index.php';
require_once BEEZUI_ROOT . '/pages/layout.php';

use Components\ModuleLoader;
use Components\SortStore;
use Components\Router;
use Components\Ui\Tabs;
use Components\Ui\FlowHelpers;
use Components\Data\Live\LiveBeezUIConfigStoreProvider;
$pageKey = 'trigger';
$targetContainer = \Components\Data\DataRegistry::navigation()->getTargetId($pageKey);
$subtabParam = \Components\Router::subtabParam();


// Handle save via HTMX POST for campaign sorting (moved from campaigns_sort.php)
if ((mh_server('REQUEST_METHOD', 'GET') === 'POST') && mh_post('order', null) !== null) {
    // Accept either comma-separated string or JSON array under 'order'
    $raw = (string) mh_post('order', '', 'string');
    $list = [];
    if ($raw !== '') {
        if ($raw[0] === '[') {
            $decoded = json_decode($raw, true);
            if (is_array($decoded)) {
                foreach ($decoded as $v) {
                    if (is_string($v)) $list[] = $v;
                }
            }
        } else {
            $parts = explode(',', $raw);
            foreach ($parts as $p) {
                $p = trim($p);
                if ($p !== '') $list[] = $p;
            }
        }
    }
    SortStore::setCampaignOrderFromList($list);

    // Preserve all current URL parameters except routing/partial flags
    $keep = [];
    $pageParam = Router::pageParam();
    $tabParam = Router::tabParam();
    foreach (\Components\Common\Request::all('get') as $k => $v) {
        if ($k === 'partial' || $k === $pageParam || $k === $tabParam) continue;
        $keep[$k] = $v;
    }
    header('HX-Redirect: ' . Router::url('trigger', $keep));
    exit;
}

// Load campaign modules grouped by e-commerce touchpoints from a single source
$modulesByTouchpoint = ModuleLoader::campaignsByGroup();


// Optional group filter coming from Wizard (or direct navigation)
$selectedGroup = mh_get('group', '', 'string');
$selectedGroup = trim($selectedGroup);
$hasFilter = $selectedGroup !== '' && isset($modulesByTouchpoint[$selectedGroup]);
if ($hasFilter) {
    $modulesByTouchpoint = [$selectedGroup => $modulesByTouchpoint[$selectedGroup]];
}

// Apply persisted sort order within groups (0 = top)
$modulesByTouchpoint = SortStore::applyOrderToGrouped($modulesByTouchpoint);

// Read and validate layout mode
$allowedLayouts = ['list', 'tiles', 'compact'];
$layout = mh_get('layout', 'list', 'string');
if (!in_array($layout, $allowedLayouts, true)) {
    $layout = 'tiles';
}

// Read grouping mode and persist per-user similar to MAILBEEZ_CONFIG_BEEZ_UI_LIST_LAYOUT
// Only affects list layout visually, but we keep/persist it consistently via URL+storage
$provider = new LiveBeezUIConfigStoreProvider();
$groupedListId = 'trigger_list_grouped';
$getParams = \Components\Common\Request::all('get');
if (isset($getParams['grouped'])) {
    $grouped = mh_get('grouped', 1, 'int') ? 1 : 0;
    $provider->setListGrouped($groupedListId, (bool)$grouped);
} else {
    $grouped = $provider->getListGrouped($groupedListId, true) ? 1 : 0;
}

$viewMode = $provider->getViewMode($pageKey);

// Read and validate sub-tab selection
$allowedTabs = ['prebuild', 'custom'];
$subtab = mh_get($subtabParam, 'prebuild', 'string');
if (!in_array($subtab, $allowedTabs, true)) {
    $subtab = 'prebuild';
}

// Show/Hide inactive items toggle (1 = show inactive, 0 = hide inactive)
// Server-side flag kept for initial render and non-JS fallback. Client-side toggling is done via Alpine store.
$showInactive = mh_get('show_inactive', 1, 'int') ? 1 : 0;

// Helper to build a campaigns URL keeping current filters (Alpine handles inactive filtering client-side)
$baseArgs = ['partial' => 1, 'layout' => $layout, $subtabParam => $subtab, 'grouped' => $grouped];
if ($hasFilter) {
    $baseArgs['group'] = $selectedGroup;
}

$addAutomationTitle = \mh_lng('UI_ADD_AUTOMATION', 'Add Automation');
$newAutomationFlowTitle = \mh_lng('UI_NEW_AUTOMATION_FLOW', 'New Automation Item');
$installAutomationUrl = \Components\Router::url('trigger_install_dialog', ['partial' => 1, 'layout' => $layout, 'group' => $selectedGroup]);
$customAutomationUrl = \Components\Router::url('newsletter_audience_selection_modal', ['partial' => 1, 'step' => 'existing', 'page_mode' => 'automation']);
$headerAddAutomationPrebuildAttrs = [
    'command' => 'show-modal',
    'commandfor' => 'config-modal',
    'data-title' => $addAutomationTitle,
    'data-size' => '5xl',
    'hx-get' => $installAutomationUrl,
    'hx-target' => '#config-modal-body',
    'hx-swap' => 'innerHTML',
    'data-no-global-loader' => 'true',
];

$headerAddAutomationCustomAttrs = [
    'command' => 'show-modal',
    'commandfor' => 'config-modal',
    'data-title' => $newAutomationFlowTitle,
    'data-size' => '5xl',
    'hx-get' => $customAutomationUrl,
    'hx-target' => '#config-modal-body',
    'hx-swap' => 'innerHTML',
    'hx-push-url' => 'false',
    'data-no-global-loader' => 'true',
    'data-no-local-loader' => 'true',
];

// SECTION partial rendering helpers
$renderPrebuild = function () use ($modulesByTouchpoint, $hasFilter, $selectedGroup, $layout, $targetContainer, $subtabParam, $baseArgs, $grouped, $showInactive, $addAutomationTitle, $installAutomationUrl) {

    $installAutomationAttrs = [
        'command' => 'show-modal',
        'commandfor' => 'config-modal',
        'data-title' => $addAutomationTitle,
        'data-size' => '5xl',
        'hx-get' => $installAutomationUrl,
        'hx-target' => '#config-modal-body',
        'hx-swap' => 'innerHTML',
        'data-no-global-loader' => 'true',
    ];

    $installedModuleCount = 0;
    foreach ($modulesByTouchpoint as $__mods) {
        if (!is_array($__mods)) {
            continue;
        }
        $installedModuleCount += count($__mods);
    }

    ob_start();
    ?>
    <div>
        <?php

        if ($installedModuleCount === 0) {
            ?>
            <?= \Components\Ui\EmptyState::render([
                'icon' => \Components\Base::SVG_TRIGGER,
                'icon_color' => 'bg-brand/70 text-white/90',
                'title' => \mh_lng('UI_TRIGGER_EMPTY_TITLE', 'No automations active yet'),
                'text' => \mh_lng('UI_TRIGGER_EMPTY_TEXT', 'Install an automation module to trigger emails automatically, for example after signup, order placement, or cart abandonment.'),
//                'grid_buttons' => [
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_SIGNUP', 'After signup'),
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_ORDER', 'After order'),
//                    \mh_lng('UI_TRIGGER_EMPTY_EXAMPLE_CART', 'Cart abandonment'),
//                ],
                'action' => [
                    'label' => \mh_lng('UI_TRIGGER_EMPTY_ACTION', 'Choose automation module'),
                    'icon' => \Components\Base::SVG_PLUS,
                    'iconPosition' => 'front',
                    'size' => 'sm',
                    'variant' => 'primary',
                    'attrs' => $installAutomationAttrs,
                ],
            ]); ?>
            <?php
            return ob_get_clean();
        }

        // Render selected layout from extracted partials
        $partialMap = [
            'tiles' => __DIR__ . '/components/trigger_layout_tiles.php',
            'list' => __DIR__ . '/components/trigger_layout_list.php',
            'compact' => __DIR__ . '/components/trigger_layout_compact.php',
        ];
        $partial = $partialMap[$layout] ?? $partialMap['tiles'];
        include $partial; // expects $modulesByTouchpoint in scope
        ?>
        <script>
            (function () {
                try {
                    var refreshUrl = <?= json_encode(\Components\Router::url('trigger', $baseArgs)); ?>;
                    function refresh() {
                        try { htmx.ajax('GET', refreshUrl, '<?= $targetContainer; ?>'); } catch (e) {}
                    }
                    window.addEventListener('campaigns-sort-saved', function () { setTimeout(refresh, 50); });
                } catch (e) {}
            })();
        </script>
    </div>
    <?php
    return ob_get_clean();
};

$renderCustom = function () {
    // Automation newsletters are technically newsletters, but in UX they are treated as Automations.
    // Here we load the newsletter page in automation mode as a partial for this tab.
    $originalGet = $_GET;
    $_GET['page_mode'] = 'automation';
    $_GET['partial'] = 1;
    $isNewsletterInclude = true;
    $result = require BEEZUI_ROOT . '/pages/newsletter.php';
    $_GET = $originalGet;
    return $result;
};

// Serve partial section only (for htmx lazy-load containers)
$section = mh_get('section', '', 'string');
if (mh_get('partial', 0, 'int') && ($section === 'prebuild' || $section === 'custom')) {
    if ($section === 'prebuild') {
        echo $renderPrebuild();
    } else {
        echo $renderCustom();
    }
    exit;
}

// Build URLs for section lazy loads
$prebuildSectionUrl = \Components\Router::url('trigger', array_merge(
    $hasFilter ? ['group' => $selectedGroup] : [],
    ['partial' => 1, 'section' => 'prebuild', 'layout' => $layout, $subtabParam => 'prebuild', 'grouped' => $grouped]
));
$customSectionUrl = \Components\Router::url('trigger', array_merge(
    $hasFilter ? ['group' => $selectedGroup] : [],
    ['partial' => 1, 'section' => 'custom', 'layout' => 'tiles', $subtabParam => 'custom']
));
$customSectionTrigger = ($subtab === 'custom')
    ? 'trigger:refresh from:body'
    : 'revealed once, trigger:refresh from:body';

// Prepare tab items once for Tabs component rendering
$tabItems = [
    ['value' => 'prebuild', 'label' => mh_lng('MAILBEEZ_MODULES', 'MailBeez Flows')],
    // To enable the Custom tab in the UI, uncomment the next line:
     ['value' => 'custom', 'label' => mh_lng('MAILBEEZ_CUSTOM', 'Custom')],
];

ob_start();
?>
<div x-data="{ tab: '<?= $subtab; ?>' }"
     @automation:newsletter_item:created.window="tab = 'custom'"
     @mb:open-automation.window="tab = 'custom'"
     @mb:open-item.window="if ($event.detail.key && $event.detail.key.startsWith('automation-flow:')) tab = 'custom'"
     @mb:open-module.window="if (!$event.detail.module.startsWith('automation-flow:')) tab = 'prebuild'"
     @mb:navigate.window="if ($event.detail.active === 'trigger' && $event.detail.params && $event.detail.params['<?= $subtabParam ?>']) tab = $event.detail.params['<?= $subtabParam ?>']">
    <div>
        <?php
        $viewModeToggle = FlowHelpers::renderGlobalToggle($pageKey);

        $headerRight = \Components\Button::render(\mh_lng('UI_ADD_AUTOMATION', 'Add Automation'), [
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'md',
                'variant' => 'secondary',
                'attrs' => array_merge($headerAddAutomationPrebuildAttrs, [
                    'x-show' => "tab !== 'custom'",
                    'x-cloak' => true,
                ]),
            ])
            .
            \Components\Button::render(\mh_lng('UI_NEW_CUSTOM_AUTOMATION', 'New Automation'), [
                'icon' => \Components\Base::SVG_PLUS,
                'iconPosition' => 'front',
                'size' => 'md',
                'variant' => 'secondary',
                'attrs' => array_merge($headerAddAutomationCustomAttrs, [
                    'x-show' => "tab === 'custom'",
                    'x-cloak' => true,
                ]),
            ]);

        echo \Components\Ui\PageHeader::render(mh_lng('MAILBEEZ_APP_LABEL_AUTOMATIONS', 'Automations'), [
                'subtitle' => mh_lng('MAILBEEZ_APP_DESC_AUTOMATIONS', 'Automate your marketing campaigns with MailBeez Flows.'),
                'center' => $viewModeToggle,
                'right' => '<div class="flex gap-2 items-center">' . $headerRight. '</div>',

        ]);
        ?>
    </div>
    <script>
        // Initialize Alpine store for Trigger page filters (used by list layouts and toolbar pill)
        (function () {
            try {
                var seed = <?= $showInactive ? 'true' : 'false'; ?>;
                var viewModeSeed = <?= json_encode($viewMode); ?>;
                function ensureTriggerStore() {
                    try {
                        if (!window.Alpine) return;
                        if (!Alpine.store('trigger')) {
                            Alpine.store('trigger', { 
                                showInactive: seed,
                                viewMode: viewModeSeed
                            });
                        }
                    } catch (e) {}
                }
                // If Alpine is already present, initialize immediately; otherwise wait for alpine:init
                if (window.Alpine && typeof Alpine.store === 'function') {
                    ensureTriggerStore();
                } else {
                    document.addEventListener('alpine:init', ensureTriggerStore, { once: true });
                }
            } catch (e) {}
        })();
    </script>
    <!-- Tabs: mobile select via reusable component -->
    <?= Tabs::mobile('tab', $tabItems, ['ariaLabel' => \mh_lng('UI_SELECT_TAB', 'Select a tab')]); ?>

    <!-- Tabs: desktop nav via reusable component (actions remain on the right) -->
    <div class="hidden sm:block" x-cloak>
        <div class="border-b border-divider">
            <div class="flex items-center justify-between">
                <?= Tabs::desktopNavOnly('tab', $tabItems); ?>
<?php

                // (Ungroup / Group by touchpoint actions live inside the list layout dropdown menu)
?>
                <?php
                // Alpine-driven Show/Hide Inactive pill (client-side only). No HTMX requests.
                $labelShowAll = mh_lng('UI_SHOWING_ALL', 'Showing all');
                $labelHidden  = mh_lng('UI_INACTIVE_HIDDEN', 'Inactive hidden');
                $titleShow    = mh_lng('UI_SHOW_INACTIVE', 'Show inactive');
                $titleHide    = mh_lng('UI_HIDE_INACTIVE', 'Hide inactive');
                ?>
                <button type="button"
                        x-show="tab === 'prebuild' && !($store.trigger && $store.trigger.showInactive)"
                        x-cloak
                        class="inline-flex items-center font-semibold rounded-full focus:ring-4 text-sm px-2 py-1.5 gap-x-1.5 ring-1 transition-colors"
                        :class="$store.trigger && $store.trigger.showInactive ? 'ring-gray-200 bg-gray-50 text-secondary hover:bg-gray-100' : 'ring-amber-200 bg-amber-50 text-amber-700 hover:bg-amber-100'"
                        @click="$store.trigger && ($store.trigger.showInactive = !$store.trigger.showInactive)"
                        :title="$store.trigger && $store.trigger.showInactive ? $el.dataset.titleHide : $el.dataset.titleShow"
                        data-title-show="<?= \Components\Base::h($titleShow, false); ?>"
                        data-title-hide="<?= \Components\Base::h($titleHide, false); ?>"
                >
                    <span x-show="$store.trigger && $store.trigger.showInactive" class="[&_svg]:size-4" aria-hidden="true"><?php echo \Components\Base::SVG_EYE; ?></span>
                    <span x-show="!($store.trigger && $store.trigger.showInactive)" class="[&_svg]:size-4" aria-hidden="true"><?php echo \Components\Base::SVG_EYE_SLASH; ?></span>
                    <span x-show="$store.trigger && $store.trigger.showInactive"><?php echo \Components\Base::h($labelShowAll); ?></span>
                    <span x-show="!($store.trigger && $store.trigger.showInactive)"><?php echo \Components\Base::h($labelHidden); ?></span>
                </button>
            </div>
        </div>
    </div>

    <!-- Content Sections (lazy-loaded) -->
    <div x-show="typeof tab === 'undefined' || tab === 'prebuild'"
         x-cloak
         id="prebuild-section"
         hx-trigger="trigger:refresh from:body"
         hx-get="<?= $prebuildSectionUrl; ?>"
         hx-swap="innerHTML"
    >
        <?= $renderPrebuild(); ?>
    </div>

    <div x-show="typeof tab !== 'undefined' && tab === 'custom'" x-cloak
         id="custom-section"
         hx-trigger="<?= \Components\Base::h($customSectionTrigger, false); ?>"
         hx-get="<?= $customSectionUrl; ?>"
         hx-swap="innerHTML">
        <?= $subtab === 'custom' ? $renderCustom() : ''; ?>
    </div>
</div>
<?php
$content = ob_get_clean();

echo layout($pageKey, $content);
