<?php

use Components\Legacy\LegacyRouter;
use Components\Router;

LegacyRouter::add('sendTest', mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'test', [
    'allowed' => ['lng_id', 'module', 'maintemplate_id'],
    'defaults' => [],
]);

LegacyRouter::add('preview', mh_cfg('MAILBEEZ_MAILHIVE_URL') . 'view&format=html&realview=true', [
    'allowed' => ['lng_id', 'module', 'maintemplate_id', 'content_module_id', 'template_id', 'gnd'],
    'defaults' => ['gnd' => 'unknown'],
]);

LegacyRouter::add('templateSelect', function ($params = []) {
    $context = $params['context'] ?? mh_get('context', 'module');
    if ($context === 'module') {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_module.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_module.php';
    } else {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_common.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_common.php';
    }
    return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&app_action=select');
}, [
    'allowed' => ['module', 'lng_id', 'newsletter_id', 'flow_id', 'template_id', 'context', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('mainEditor', function ($params = []) {
    $module = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'config_tmplmngr_lng' : 'config_tmplmngr';
    $appPath = 'configbeez/' . $module . '/admin_application_plugins/cfg_language_common.php';
    return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&module=' . $module);
}, [
    'allowed' => ['maintemplate_id'],
    'defaults' => [],
]);

LegacyRouter::add('visualEditor', function ($params = []) {
    $context = $params['context'] ?? mh_get('context', 'module');
    if ($context === 'newsletter') {
        $appPath = 'mailbeez/mb_newsletter/admin_application_plugins/visual_editor.php';
    } else {
        $templateManager = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'config_tmplmngr_lng' : 'config_tmplmngr';
        $appPath = 'configbeez/' . $templateManager . '/admin_application_plugins/visual_editor.php';
    }

    $baseUrl = mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&popup=true');
    if (mh_cfg('MAILBEEZ_FILTER_ADD_GENDER_STATUS') === 'True') {
        $baseUrl .= '&gnd=unknown';
    }

    if ($context === 'main') {
        if (empty($params['maintemplate_id'])) {
            $baseUrl .= '&maintemplate_id=MAIN';
        }
        if (empty($params['content_module_id'])) {
            $baseUrl .= '&content_module_id=MAIN';
        }
    }

    return $baseUrl;
}, [
    'allowed' => ['newsletter_id', 'flow_id', 'lng_id', 'module', 'maintemplate_id', 'content_module_id', 'gnd'],
    'defaults' => [],
]);

LegacyRouter::add('autosave', function ($params = []) {
    $context = $params['context'] ?? mh_get('context', 'module');
    if ($context === 'newsletter') {
        $appPath = 'mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php';
    } else {
        $templateManager = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'config_tmplmngr_lng' : 'config_tmplmngr';
        $appPathAuto = ($context === 'main') ? 'cfg_language_common.php' : 'cfg_language_module.php';
        $appPath = 'configbeez/' . $templateManager . '/admin_application_plugins/' . $appPathAuto;
    }

    $baseUrl = mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&app_action=save_meta_htmx');
    if ($context === 'main') {
        if (empty($params['maintemplate_id'])) {
            $baseUrl .= '&maintemplate_id=MAIN';
        }
        if (empty($params['content_module_id'])) {
            $baseUrl .= '&content_module_id=MAIN';
        }
    }
    return $baseUrl;
}, [
    'allowed' => ['newsletter_id', 'flow_id', 'lng_id', 'module', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('stylingEditor', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_styling.php'), [
    'allowed' => ['module', 'lng_id', 'context', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateCreate', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_templates.php&app_action=create_template'), [
    'allowed' => ['module', 'newsletter_id', 'flow_id', 'context', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateCreateConfirm', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_templates.php&app_action=create_template_confirm'), [
    'allowed' => ['module', 'lng_id', 'context', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateDelete', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_templates.php&app_action=delete_user_template'), [
    'allowed' => ['module', 'template_id', 'lng_id', 'context', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateDeleteConfirm', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_templates.php&app_action=delete_user_template_confirm'), [
    'allowed' => ['module', 'template_id', 'lng_id', 'context', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateExport', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/editor_templates.php&app_action=export'), [
    'allowed' => ['module', 'template_id', 'lng_id', 'context', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateImport', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=configbeez/config_editor/admin_application_plugins/template_import.php'), [
    'allowed' => ['module', 'lng_id', 'newsletter_id', 'flow_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('templateImportToMain', function ($params = []) {
    $module = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'config_tmplmngr_lng' : 'config_tmplmngr';
    $appPath = 'configbeez/' . $module . '/admin_application_plugins/cfg_language_common.php';
    return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&module=' . $module . '&app_action=select');
}, [
    'allowed' => ['template_id', 'maintemplate_id', 'lng_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('thumbnailUpdate', Router::joinUrl(MAILBEEZ_MAILHIVE_URL_DIRECT, '/api/private/v1.0/editor/thumbnail/'), [
    'allowed' => ['apikey', 'lng_id'],
    'defaults' => ['apikey' => mh_cfg('MAILBEEZ_API_KEY')],
]);

LegacyRouter::add('newsletterLock', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php&app_action=lock'), [
    'allowed' => ['newsletter_id', 'flow_id', 'page_mode'],
    'defaults' => [],
]);

LegacyRouter::add('newsletterUnlock', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php&app_action=unlock'), [
    'allowed' => ['newsletter_id', 'flow_id', 'page_mode'],
    'defaults' => [],
]);

// Public newsletter signup dialog (legacy frontend route)
// Basic:
//   <server-url>/mailhive.php?m=mb_newsletter&ma=signup
// Options:
//   <server-url>/mailhive.php?m=mb_newsletter&ma=signup&email=test@test.com&topics=3,9
LegacyRouter::add('newsletterSignup', Router::joinUrl(MAILBEEZ_MAILHIVE_URL_DIRECT, '?m=mb_newsletter&ma=signup'), [
    'allowed' => ['email', 'topics', 'mp'],
    'defaults' => [],
]);

// Public newsletter opt-in confirmation landing page (legacy frontend route)
// Example (defaults):
//   <server-url>/mailhive.php?m=mb_newsletter&ma=confirm&source=prospects&c=testoptincode
LegacyRouter::add('newsletterConfirm', Router::joinUrl(MAILBEEZ_MAILHIVE_URL_DIRECT, '?m=mb_newsletter&ma=confirm'), [
    'allowed' => ['source', 'c'],
    'defaults' => [
        'source' => 'prospects',
        'c'      => 'testoptincode', // \mb_newsletter::TESTOPTINCODE
    ],
]);

LegacyRouter::add('afterSendActions', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/after_send_actions.php'), [
    'allowed' => ['newsletter_id', 'campaign_id', 'flow_id', 'lng_id'],
    'defaults' => [],
]);

LegacyRouter::add('newsletterCopy', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php&app_action=copy_confirm'), [
    'allowed' => ['newsletter_id', 'campaign_id', 'page_mode'],
    'defaults' => [],
]);

LegacyRouter::add('listSegmentationEdit', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=mailbeez/mb_newsletter/admin_application_plugins/list_segmentation_edit.php'), [
    'allowed' => ['list_id', 'flow_id', 'return_to', 'page_mode', 'newsletter_campaign_id', 'module', 'app_action', 'template_id'],
    'defaults' => [],
]);

LegacyRouter::add('nerdmode', function ($params = []) {
    $context = $params['context'] ?? mh_get('context', 'module');
    if ($context === 'newsletter') {
        $appPath = 'mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php';
    } elseif ($context === 'module') {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_module.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_module.php';
    } else {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_common.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_common.php';
    }
    return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&nerdmode=true');
}, [
    'allowed' => ['module', 'lng_id', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

LegacyRouter::add('textmode', function ($params = []) {
    $context = $params['context'] ?? mh_get('context', 'module');
    if ($context === 'newsletter') {
        $appPath = 'mailbeez/mb_newsletter/admin_application_plugins/newsletter_edit.php';
    } elseif ($context === 'module') {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_module.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_module.php';
    } else {
        $appPath = (mh_cfg('MAILBEEZ_CONFIG_TMPLMNGR_LNG_STATUS') == 'True') ? 'configbeez/config_tmplmngr_lng/admin_application_plugins/cfg_language_common.php' : 'configbeez/config_tmplmngr/admin_application_plugins/cfg_language_common.php';
    }
    return mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=' . $appPath . '&textmode=true');
}, [
    'allowed' => ['module', 'lng_id', 'newsletter_id', 'flow_id', 'maintemplate_id', 'content_module_id'],
    'defaults' => [],
]);

// Analytics (report_analytics_advanced) — delegate URL generation to legacy class method
LegacyRouter::add('reportAnalyticsAdvanced', function ($params = []) {
    // Ensure the legacy report class is available
    if (!class_exists('report_analytics_advanced')) {
        $legacyBootstrap = MH_DIR_REPORT . 'report_analytics_advanced.php';
        if (file_exists($legacyBootstrap)) {
            include_once $legacyBootstrap;
        }
    }
    // Whitelist supported filter parameters
    $allowedKeys = [
        'selected_startdate',
        'selected_enddate',
        'selected_module',
        // if mb_newsletter
        'selected_campaign',
        'selected_campaign_item',
    ];
    $filtered = array_intersect_key($params, array_flip($allowedKeys));
    // Use the canonical legacy generator; when no params are provided it will
    // fallback to the given range ('this_year') for start/end dates.
    return \report_analytics_advanced::getLink($filtered ?: null, 'this_year');
}, [
    // We return a fully composed URL from the closure; do not append params again.
    'allowed' => [],
    'defaults' => [],
]);

LegacyRouter::add('segmentationProductSearch', function ($params = []) {
    $catalogServer = defined('MH_CATALOG_SERVER') ? rtrim((string)MH_CATALOG_SERVER, '/\\') : '';
    $catalogWs = defined('MH_WS_CATALOG') ? trim((string)MH_WS_CATALOG, '/\\') : '';
    $prefix = $prefix = (mh_cfg('MAILBEEZ_API_SSL')) ? "https://" : "http://";
    if ($catalogWs !== '') {
        $prefix .= '/' . $catalogWs;
    }
    if ($prefix !== '') {
        $prefix .= '/';
    }

    $languagesId = isset($params['lng_id']) ? (int)$params['lng_id'] : 0;
    if ($languagesId <= 0 && isset($_SESSION['languages_id'])) {
        $languagesId = (int)$_SESSION['languages_id'];
    }
    if ($languagesId <= 0) {
        $languagesId = (int)mh_get('lng_id', 0, 'int');
    }
    if ($languagesId <= 0) {
        $languagesId = 2;
    }

    $apiEntrypoint = ltrim((string)mh_cfg('MAILBEEZ_API_ENTRYPOINT'), '/');
    $apiKey = (string)mh_cfg('MAILBEEZ_API_KEY');

    return $prefix
        . $apiEntrypoint
        . 'private/v1.0/segmentation/product/?apikey=' . rawurlencode($apiKey)
        . '&lng_id=' . $languagesId;
}, [
    'allowed' => ['q', 'lng_id'],
    'defaults' => [],
]);



// Coupon edit (legacy voucher admin).
// The coupon id parameter name differs per platform:
//   - gambio  => 'cid'
//   - zencart => 'cid'
//   - modified (MH_PLATFORM === 'xtc') => 'cID'
// Callers always pass a normalized 'cid' param; we map it to the platform
// specific key here so the legacy voucher admin receives the expected name.
LegacyRouter::add('couponEdit', function ($params = []) {
    $base = mh_href_link(FILENAME_COUPON_ADMIN, 'action=voucheredit');

    // Normalized coupon id may arrive as 'cid' or 'cID' from callers.
    $cid = $params['cid'] ?? ($params['cID'] ?? null);
    if ($cid === null || $cid === '') {
        return $base;
    }

    // modified-shop expects the camel-cased 'cID', others use 'cid'.
    $cidKey = (defined('MH_PLATFORM') && MH_PLATFORM === 'xtc') ? 'cID' : 'cid';

    $separator = (strpos($base, '?') !== false) ? '&' : '?';
    return $base . $separator . $cidKey . '=' . rawurlencode((string) $cid);
}, [
    // The closure composes the full URL (incl. coupon id); do not append again.
    'allowed' => [],
    'defaults' => [],
]);

// Customer Group configuration popup (from main_mailbeez.php:522)
// Original legacy link example:
// app=load_app&app_path=filterbeez/filter_check_group/admin_application_plugins/config_groups.php&module=filter_check_group&popup=true&m=<module_code>
LegacyRouter::add('filterCheckGroupConfig', mh_href_link(FILENAME_MAILBEEZ, 'app=load_app&app_path=filterbeez/filter_check_group/admin_application_plugins/config_groups.php&module=filter_check_group&popup=true'), [
    // Pass current module code as 'm' (same as legacy usage)
    'allowed' => ['m'],
    'defaults' => [],
]);

LegacyRouter::add('reviewEdit', mh_href_link(FILENAME_REVIEWS, 'action=edit'), [
    'allowed' => ['rID'],
    'defaults' => [],
]);
