<?php

namespace Core\System;

class Router
{
    private static array $routes = [];
    private static array $groupStack = [];
    private static string $currentMethod = '';
    private static string $currentUri = '';

    private static function normalizeUri(string $uri): string
{
    $path = parse_url($uri, PHP_URL_PATH) ?? '/';

    // إصلاح مهم لدعم الروابط العربية
    $path = rawurldecode($path);

    $path = preg_replace('#/+#', '/', $path);

    if ($path !== '/') {
        $path = rtrim($path, '/');
    }

    $base = '';

    if ($base !== '' && strpos($path, $base) === 0) {
        $path = substr($path, strlen($base));
    }

    if ($path === '' || $path === false) {
        return '/';
    }

    return $path[0] === '/' ? $path : '/' . $path;
}

    public static function group(array $options, callable $callback)
    {
        self::$groupStack[] = $options;
        $callback();
        array_pop(self::$groupStack);
    }

    public static function add(string $method, string $route, $action, array $options = [])
    {
        $route = '/' . trim($route, '/');

        foreach (self::$groupStack as $group) {
            if (isset($group['prefix'])) {
                $route = '/' . trim($group['prefix'], '/') . $route;
            }

            if (isset($group['namespace'])) {
                $options['namespace'] = rtrim($group['namespace'], '\\') . '\\';
            }
        }

        // ✅ دعم {param:regex} مع الحفاظ على السلوك القديم
        $regex = preg_replace_callback('/{([^}:]+)(?::([^}]+))?}/', function ($m) {
            $name = $m[1];
            $pattern = $m[2] ?? '[^/]+';
            return '(?P<' . $name . '>' . $pattern . ')';
        }, $route);

        self::$routes[] = [
            'method'  => strtoupper($method),
            'route'   => $route,
            'regex'   => '#^' . $regex . '$#',
            'action'  => $action,
            'options' => $options
        ];
    }

    public static function get(string $route, $action, array $options = [])
    {
        self::add('GET', $route, $action, $options);
    }

    public static function post(string $route, $action, array $options = [])
    {
        self::add('POST', $route, $action, $options);
    }

    public static function dispatch()
    {
        self::$currentMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        self::$currentUri    = self::normalizeUri($_SERVER['REQUEST_URI'] ?? '/');

        /* =====================================================
           SEO ROUTES (SITEMAP & ROBOTS)
           ===================================================== */

        if (self::$currentUri === '/sitemap.xml') {
            require ROOT_PATH . '/public/sitemap.php';
            exit;
        }

        if (self::$currentUri === '/robots.txt') {
            require ROOT_PATH . '/public/robots.php';
            exit;
        }

        /* =====================================================
           INSTALLER ROUTE (LICENSE ACTIVATION)
           ===================================================== */

        if (self::$currentUri === '/install' || self::$currentUri === '/install/index.php') {
            require ROOT_PATH . '/public/install/index.php';
            exit;
        }

        if (self::$currentUri === '/license/recover' || self::$currentUri === '/license/recover.php') {
            require ROOT_PATH . '/public/license/recover.php';
            exit;
        }


        /* =====================================================
           NORMAL ROUTING
           ===================================================== */

        // Prevent /admin or /admin/* from being captured by catch-all routes
        $isAdminRequest = (self::$currentUri === '/admin' || strpos(self::$currentUri, '/admin/') === 0);

        foreach (self::$routes as $route) {
            if ($route['method'] !== self::$currentMethod) {
                continue;
            }

            $routeRegex = $route['regex'] ?? '';
            $isAdminRoute = (is_string($routeRegex) && preg_match('/^[#~\/]\^\/admin(\/|$)/', $routeRegex) === 1);

            if ($isAdminRequest && !$isAdminRoute) {
                continue;
            }

            if (!$isAdminRequest && $isAdminRoute) {
                continue;
            }

            if (preg_match($route['regex'], self::$currentUri, $matches)) {
                $params = array_values(
                    array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY)
                );

                return self::executeAction(
                    $route['action'],
                    $params,
                    $route['options']
                );
            }
        }

        /* =====================================================
           404 HANDLER
           ===================================================== */

        http_response_code(404);

        try {
            \Core\App\Models\SecurityLog::log(
                '404',
                'Page not found',
                self::$currentUri
            );
        } catch (\Throwable $e) {
            // لا نكسر الموقع أبداً
        }

        \Core\System\ThemeManager::render('404');
        exit;
    }

    private static function executeAction($action, array $params, array $options)
    {
        if (is_string($action) && str_contains($action, '@')) {
            [$controller, $method] = explode('@', $action);

            $namespace = $options['namespace'] ?? 'Core\\App\\Controllers\\';
            $class = $namespace . $controller;

            $instance = new $class();
            return call_user_func_array([$instance, $method], $params);
        }
    }
}

/* =========================================================
   CRON
   /cron/run      — public endpoint hit by server cron job (token-protected)
   /admin/cron/regenerate — admin-only token refresh (session-protected)
========================================================= */
Router::get('/cron/run', 'CronController@run');

/* =========================================================
   FRONTEND
========================================================= */

// Home
Router::get('/', 'HomeController@index');

// Product (ID-based route – numeric only)
Router::get('/product/{id:\d+}', 'HomeController@product');

// Product (slug)
Router::get('/product/{slug:[^/]+}', 'HomeController@product');
Router::get('/products', 'HomeController@products');
Router::get('/category/{slug}', 'HomeController@category');

// Public AI Landing Pages
Router::get('/lp/{slug:[^/]+}', 'AiLandingPageController@publicView');

// Landing page order form — standalone iframe embed
Router::get('/lp-order-form/{productId:[0-9]+}', 'LandingOrderFormController@form');

/* =========================================================
   API
========================================================= */
Router::get('/api/home-search', 'HomeController@homeSearch');
Router::get('/api/dz/states', 'LocationController@dzStates');
Router::get('/api/dz/cities/{state}', 'LocationController@dzCities');
Router::get('/api/shipping/price/{state}/{city}', 'LocationController@shippingPrice');
Router::get('/api/frontend/shipping/config', 'LocationController@frontendShippingConfig');
Router::get('/api/frontend/shipping/maystro/wilayas', 'LocationController@maystroWilayas');
Router::get('/api/frontend/shipping/maystro/communes', 'LocationController@maystroCommunesFrontendIndex');
Router::get('/api/frontend/shipping/maystro/communes/{wilaya}', 'LocationController@maystroCommunesFrontend');
Router::get('/api/frontend/shipping/maystro/pickup-points/{commune}', 'LocationController@maystroPickupPointsFrontend');
Router::get('/api/frontend/shipping/maystro/delivery-price/{commune}', 'LocationController@maystroDeliveryPriceFrontend');

// CMS Pages (catch-all, must stay AFTER specific routes)
Router::get('/{slug}', 'PageController@show');

// Admin root redirect (protected at dispatch level)
Router::get('/admin', function () {
    header('Location: /admin/login', true, 302);
    exit;
});

/* ===== Product Reviews ===== */
Router::post('/product-review/store', 'ProductReviewController@store');
Router::post('/submit-order', 'OrderController@submitOrder');
Router::get('/order/success', 'OrderController@success');

/* =========================================================
   ADMIN
========================================================= */
Router::group([
    'prefix' => 'admin',
    'namespace' => 'Core\\App\\Controllers'
], function () {

    /* ===== Auth ===== */
    Router::get('/login', 'AdminController@login');
    Router::post('/login', 'AdminController@doLogin');
    Router::post('/logout', 'AdminController@logout');
    Router::get('/dashboard', 'AdminController@dashboard');

    /* ===== Cron management (admin-only) ===== */
    Router::post('/cron/regenerate', 'CronController@regenerate');

    // Finance / Statistics
    Router::get('/finance', 'FinanceController@index');

    // Customers
    Router::get('/customers',                  'CustomersController@index');
    Router::get('/customers/view/{id:[0-9]+}', 'CustomersController@view');
    Router::get('/customers/marketing',        'CustomersController@marketing');
    Router::post('/customers/send-campaign',   'CustomersController@sendCampaign');
    Router::get('/customers/preview-count',    'CustomersController@previewCount');
    Router::post('/customers/sync',            'CustomersController@sync');

    // Call Attempts (أرشيف محاولات التأكيد)
    Router::post('/orders/call-attempt/{id}',   'OrderController@logCallAttempt');
    Router::get('/orders/call-attempts',         'OrderController@callAttemptsStats');
    Router::post('/orders/workflow-action/{id}', 'OrderController@workflowAction');

    // AI Settings (multi-provider: Gemini, Claude, OpenAI)
    Router::get('/settings/ai',                      'AiController@settings');
    Router::post('/settings/ai/save',                'AiController@save');
    Router::post('/ai/list-models',                  'AiController@listModels');
    Router::post('/ai/test',                         'AiController@testConnection');
    Router::post('/ai/generate-product-description', 'AiController@generateProductDescription');
    Router::post('/ai/generate-product-seo',         'AiController@generateProductSeo');
    Router::post('/ai/generate-product-images',      'AiController@generateProductImages');
    Router::post('/ai/generate-marketing',           'AiController@generateMarketingMessage');
    Router::post('/ai/proxy-assistant',              'AiController@proxyAssistant');
    Router::post('/ai/proxy-claude',                 'AiController@proxyClaude');
    // Legacy Gemini routes (backward compat)
    Router::get('/settings/gemini',                  'AiController@settings');
    Router::post('/settings/gemini/save',            'AiController@save');

    /* ===== AI Landing Pages ===== */
    Router::get('/ai-landing-pages',                              'AiLandingPageController@index');
    Router::get('/ai-landing-pages/create',                       'AiLandingPageController@create');
    Router::post('/ai-landing-pages/store',                       'AiLandingPageController@store');
    Router::get('/ai-landing-pages/edit/{id:[0-9]+}',             'AiLandingPageController@edit');
    Router::get('/ai-landing-pages/chat/{id:[0-9]+}',             'AiLandingPageController@chatExpert');
    Router::get('/ai-landing-pages/production/{id:[0-9]+}',       'AiLandingPageController@productionWorkspace');
    Router::get('/ai-landing-pages/competitors/{id:[0-9]+}',      'AiLandingPageController@competitorWorkspace');
    Router::get('/ai-landing-pages/destination/{id:[0-9]+}/{destination:[a-z_]+}', 'AiLandingPageController@destinationWorkspace');
    Router::post('/ai-landing-pages/update/{id:[0-9]+}',          'AiLandingPageController@update');
    Router::post('/ai-landing-pages/delete/{id:[0-9]+}',          'AiLandingPageController@delete');
    Router::post('/ai-landing-pages/create-session/{id:[0-9]+}',  'AiLandingPageController@createSession');
    Router::post('/ai-landing-pages/destination-run/{id:[0-9]+}/{destination:[a-z_]+}', 'AiLandingPageController@runDestinationWorkflow');
    Router::post('/ai-landing-pages/generate/{id:[0-9]+}',        'AiLandingPageController@generate');
    Router::post('/ai-landing-pages/generate-from-image/{id:[0-9]+}', 'AiLandingPageController@generateFromImage');
    Router::post('/ai-landing-pages/regenerate/{id:[0-9]+}',      'AiLandingPageController@regenerate');
    Router::post('/ai-landing-pages/assemble/{id:[0-9]+}',        'AiLandingPageController@assemble');
    Router::post('/ai-landing-pages/generate-variants/{id:[0-9]+}', 'AiLandingPageController@generateVariants');
    Router::post('/ai-landing-pages/analyze-competitor/{id:[0-9]+}', 'AiLandingPageController@analyzeCompetitor');
    Router::post('/ai-landing-pages/save-analysis/{id:[0-9]+}',     'AiLandingPageController@saveAnalysis');
    Router::post('/ai-landing-pages/save-workspace/{id:[0-9]+}',    'AiLandingPageController@saveWorkspace');
    Router::post('/ai-landing-pages/generate-brief/{id:[0-9]+}',    'AiLandingPageController@generateBrief');
    Router::post('/ai-landing-pages/save-html/{id:[0-9]+}',       'AiLandingPageController@saveHtml');
    Router::get('/ai-landing-pages/preview/{id:[0-9]+}',          'AiLandingPageController@preview');
    Router::post('/ai-landing-pages/upload-image/{id:[0-9]+}',    'AiLandingPageController@uploadImage');
    Router::post('/ai-landing-pages/import-html/{id:[0-9]+}',     'AiLandingPageController@importHtml');

    // ✅ Clear Page Cache (manual)
    Router::post('/system/clear-cache', 'SystemCleanupController@clearCache');

    /* ===== Notifications ===== */
    Router::get('/notifications', 'Admin\\NotificationController@index');
    Router::get('/notifications/show/{id}', 'Admin\\NotificationController@show');
    Router::post('/notifications/read/{id}', 'Admin\\NotificationController@markRead');
    Router::post('/notifications/read-all', 'Admin\\NotificationController@markAllRead');
    Router::post('/notifications/archive/{id}', 'Admin\\NotificationController@archive');
    Router::post('/notifications/archive-all', 'Admin\\NotificationController@archiveAll');
    Router::get('/notifications/unread-count', 'Admin\\NotificationController@unreadCount');

    /* AJAX dropdown */
    Router::get('/notifications/unread', 'Admin\\NotificationController@unreadJson');
    Router::post('/notifications/read-from-dropdown/{id}', 'Admin\\NotificationController@markReadFromDropdown');

    /* =====================================================
       SYSTEM CLEANUP
    ===================================================== */
    Router::get('/system/cleanup', 'SystemCleanupController@index');
    Router::post('/system/cleanup/run', 'SystemCleanupController@run');
    Router::get('/system/errors', 'SystemErrorsController@index');
    Router::post('/system/errors/clear', 'SystemErrorsController@clear');

    /* =====================================================
       SYSTEM BACKUP
    ===================================================== */
    Router::get('/system/backup', 'SystemBackupController@index');
    Router::post('/system/backup/run', 'SystemBackupController@run');
    Router::get('/system/backup/download', 'SystemBackupController@download');
    Router::post('/system/backup/delete', 'SystemBackupController@delete');
    Router::post('/system/backup/clean', 'SystemBackupController@clean');

    /* =====================================================
       ADMIN PROFILE
    ===================================================== */
    Router::get('/profile', 'AdminProfileController@index');

    // ── Team Management ──
    Router::get('/team',                  'TeamController@index');
    Router::get('/team/create',           'TeamController@create');
    Router::post('/team/store',           'TeamController@store');
    Router::get('/team/edit/{id}',        'TeamController@edit');
    Router::post('/team/update/{id}',     'TeamController@update');
    Router::post('/team/delete/{id}',     'TeamController@delete');
    Router::post('/team/toggle/{id}',     'TeamController@toggle');
    Router::post('/team/assign-order',    'TeamController@assignOrder');
    Router::get('/team/stats',            'TeamController@stats');
    Router::get('/team/member/{id}',       'TeamController@viewMember');
    Router::get('/team/permissions',       'TeamController@permissions');
    Router::post('/team/permissions/save', 'TeamController@savePermissions');
    Router::get('/team/workflow',          'TeamController@workflow');
    Router::post('/team/workflow/rules/save', 'TeamController@saveWorkflowRule');
    Router::post('/team/workflow/rules/toggle/{id}', 'TeamController@toggleWorkflowRule');
    Router::post('/team/workflow/rules/delete/{id}', 'TeamController@deleteWorkflowRule');

    // ── Team Communication ──
    Router::get('/team/communication', 'TeamCommunicationController@index');
    Router::get('/team/communication/{id:[0-9]+}', 'TeamCommunicationController@chat');
    Router::post('/team/messages/send', 'TeamCommunicationController@sendMessage');
    Router::post('/team/messages/delete/{id:[0-9]+}', 'TeamCommunicationController@deleteMessage');
    Router::post('/team/messages/pin/{id:[0-9]+}', 'TeamCommunicationController@pinMessage');
    Router::get('/team/messages/poll/{id:[0-9]+}', 'TeamCommunicationController@pollMessages');
    Router::get('/team/messages/unread-count', 'TeamCommunicationController@unreadCount');

    // ── Team Meetings ──
    Router::get('/team/meetings', 'TeamCommunicationController@meetings');
    Router::get('/team/meetings/create', 'TeamCommunicationController@createMeeting');
    Router::post('/team/meetings/store', 'TeamCommunicationController@storeMeeting');
    Router::get('/team/meetings/edit/{id:[0-9]+}', 'TeamCommunicationController@editMeeting');
    Router::post('/team/meetings/update/{id:[0-9]+}', 'TeamCommunicationController@updateMeeting');
    Router::post('/team/meetings/delete/{id:[0-9]+}', 'TeamCommunicationController@deleteMeeting');
    Router::post('/team/meetings/rsvp/{id:[0-9]+}', 'TeamCommunicationController@rsvpMeeting');
    Router::post('/team/meetings/complete/{id:[0-9]+}', 'TeamCommunicationController@completeMeeting');
    Router::get('/team/meetings/room/{id:[0-9]+}', 'TeamCommunicationController@meetingRoom');

    // ── Team Group Chat ──
    Router::get('/team/group-chat/{id:[0-9]+}', 'TeamCommunicationController@groupChat');
    Router::post('/team/group-chat/send', 'TeamCommunicationController@sendGroupMessage');
    Router::post('/team/group-chat/pin/{id:[0-9]+}', 'TeamCommunicationController@pinGroupMessage');
    Router::get('/team/group-chat/poll/{id:[0-9]+}', 'TeamCommunicationController@pollGroupMessages');

    // ── Team Activity & Presence ──
    Router::get('/team/activity', 'TeamCommunicationController@activity');
    Router::post('/team/presence/heartbeat', 'TeamCommunicationController@heartbeat');

    // ── Team Announcements ──
    Router::post('/team/announcements/store', 'TeamCommunicationController@storeAnnouncement');
    Router::post('/team/announcements/delete/{id:[0-9]+}', 'TeamCommunicationController@deleteAnnouncement');
    Router::post('/team/announcements/pin/{id:[0-9]+}', 'TeamCommunicationController@pinAnnouncement');

    Router::post('/profile/update', 'AdminProfileController@update');

    /* ===== Products ===== */
    Router::get('/products', 'ProductController@index');
    Router::get('/products/create', 'ProductController@create');
    Router::post('/products/store', 'ProductController@store');
    Router::get('/products/edit/{id}', 'ProductController@edit');
    Router::post('/products/update/{id}', 'ProductController@update');
    Router::post('/products/delete/{id}', 'ProductController@delete');

    /* ===== Inventory ===== */
    Router::get('/inventory', 'InventoryController@index');
    Router::post('/inventory/update-stock/{id:[0-9]+}', 'InventoryController@updateStock');
    Router::post('/inventory/update-variant-stock/{id:[0-9]+}', 'InventoryController@updateVariantStock');

    /* ===== Reviews ===== */
    Router::get('/reviews', 'Admin\\ProductReviewController@index');
    Router::post('/reviews/approve/{id}', 'Admin\\ProductReviewController@approve');
    Router::post('/reviews/delete/{id}', 'Admin\\ProductReviewController@delete');

    /* ===== Categories ===== */
    Router::get('/categories', 'CategoriesController@index');
    Router::get('/categories/create', 'CategoriesController@create');
    Router::post('/categories/store', 'CategoriesController@store');
    Router::get('/categories/edit/{id}', 'CategoriesController@edit');
    Router::post('/categories/update/{id}', 'CategoriesController@update');
    Router::post('/categories/delete/{id}', 'CategoriesController@delete');

    /* ===== Orders ===== */
    Router::get('/orders', 'OrderController@index');
    /* ===== Bulk Order Confirmation ===== */
    Router::get('/orders/bulk-confirm', 'BulkOrderController@index');
    Router::post('/orders/bulk-confirm/process', 'BulkOrderController@process');
    Router::get('/orders/view/{id}', 'OrderController@view');
    Router::post('/orders/status/{id}', 'OrderController@updateStatus');
    Router::post('/orders/delete/{id}', 'OrderController@delete');
    Router::get('/orders/export', 'OrderController@export');
    Router::post('/orders/export-gsheets/{id}', 'OrderController@exportGoogleSheets');

    // Google Sheets OAuth
    Router::get('/settings/gsheets',                    'GoogleSheetsOAuthController@index');
    Router::post('/settings/gsheets/save-credentials',  'GoogleSheetsOAuthController@saveCredentials');
    Router::post('/settings/gsheets/save-config',       'GoogleSheetsOAuthController@saveSheetConfig');
    Router::get('/settings/gsheets/connect',            'GoogleSheetsOAuthController@connect');
    Router::get('/settings/gsheets/callback',           'GoogleSheetsOAuthController@callback');
    Router::post('/settings/gsheets/disconnect', 'GoogleSheetsOAuthController@disconnect');
    Router::get('/settings/gsheets/files',              'GoogleSheetsOAuthController@listFiles');
    Router::get('/settings/gsheets/sheets',             'GoogleSheetsOAuthController@listSheets');
    Router::get('/settings/gsheets/monitor',    'GoogleSheetsOAuthController@monitor');
    Router::post('/settings/gsheets/retry-job', 'GoogleSheetsOAuthController@retryJob');
    Router::post('/orders/shipping/{id}', 'OrderController@sendToShipping');
    Router::get('/orders/prepare-shipping/{id}', 'OrderController@prepareShipping');
    Router::post('/orders/send-ecotrack/{id}', 'OrderController@sendToEcotrack');
    Router::post('/orders/refresh-ecotrack/{id}', 'OrderController@refreshEcotrack');
    Router::get('/orders/ecotrack/communes', 'OrderController@ecotrackCommunes');
    Router::get('/orders/yalidine/communes', 'OrderController@yalidineCommunes');
    Router::get('/orders/yalidine/stopdesks', 'OrderController@yalidineStopdesks');
    Router::get('/orders/prepare-dhd/{id}', 'OrderController@prepareDhd');
    Router::post('/orders/send-dhd/{id}', 'OrderController@sendToDhd');
    Router::get('/orders/ecotrack/label', 'OrderController@ecotrackLabel');
    Router::get('/orders/ecotrack/track', 'OrderController@ecotrackTrack');
    Router::get('/orders/prepare-yalidine/{id}', 'OrderController@prepareYalidine');
    Router::post('/orders/return/{id}', 'OrderController@processReturn');
    Router::post('/orders/return-provider/{id}', 'OrderController@requestReturnToProvider');
    Router::get('/orders/returns/{id}', 'OrderController@viewReturns');
    Router::post('/orders/send-yalidine/{id}', 'OrderController@sendToYalidine');
    Router::get('/orders/prepare-maystro/{id}',      'OrderController@prepareMaystro');
    Router::post('/orders/send-maystro/{id}',         'OrderController@sendToMaystro');
    Router::get('/orders/maystro/label/{id}',         'OrderController@maystroLabel');
    Router::get('/orders/maystro/communes',           'OrderController@maystroCommunes');
    Router::get('/orders/maystro/pickup-points',      'OrderController@maystroPickupPoints');
    Router::get('/orders/maystro/delivery-prices',    'OrderController@maystroDeliveryPrices');
    Router::post('/orders/maystro/exchange/{id}',     'OrderController@maystroExchange');
    Router::post('/orders/maystro/refund/{id}',       'OrderController@maystroRefund');

    // ===== ZR EXPRESS (official provider key) =====
    Router::get('/orders/prepare-zr_express/{id}', 'OrderController@prepareZrexpress');
    Router::post('/orders/send-zr_express/{id}', 'OrderController@sendToZrexpress');

    // ===== ZR EXPRESS (backward compatibility) =====
    Router::get('/orders/prepare-zrexpress/{id}', 'OrderController@prepareZrexpress');
    Router::post('/orders/send-zrexpress/{id}', 'OrderController@sendToZrexpress');

    Router::get('/order/tracking', 'OrderTrackingController@index');
    Router::post('/order/tracking', 'OrderTrackingController@track');
    Router::get('/shipments', 'MyShipmentsController@index');

    /* ===== Shipping Control ===== */
    Router::get('/shipments/control', 'ShippingControlController@index');
    Router::post('/shipments/control/run', 'ShippingControlController@runNow');
    Router::post('/shipments/control/toggle', 'ShippingControlController@toggleProvider');

    /* =====================================================
       SUSPICIOUS ORDERS (ANTI-FRAUD)
    ===================================================== */
    Router::get('/suspicious-orders', 'SuspiciousOrdersController@index');
    Router::post('/suspicious-orders/approve/{id:\d+}', 'SuspiciousOrdersController@approve');
    Router::post('/suspicious-orders/cancel/{id:\d+}', 'SuspiciousOrdersController@cancel');
    Router::post('/suspicious-orders/ban-phone', 'SuspiciousOrdersController@banPhone');
    Router::post('/suspicious-orders/unban-phone', 'SuspiciousOrdersController@unbanPhone');

    /* ===== Plugin ===== */
    Router::get('/plugins', 'Admin\\PluginController@index');
    Router::post('/plugins/enable/{slug}', 'Admin\\PluginController@enable');
    Router::post('/plugins/disable/{slug}', 'Admin\\PluginController@disable');
    Router::post('/plugins/install', 'Admin\\PluginController@install');
    Router::post('/plugins/verify-license', 'Admin\\PluginLicenseController@verifyLicense');
    Router::post('/plugins/enable-licensed/{slug}', 'Admin\\PluginLicenseController@enableLicensed');

    /* ===== Integrations ===== */
    Router::get('/integrations', 'IntegrationsController@index');
    Router::get('/integrations/configure', 'IntegrationsController@configure');
    Router::post('/integrations/configure', 'IntegrationsController@configure');
    Router::post('/integrations/toggle', 'IntegrationsController@toggle');
    Router::post('/integrations/maystro/test-connection', 'IntegrationsController@maystroTestConnection');

    /* ===== Video Meeting Integration ===== */
    Router::get('/integrations/video-meeting',        'VideoMeetingController@settings');
    Router::post('/integrations/video-meeting/save',  'VideoMeetingController@save');
    Router::post('/integrations/video-meeting/test',  'VideoMeetingController@testConnection');
    Router::get('/team/meetings/video-url/{id:[0-9]+}',   'VideoMeetingController@getRoomUrl');
    Router::post('/team/meetings/video-start/{id:[0-9]+}', 'VideoMeetingController@videoStart');

    /* ===== Settings ===== */
    Router::get('/settings/basic', 'SettingsController@basic');
    Router::post('/settings/save', 'SettingsController@save');
    Router::get('/settings/shipping', 'SettingsController@shipping');
    Router::post('/settings/shipping/save', 'SettingsController@saveShipping');
    Router::post('/settings/shipping/sync-provider-prices', 'SettingsController@syncShippingProviderPrices');
    Router::post('/settings/shipping/apply-imported-prices', 'SettingsController@applyImportedShippingProviderPrices');
    Router::get('/settings/identity', 'SettingsIdentityController@index');
    Router::post('/settings/identity/save', 'SettingsIdentityController@save');
    Router::post('/settings/identity/delete-image', 'SettingsIdentityController@deleteImage');
    Router::get('/settings/security', 'SettingsSecurityController@index');
    Router::post('/settings/security/save', 'SettingsSecurityController@save');
    Router::post('/settings/security/logs/clear', 'SettingsSecurityController@clearLogs');

    /* ===== Appearance ===== */
    Router::get('/appearance/customize', 'ThemeCustomizerController@index');
    Router::post('/appearance/customize/save', 'ThemeCustomizerController@save');

    Router::get('/appearance/header', 'HeaderController@index');
    Router::post('/appearance/header/save', 'HeaderController@save');

    /* ===== Active Product ===== */
    Router::get('/theme/active-product', 'ThemeProductController@activeProduct');
    Router::post('/theme/active-product/set/{id}', 'ThemeProductController@setActiveProduct');

    /* ===== Languages ===== */
    Router::get('/languages', 'LanguageManagerController@index');
    Router::get('/languages/create', 'LanguageManagerController@create');
    Router::post('/languages/store', 'LanguageManagerController@store');
    Router::get('/languages/edit/{id}', 'LanguageManagerController@edit');
    Router::post('/languages/update/{id}', 'LanguageManagerController@update');
    Router::post('/languages/delete/{id}', 'LanguageManagerController@delete');
    Router::post('/languages/default/{id}', 'LanguageManagerController@setDefault');
    Router::get('/languages/translate/{code}', 'LanguageManagerController@translate');
    Router::post('/languages/translate/{code}', 'LanguageManagerController@saveTranslations');

    Router::get('/lang/{lang}', 'LanguageManagerController@switch');

    /* ===== AI ===== */


    /* ===== Tracking & Pixels ===== */
    Router::get('/settings/ga4', 'Ga4Controller@settings');
    Router::post('/ga4/save', 'Ga4Controller@save');

    Router::get('/settings/facebook-pixel', 'FacebookPixelController@settings');
    Router::post('/facebook-pixel/save', 'FacebookPixelController@save');

    Router::get('/settings/tiktok-pixel', 'TikTokPixelController@settings');
    Router::post('/tiktok-pixel/save', 'TikTokPixelController@save');

    Router::get('/settings/gtm', 'GtmController@settings');
    Router::post('/gtm/save', 'GtmController@save');

    Router::get('/settings/whatsapp',      'WhatsappController@settings');
    Router::post('/whatsapp/save',         'WhatsappController@save');
    Router::post('/whatsapp/test',         'WhatsappController@test');
    Router::get('/settings/whatsapp/logs', 'WhatsappController@logs');

    /* ===== Homepage Sections ===== */
    Router::get('/home-sections', 'HomeSectionsController@index');
    Router::get('/home-sections/create', 'HomeSectionsController@create');
    Router::post('/home-sections/store', 'HomeSectionsController@store');
    Router::get('/home-sections/edit/{id}', 'HomeSectionsController@edit');
    Router::post('/home-sections/update/{id}', 'HomeSectionsController@update');
    Router::post('/home-sections/delete/{id}', 'HomeSectionsController@delete');

    /* ===== CMS Pages ===== */
    Router::get('/pages', 'Admin\\PageController@index');
    Router::get('/pages/create', 'Admin\\PageController@create');
    Router::post('/pages/store', 'Admin\\PageController@store');
    Router::get('/pages/edit/{id}', 'Admin\\PageController@edit');
    Router::post('/pages/update/{id}', 'Admin\\PageController@update');
    Router::post('/pages/delete/{id}', 'Admin\\PageController@delete');

    /* ===== Footer ===== */
    Router::get('/footer', 'FooterController@index');
    Router::get('/footer/create', 'FooterController@create');
    Router::post('/footer/store', 'FooterController@store');
    Router::get('/footer/edit/{id}', 'FooterController@edit');
    Router::post('/footer/update/{id}', 'FooterController@update');
    Router::post('/footer/delete/{id}', 'FooterController@delete');

    Router::post('/footer/{sectionId}/links/store', 'FooterController@storeLink');
    Router::post('/footer/links/update/{id}', 'FooterController@updateLink');
    Router::post('/footer/links/delete/{id}', 'FooterController@deleteLink');
    Router::post('/footer/reorder', 'FooterController@reorder');

    /* ===== Forgot Password ===== */
    Router::get('/forgot-password', 'AdminPasswordController@showForgotForm');
    Router::post('/forgot-password', 'AdminPasswordController@sendResetLink');

    /* ===== Reset Password ===== */
    Router::get('/reset-password', 'AdminPasswordController@showResetForm');
    Router::post('/reset-password', 'AdminPasswordController@resetPassword');

    /* ===== Updates & License ===== */
    Router::get('/updates-license', 'UpdatesLicenseController@index');
    Router::post('/updates-license/verify-now', 'UpdatesLicenseController@verifyNow');
    Router::post('/updates-license/ping-now', 'UpdatesLicenseController@pingNow');
    Router::post('/updates-license/change-key', 'UpdatesLicenseController@changeKey');

    /* ===== Support ===== */
    Router::get('/support', 'SupportController@index');
    Router::post('/support/create', 'SupportController@create');
    Router::get('/support/view/{id}', 'SupportController@view');
    Router::post('/support/reply/{id}', 'SupportController@reply');
    Router::post('/support/close/{id}', 'SupportController@close');

    /* ===== Upload ===== */
    Router::post('/upload/image', 'Admin\\UploadController@image');

});
