<?php
declare(strict_types=1);

/**
 * Handles the admin UI (dashboard + settings).
 *
 * @package StockGuardianPro
 */

namespace StockGuardianPro\LowStock\Services;

use StockGuardianPro\LowStock\Plugin;
use WC_Product;

\defined('ABSPATH') || exit;

final class AdminPageService implements ServiceInterface
{
    private Plugin $plugin;

    private ThresholdRepository $thresholds;

    private EventRepository $events;

    public function __construct(Plugin $plugin)
    {
        $this->plugin     = $plugin;
        $this->thresholds = new ThresholdRepository($plugin);
        $this->events     = $this->resolve_event_repository($plugin);
    }

    public function register(): void
    {
        add_action('admin_menu', [$this, 'register_menu']);
        add_action('admin_init', [$this, 'register_settings']);
    }

    public function register_menu(): void
    {
        // Main menu
        add_menu_page(
            __('Stock Guardian Pro', 'stock-guardian-pro'),
            __('Stock Guardian Pro', 'stock-guardian-pro'),
            'manage_woocommerce',
            'stock-guardian-pro',
            [$this, 'render_page'],
            'dashicons-shield-alt',
            56 // Position after WooCommerce
        );

        // First submenu (same as main menu, but with different title)
        add_submenu_page(
            'stock-guardian-pro',
            __('Dashboard', 'stock-guardian-pro'),
            __('Dashboard', 'stock-guardian-pro'),
            'manage_woocommerce',
            'stock-guardian-pro',
            [$this, 'render_page']
        );
    }

    public function register_settings(): void
    {
        register_setting(
            'woolsn_settings',
            'woolsn_default_threshold',
            [
                'type'              => 'integer',
                'sanitize_callback' => 'absint',
                'default'           => 5,
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_notifications_email',
            [
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_email',
                'default'           => get_option('admin_email'),
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_email_subject_template',
            [
                'type'              => 'string',
                'sanitize_callback' => [$this, 'sanitize_subject_template'],
                'default'           => 'Stock Guardian Alert: {product_name}',
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_email_intro',
            [
                'type'              => 'string',
                'sanitize_callback' => [$this, 'sanitize_multiline_text'],
                'default'           => 'The stock level for the product below has reached or fallen below the configured threshold.',
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_email_footer',
            [
                'type'              => 'string',
                'sanitize_callback' => [$this, 'sanitize_multiline_text'],
                'default'           => 'If you need to adjust the stock threshold, open the product in WooCommerce and update the low stock settings.',
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_telegram_enabled',
            [
                'type'              => 'boolean',
                'sanitize_callback' => [$this, 'sanitize_checkbox'],
                'default'           => false,
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_telegram_bot_token',
            [
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default'           => '',
            ]
        );

        register_setting(
            'woolsn_settings',
            'woolsn_telegram_chat_id',
            [
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
                'default'           => '',
            ]
        );
    }

    public function render_page(): void
    {
        if (! current_user_can('manage_woocommerce')) {
            wp_die(esc_html__('You do not have permission to access this page.', 'stock-guardian-pro'));
        }

        $current_tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'dashboard'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $tabs        = [
            'dashboard'      => __('Dashboard', 'stock-guardian-pro'),
            'settings'       => __('Settings', 'stock-guardian-pro'),
            'documentation'  => __('Documentation', 'stock-guardian-pro'),
        ];
        ?>
        <div class="wrap woolsn-admin-wrap">
            <h1 class="wp-heading-inline"><?php esc_html_e('Stock Guardian Pro', 'stock-guardian-pro'); ?></h1>
            <nav class="nav-tab-wrapper woolsn-tabs">
                <?php foreach ($tabs as $tab => $label) : ?>
                    <a
                        href="<?php echo esc_url(add_query_arg(['tab' => $tab])); ?>"
                        class="nav-tab <?php echo $current_tab === $tab ? 'nav-tab-active' : ''; ?>"
                    >
                        <?php echo esc_html($label); ?>
                    </a>
                <?php endforeach; ?>
            </nav>
            <?php
            if (isset($_GET['settings-updated'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                add_settings_error(
                    'woolsn_messages',
                    'woolsn_message',
                    __('Settings saved successfully.', 'stock-guardian-pro'),
                    'updated'
                );
            }
            settings_errors('woolsn_messages');
            ?>
            <?php $this->maybe_render_seed_notice(); ?>
            <div class="woolsn-card">
                <?php
                switch ($current_tab) {
                    case 'settings':
                        $this->render_settings();
                        break;
                    case 'documentation':
                        $this->render_documentation();
                        break;
                    default:
                        $this->render_dashboard();
                }
                ?>
            </div>
        </div>
        <?php
    }

    private function render_settings(): void
    {
        ?>
        <form method="post" action="options.php" class="woolsn-settings-form">
            <?php
            settings_fields('woolsn_settings');
            ?>
            <?php
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                if (is_array($creds)) {
                    ?>
                    <div class="notice notice-success is-dismissible">
                        <p>
                            <?php
                            printf(
                                /* translators: 1: username, 2: password */
                                '<code>' . esc_html((string) ($creds['username'] ?? '')) . '</code>',
                                '<code>' . esc_html((string) ($creds['password'] ?? '')) . '</code>'
                            );
                            ?>
                        </p>
                        <p><?php esc_html_e('Credentials are fixed to guarantee consistent access for reviewers.', 'stock-guardian-pro'); ?></p>
                    </div>
                    <?php
                }
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended
                ?>
                <div class="notice notice-error">
                </div>
                <?php
            }
            ?>
            <table class="form-table" role="presentation">
                <tbody>
                <tr>
                    <th scope="row">
                        <label for="woolsn_default_threshold">
                            <?php esc_html_e('Default threshold', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <input
                            id="woolsn_default_threshold"
                            name="woolsn_default_threshold"
                            type="number"
                            min="0"
                            value="<?php echo esc_attr((string) get_option('woolsn_default_threshold', 5)); ?>"
                        />
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_notifications_email">
                            <?php esc_html_e('Notification email', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <input
                            id="woolsn_notifications_email"
                            name="woolsn_notifications_email"
                            type="email"
                            value="<?php echo esc_attr((string) get_option('woolsn_notifications_email', get_option('admin_email'))); ?>"
                            class="regular-text"
                        />
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_email_subject_template">
                            <?php esc_html_e('Email subject template', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <input
                            id="woolsn_email_subject_template"
                            name="woolsn_email_subject_template"
                            type="text"
                            value="<?php echo esc_attr((string) get_option('woolsn_email_subject_template', 'Stock Guardian Alert: {product_name}')); ?>"
                            class="regular-text"
                        />
                        <p class="description">
                            <?php
                            esc_html_e('Available placeholders: {site_name}, {product_name}, {product_sku}, {stock}, {threshold}.', 'stock-guardian-pro');
                            ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_email_intro">
                            <?php esc_html_e('Email intro message', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <textarea
                            id="woolsn_email_intro"
                            name="woolsn_email_intro"
                            rows="4"
                            class="large-text"
                        ><?php echo esc_textarea((string) get_option('woolsn_email_intro', 'The stock level for the product below has reached or fallen below the configured threshold.')); ?></textarea>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_email_footer">
                            <?php esc_html_e('Email footer message', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <textarea
                            id="woolsn_email_footer"
                            name="woolsn_email_footer"
                            rows="3"
                            class="large-text"
                        ><?php echo esc_textarea((string) get_option('woolsn_email_footer', 'If you need to adjust the stock threshold, open the product in WooCommerce and update the low stock settings.')); ?></textarea>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_telegram_enabled">
                            <?php esc_html_e('Enable Telegram alerts', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <label>
                            <input
                                id="woolsn_telegram_enabled"
                                name="woolsn_telegram_enabled"
                                type="checkbox"
                                value="1"
                                <?php checked((bool) get_option('woolsn_telegram_enabled', false)); ?>
                            />
                            <?php esc_html_e('Send notifications to Telegram in addition to email.', 'stock-guardian-pro'); ?>
                        </label>
                        <div class="notice notice-info inline" style="margin: 10px 0; padding: 10px; background-color: #f0f6fc; border-left: 4px solid #2271b1;">
                            <p style="margin: 0 0 8px 0;">
                                <strong><?php esc_html_e('External Service Notice', 'stock-guardian-pro'); ?></strong>
                            </p>
                            <p style="margin: 0;">
                                <?php
                                printf(
                                    /* translators: 1: link to Telegram privacy policy */
                                    esc_html__(
                                        'This is an optional third-party service. When enabled, notification data will be transmitted to Telegram servers (api.telegram.org). By enabling this feature, you acknowledge that data will be sent to Telegram. %1$s',
                                        'stock-guardian-pro'
                                    ),
                                    '<a href="https://telegram.org/privacy" target="_blank" rel="noopener noreferrer">' . esc_html__('Learn more about Telegram privacy policy', 'stock-guardian-pro') . '</a>'
                                );
                                ?>
                            </p>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_telegram_bot_token">
                            <?php esc_html_e('Telegram bot token', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <input
                            id="woolsn_telegram_bot_token"
                            name="woolsn_telegram_bot_token"
                            type="text"
                            class="regular-text"
                            value="<?php echo esc_attr((string) get_option('woolsn_telegram_bot_token', '')); ?>"
                            placeholder="123456789:ABCDEF..."
                        />
                        <p class="description">
                            <?php esc_html_e('Create a bot using @BotFather and paste the API token here.', 'stock-guardian-pro'); ?>
                        </p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="woolsn_telegram_chat_id">
                            <?php esc_html_e('Telegram chat ID', 'stock-guardian-pro'); ?>
                        </label>
                    </th>
                    <td>
                        <input
                            id="woolsn_telegram_chat_id"
                            name="woolsn_telegram_chat_id"
                            type="text"
                            class="regular-text"
                            value="<?php echo esc_attr((string) get_option('woolsn_telegram_chat_id', '')); ?>"
                            placeholder="@channelusername or numeric ID"
                        />
                        <p class="description">
                            <?php esc_html_e('Use @userinfobot or @RawDataBot to retrieve your chat/channel ID.', 'stock-guardian-pro'); ?>
                        </p>
                    </td>
                </tr>
                </tbody>
            </table>
            <?php submit_button(__('Save settings', 'stock-guardian-pro')); ?>
        </form>
        <?php
    }

    private function render_dashboard(): void
    {
        $metrics = $this->collect_metrics();
        $events  = $this->events->latest_events(8);
        $critical_products = $this->get_critical_products();
        $all_managed_products = $this->get_all_managed_products(20);
        ?>
        <div class="woolsn-metrics-grid">
            <div class="woolsn-metric">
                <span class="woolsn-metric-label"><?php esc_html_e('Notifications last 24h', 'stock-guardian-pro'); ?></span>
                <span class="woolsn-metric-value"><?php echo esc_html((string) ($metrics['events_last_24h'] ?? 0)); ?></span>
            </div>
            <div class="woolsn-metric">
                <span class="woolsn-metric-label"><?php esc_html_e('Custom thresholds', 'stock-guardian-pro'); ?></span>
                <span class="woolsn-metric-value"><?php echo esc_html((string) ($metrics['custom_thresholds'] ?? 0)); ?></span>
            </div>
            <div class="woolsn-metric">
                <span class="woolsn-metric-label"><?php esc_html_e('Managed products', 'stock-guardian-pro'); ?></span>
                <span class="woolsn-metric-value"><?php echo esc_html((string) ($metrics['managed_products'] ?? 0)); ?></span>
            </div>
        </div>

        <div class="woolsn-dashboard-columns">
            <div class="woolsn-dashboard-panel">
                <h2><?php esc_html_e('Recent notifications', 'stock-guardian-pro'); ?></h2>
                <?php $this->render_seed_button(); ?>
                <?php if (empty($events)) : ?>
                    <p><?php esc_html_e('No notifications recorded yet.', 'stock-guardian-pro'); ?></p>
                <?php else : ?>
                    <table class="widefat striped">
                        <thead>
                        <tr>
                            <th><?php esc_html_e('Product', 'stock-guardian-pro'); ?></th>
                            <th><?php esc_html_e('Stock', 'stock-guardian-pro'); ?></th>
                            <th><?php esc_html_e('Threshold', 'stock-guardian-pro'); ?></th>
                            <th><?php esc_html_e('Channel', 'stock-guardian-pro'); ?></th>
                            <th><?php esc_html_e('Sent at', 'stock-guardian-pro'); ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($events as $event) : ?>
                            <tr>
                                <td>
                                    <strong><?php echo esc_html($event['product_name']); ?></strong><br/>
                                    <small><?php printf('#%d', (int) $event['product_id']); ?></small>
                                </td>
                                <td><?php echo esc_html((string) $event['stock']); ?></td>
                                <td><?php echo esc_html((string) $event['threshold']); ?></td>
                                <td><?php echo esc_html(ucfirst($event['channel'])); ?></td>
                                <td><?php echo esc_html($this->format_datetime($event['notified_at'])); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
            <div class="woolsn-dashboard-panel">
                <h2><?php esc_html_e('Currently critical products', 'stock-guardian-pro'); ?></h2>
                <?php if (empty($critical_products)) : ?>
                    <p><?php esc_html_e('No products below their monitored threshold right now.', 'stock-guardian-pro'); ?></p>
                <?php else : ?>
                    <ul class="woolsn-critical-list">
                        <?php foreach ($critical_products as $product) : ?>
                            <li>
                                <a href="<?php echo esc_url($product['edit_link']); ?>">
                                    <?php echo esc_html($product['name']); ?>
                                </a>
                                <span class="woolsn-critical-meta">
                                    <?php
                                    printf(
                                        /* translators: 1: stock quantity, 2: threshold */
                                        esc_html__('Stock: %1$d / Threshold: %2$d', 'stock-guardian-pro'),
                                        (int) $product['stock'],
                                        (int) $product['threshold']
                                    );
                                    ?>
                                </span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>

        <div class="woolsn-dashboard-panel" style="margin-top: 20px;">
            <h2><?php esc_html_e('All managed products', 'stock-guardian-pro'); ?></h2>
            <p class="description"><?php esc_html_e('All products with stock management enabled. Products below threshold are highlighted.', 'stock-guardian-pro'); ?></p>
            <?php if (empty($all_managed_products)) : ?>
                <p><?php esc_html_e('No products with stock management enabled.', 'stock-guardian-pro'); ?></p>
            <?php else : ?>
                <table class="widefat striped">
                    <thead>
                    <tr>
                        <th><?php esc_html_e('Product', 'stock-guardian-pro'); ?></th>
                        <th><?php esc_html_e('Stock', 'stock-guardian-pro'); ?></th>
                        <th><?php esc_html_e('Threshold', 'stock-guardian-pro'); ?></th>
                        <th><?php esc_html_e('Status', 'stock-guardian-pro'); ?></th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($all_managed_products as $product) : ?>
                        <tr class="<?php echo $product['is_critical'] ? 'woolsn-critical-row' : ''; ?>">
                            <td>
                                <a href="<?php echo esc_url($product['edit_link']); ?>">
                                    <strong><?php echo esc_html($product['name']); ?></strong>
                                </a>
                                <br/>
                                <small><?php printf('#%d', (int) $product['id']); ?></small>
                            </td>
                            <td><?php echo esc_html((string) $product['stock']); ?></td>
                            <td><?php echo esc_html((string) $product['threshold']); ?></td>
                            <td>
                                <?php if ($product['is_critical']) : ?>
                                    <span style="color: #d63638; font-weight: bold;">
                                        <?php esc_html_e('Critical', 'stock-guardian-pro'); ?>
                                    </span>
                                <?php else : ?>
                                    <span style="color: #00a32a;">
                                        <?php esc_html_e('OK', 'stock-guardian-pro'); ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * @return array<string, int>
     */
    private function collect_metrics(): array
    {
        return [
            'events_last_24h'   => $this->events->count_recent(),
            'custom_thresholds' => $this->thresholds->count_all(),
            'managed_products'  => $this->count_managed_products(),
        ];
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    private function get_critical_products(): array
    {
        $critical = [];

        $custom_entries = $this->thresholds->all();
        $seen_ids = [];

        foreach ($custom_entries as $entry) {
            $product_id   = (int) $entry['product_id'];
            $variation_id = (int) $entry['variation_id'];
            $threshold    = (int) $entry['threshold'];

            $target_id = $variation_id > 0 ? $variation_id : $product_id;
            $product   = wc_get_product($target_id);

            if (! $product instanceof WC_Product) {
                continue;
            }

            if (! $product->managing_stock()) {
                continue;
            }

            $stock = $product->get_stock_quantity();
            if ($stock === null) {
                continue;
            }

            if ($stock > $threshold) {
                continue;
            }

            $critical[] = [
                'id'        => $target_id,
                'name'      => $product->get_formatted_name(),
                'stock'     => $stock,
                'threshold' => $threshold,
                'edit_link' => $this->get_edit_link($product),
            ];

            $seen_ids[] = $target_id;
        }

        $default_threshold = (int) get_option('woolsn_default_threshold', 5);

        if ($default_threshold > 0) {
            global $wpdb;

            $exclude_clause = '';
            if (! empty($seen_ids)) {
                $ids = implode(',', array_map('intval', $seen_ids));
                $exclude_clause = "AND p.ID NOT IN ({$ids})";
            }

            // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared
            $query = "
                SELECT p.ID, CAST(stock.meta_value AS SIGNED) AS stock_value
                FROM {$wpdb->posts} p
                INNER JOIN {$wpdb->postmeta} stock ON stock.post_id = p.ID AND stock.meta_key = '_stock'
                INNER JOIN {$wpdb->postmeta} manage ON manage.post_id = p.ID AND manage.meta_key = '_manage_stock' AND manage.meta_value = 'yes'
                WHERE p.post_status = 'publish'
                AND p.post_type IN ('product', 'product_variation')
                AND CAST(stock.meta_value AS SIGNED) <= %d
                {$exclude_clause}
                ORDER BY stock_value ASC
                LIMIT 10
            ";

            $prepared = $wpdb->prepare($query, $default_threshold);
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $results  = $prepared ? $wpdb->get_results($prepared, ARRAY_A) : [];
            // phpcs:enable

            foreach ($results as $row) {
                $product = wc_get_product((int) $row['ID']);
                if (! $product instanceof WC_Product) {
                    continue;
                }

                $critical[] = [
                    'id'        => (int) $row['ID'],
                    'name'      => $product->get_formatted_name(),
                    'stock'     => (int) $row['stock_value'],
                    'threshold' => $default_threshold,
                    'edit_link' => $this->get_edit_link($product),
                ];
            }
        }

        return array_slice($critical, 0, 10);
    }

    private function count_managed_products(): int
    {
        global $wpdb;

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var(
            "
            SELECT COUNT(*)
            FROM {$wpdb->postmeta} pm
            INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
            WHERE pm.meta_key = '_manage_stock'
              AND pm.meta_value = 'yes'
              AND p.post_type IN ('product','product_variation')
              AND p.post_status = 'publish'
            "
        );
        // phpcs:enable

        return (int) $count;
    }

    /**
     * Recupera tutti i prodotti gestiti con informazioni su stock e threshold.
     *
     * @param int $limit Numero massimo di prodotti da recuperare.
     * @return array<int, array<string, mixed>>
     */
    private function get_all_managed_products(int $limit = 50): array
    {
        global $wpdb;

        $default_threshold = (int) get_option('woolsn_default_threshold', 5);
        $custom_thresholds = $this->thresholds->all();
        
        // Crea mappa di threshold personalizzati
        $threshold_map = [];
        foreach ($custom_thresholds as $entry) {
            $product_id = (int) $entry['product_id'];
            $variation_id = (int) $entry['variation_id'];
            $key = $variation_id > 0 ? "v_{$variation_id}" : "p_{$product_id}";
            $threshold_map[$key] = (int) $entry['threshold'];
        }

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $query = "
            SELECT p.ID, p.post_title, p.post_type,
                   CAST(stock.meta_value AS SIGNED) AS stock_value
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} stock ON stock.post_id = p.ID AND stock.meta_key = '_stock'
            INNER JOIN {$wpdb->postmeta} manage ON manage.post_id = p.ID AND manage.meta_key = '_manage_stock' AND manage.meta_value = 'yes'
            WHERE p.post_status = 'publish'
            AND p.post_type IN ('product', 'product_variation')
            ORDER BY p.post_type DESC, p.post_title ASC
            LIMIT %d
        ";

        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
        $results = $wpdb->get_results($wpdb->prepare($query, $limit), ARRAY_A);
        // phpcs:enable

        $products = [];
        foreach ($results as $row) {
            $product_id = (int) $row['ID'];
            $is_variation = $row['post_type'] === 'product_variation';
            
            $product = wc_get_product($product_id);
            if (! $product instanceof WC_Product) {
                continue;
            }

            $stock = $product->get_stock_quantity();
            if ($stock === null) {
                continue;
            }

            // Determina threshold (personalizzato o default)
            $threshold = $default_threshold;
            if ($is_variation) {
                $variation_id = $product_id;
                $parent_id = $product->get_parent_id();
                $key = "v_{$variation_id}";
                if (isset($threshold_map[$key])) {
                    $threshold = $threshold_map[$key];
                } elseif (isset($threshold_map["p_{$parent_id}"])) {
                    $threshold = $threshold_map["p_{$parent_id}"];
                }
            } else {
                $key = "p_{$product_id}";
                if (isset($threshold_map[$key])) {
                    $threshold = $threshold_map[$key];
                }
            }

            $products[] = [
                'id'          => $product_id,
                'name'        => $product->get_formatted_name(),
                'stock'       => $stock,
                'threshold'   => $threshold,
                'is_critical' => $stock <= $threshold,
                'edit_link'   => $this->get_edit_link($product),
            ];
        }

        return $products;
    }

    private function get_edit_link(WC_Product $product): string
    {
        $target_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();
        $link      = get_edit_post_link($target_id, '');

        return $link ? $link : '#';
    }

    private function format_datetime(string $datetime): string
    {
        $timestamp = strtotime($datetime);
        if (! $timestamp) {
            return $datetime;
        }

        return wp_date(
            get_option('date_format') . ' ' . get_option('time_format'),
            $timestamp
        );
    }

    private function resolve_event_repository(Plugin $plugin): EventRepository
    {
        $service = $plugin->service(EventRepository::class);
        if ($service instanceof EventRepository) {
            return $service;
        }

        return new EventRepository($plugin);
    }

    private function render_seed_button(): void

    private function render_documentation(): void
    {
        ?>
        <div class="woolsn-documentation">
            <h2><?php esc_html_e('Getting Started', 'stock-guardian-pro'); ?></h2>
            <ol>
                <li><?php esc_html_e('Set the default threshold and notification email in the Settings tab.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Adjust per-product thresholds from the Inventory tab in each product edit screen.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Monitor live metrics and the log of recent notifications from the Dashboard tab.', 'stock-guardian-pro'); ?></li>
            </ol>

            <h2><?php esc_html_e('How It Works', 'stock-guardian-pro'); ?></h2>
            <p><?php esc_html_e('Stock Guardian Pro monitors your WooCommerce products in real-time. When a product\'s stock level falls below its configured threshold (either global or per-product), the plugin automatically sends notifications via email and/or Telegram.', 'stock-guardian-pro'); ?></p>
            <p><?php esc_html_e('The plugin tracks all stock changes, whether they occur through manual updates, orders, API calls, or bulk actions. Each notification is logged in the event history for easy tracking and auditing.', 'stock-guardian-pro'); ?></p>

            <h2><?php esc_html_e('Configuration', 'stock-guardian-pro'); ?></h2>
            <h3><?php esc_html_e('Global Settings', 'stock-guardian-pro'); ?></h3>
            <p><?php esc_html_e('Set a default low stock threshold that applies to all products unless overridden. This threshold determines when notifications are triggered.', 'stock-guardian-pro'); ?></p>
            <h3><?php esc_html_e('Per-Product Thresholds', 'stock-guardian-pro'); ?></h3>
            <p><?php esc_html_e('For individual products or variations, you can set custom thresholds in the product edit screen under the Inventory tab. This allows you to fine-tune alerts based on product importance or sales velocity.', 'stock-guardian-pro'); ?></p>
            <p><?php esc_html_e('Variation thresholds inherit from their parent product if not explicitly set. This provides flexibility while maintaining simplicity.', 'stock-guardian-pro'); ?></p>

            <h2><?php esc_html_e('Email Customization', 'stock-guardian-pro'); ?></h2>
            <p><?php esc_html_e('Customize your low stock alert emails with personalized subject lines, intro messages, and footer text. All placeholders are automatically replaced with actual product data when notifications are sent.', 'stock-guardian-pro'); ?></p>
            <p><strong><?php esc_html_e('Available Placeholders:', 'stock-guardian-pro'); ?></strong></p>
            <ul>
                <li><code>{site_name}</code> – <?php esc_html_e('WordPress site title', 'stock-guardian-pro'); ?></li>
                <li><code>{product_name}</code> – <?php esc_html_e('Product or variation name', 'stock-guardian-pro'); ?></li>
                <li><code>{product_sku}</code> – <?php esc_html_e('SKU if available', 'stock-guardian-pro'); ?></li>
                <li><code>{stock}</code> – <?php esc_html_e('Current stock quantity', 'stock-guardian-pro'); ?></li>
                <li><code>{threshold}</code> – <?php esc_html_e('Threshold value that triggered the alert', 'stock-guardian-pro'); ?></li>
            </ul>
            <p><?php esc_html_e('Placeholders can be used in the email subject template, intro message, and footer message. They work in any combination and can be used multiple times.', 'stock-guardian-pro'); ?></p>

            <h2><?php esc_html_e('Telegram Alerts', 'stock-guardian-pro'); ?></h2>
            <p><?php esc_html_e('Enable instant mobile notifications via Telegram. This optional feature allows you to receive stock alerts directly on your phone or in Telegram groups/channels.', 'stock-guardian-pro'); ?></p>
            <p><strong><?php esc_html_e('⚠️ External Service Notice:', 'stock-guardian-pro'); ?></strong> <?php esc_html_e('When enabled, notification data will be transmitted to Telegram servers (api.telegram.org). By enabling this feature, you acknowledge that data will be sent to Telegram.', 'stock-guardian-pro'); ?></p>
            <h3><?php esc_html_e('Setup Instructions:', 'stock-guardian-pro'); ?></h3>
            <ol>
                <li><?php esc_html_e('Open Telegram and start a conversation with @BotFather.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Run the command /newbot (or /token if you already have a bot) and follow the instructions to create your bot.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Copy the bot token that @BotFather provides you.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Start a conversation with your newly created bot and send /start at least once. This is required for the bot to be able to send you messages.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Get your chat ID by either:', 'stock-guardian-pro'); ?>
                    <ul>
                        <li><?php esc_html_e('Visiting https://api.telegram.org/bot&lt;your-token&gt;/getUpdates and looking for the "id" value in the response.', 'stock-guardian-pro'); ?></li>
                        <li><?php esc_html_e('Using @userinfobot or @RawDataBot in Telegram to display your chat ID.', 'stock-guardian-pro'); ?></li>
                    </ul>
                </li>
                <li><?php esc_html_e('In the Settings tab above, paste the bot token and chat ID into the respective fields.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Enable the "Enable Telegram alerts" checkbox and click "Save settings".', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Trigger a low stock event by reducing a product\'s stock below its threshold to verify both email and Telegram notifications are working correctly.', 'stock-guardian-pro'); ?></li>
            </ol>
            <p><strong><?php esc_html_e('Note:', 'stock-guardian-pro'); ?></strong> <?php esc_html_e('For group or channel notifications, add the bot to the group/channel as an administrator, then use the group/channel ID instead of your personal chat ID.', 'stock-guardian-pro'); ?></p>

            <h2><?php esc_html_e('Dashboard Features', 'stock-guardian-pro'); ?></h2>
            <h3><?php esc_html_e('Metrics Overview', 'stock-guardian-pro'); ?></h3>
            <p><?php esc_html_e('The Dashboard tab provides real-time insights into your inventory alerts:', 'stock-guardian-pro'); ?></p>
            <ul>
                <li><?php esc_html_e('Notifications sent in the last 24 hours', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Total number of custom thresholds configured', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Number of products currently being monitored', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('List of currently critical products (stock below threshold)', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('All managed products with their stock levels and thresholds', 'stock-guardian-pro'); ?></li>
            </ul>
            <h3><?php esc_html_e('Event Log', 'stock-guardian-pro'); ?></h3>
            <p><?php esc_html_e('Every notification sent is recorded in the event log with detailed information including:', 'stock-guardian-pro'); ?></p>
            <ul>
                <li><?php esc_html_e('Product name and SKU', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Stock quantity at the time of notification', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Configured threshold', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Notification channels used (Email/Telegram)', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Exact timestamp of the notification', 'stock-guardian-pro'); ?></li>
            </ul>

            <h2><?php esc_html_e('REST API Integration', 'stock-guardian-pro'); ?></h2>
            <p><?php esc_html_e('Stock Guardian Pro exposes a read-only REST API endpoint for retrieving threshold information programmatically. This is useful for custom integrations or external monitoring systems.', 'stock-guardian-pro'); ?></p>
            <p><strong><?php esc_html_e('Endpoint:', 'stock-guardian-pro'); ?></strong></p>
            <p><code><?php echo esc_html(rest_url('woolsn/v1/threshold/&lt;product_id&gt;[/&lt;variation_id&gt;]')); ?></code></p>
            <p><strong><?php esc_html_e('Authentication:', 'stock-guardian-pro'); ?></strong> <?php esc_html_e('Requires a WordPress user with the manage_woocommerce capability. Use standard WordPress REST API authentication methods (Application Passwords, OAuth, etc.).', 'stock-guardian-pro'); ?></p>
            <p><strong><?php esc_html_e('Response Format:', 'stock-guardian-pro'); ?></strong> <?php esc_html_e('Returns JSON data containing the threshold value for the specified product/variation. If no custom threshold is set, returns null.', 'stock-guardian-pro'); ?></p>

            <h2><?php esc_html_e('Updates via Envato Market', 'stock-guardian-pro'); ?></h2>
            <p><?php esc_html_e('Keep your plugin up to date automatically through the official Envato Market plugin:', 'stock-guardian-pro'); ?></p>
            <ol>
                <li><?php esc_html_e('Download and install the official Envato Market plugin from build.envato.com.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Activate the plugin and navigate to Envato Market settings in your WordPress admin.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Add your personal token from your Envato account to connect your site.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Once connected, Stock Guardian Pro will appear in your Envato Market dashboard.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Future updates will be delivered automatically with one-click installation.', 'stock-guardian-pro'); ?></li>
            </ol>

            <h2><?php esc_html_e('Troubleshooting', 'stock-guardian-pro'); ?></h2>
            <h3><?php esc_html_e('Notifications Not Being Sent', 'stock-guardian-pro'); ?></h3>
            <ul>
                <li><?php esc_html_e('Verify that WooCommerce inventory management is enabled for the product (Product → Inventory → Manage stock).', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Ensure the product\'s stock quantity is actually below the configured threshold.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Check WooCommerce → Status → Logs for entries from Stock Guardian Pro to identify any errors.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Verify that duplicate notifications are being prevented (same product/variation/stock combination within 2 hours).', 'stock-guardian-pro'); ?></li>
            </ul>
            <h3><?php esc_html_e('Email Issues', 'stock-guardian-pro'); ?></h3>
            <ul>
                <li><?php esc_html_e('Ensure your WordPress email configuration is working correctly by sending a test email.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Check that the notification email address in Settings is valid and receiving messages.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Review your SMTP plugin settings if you\'re using one (WP Mail SMTP, Post SMTP, etc.).', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Check spam/junk folders as low stock alerts might be filtered.', 'stock-guardian-pro'); ?></li>
            </ul>
            <h3><?php esc_html_e('Telegram Issues', 'stock-guardian-pro'); ?></h3>
            <ul>
                <li><?php esc_html_e('Verify that Telegram alerts are enabled in Settings and settings have been saved.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Double-check that the bot token and chat ID are correct (no extra spaces or characters).', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Ensure you\'ve sent /start to your bot at least once to allow it to message you.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('For group/channel notifications, verify the bot is added as an administrator.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Check that your server can make outbound HTTPS connections to api.telegram.org (port 443).', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Review WooCommerce logs for any Telegram API errors or connection issues.', 'stock-guardian-pro'); ?></li>
            </ul>
            <h3><?php esc_html_e('General Issues', 'stock-guardian-pro'); ?></h3>
            <ul>
                <li><?php esc_html_e('Ensure WordPress, WooCommerce, and Stock Guardian Pro are all up to date.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Test with a product that has stock management enabled and reduce stock manually to trigger an alert.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Check the Dashboard event log to see if notifications are being triggered but not delivered.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Review plugin conflicts by temporarily deactivating other plugins one by one.', 'stock-guardian-pro'); ?></li>
            </ul>

            <h2><?php esc_html_e('Best Practices', 'stock-guardian-pro'); ?></h2>
            <ul>
                <li><?php esc_html_e('Set thresholds based on your average sales velocity and reorder times.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Use per-product thresholds for high-value or fast-moving items that need earlier alerts.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Enable both email and Telegram notifications for critical products to ensure alerts are not missed.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Regularly review the Dashboard metrics to optimize your threshold values.', 'stock-guardian-pro'); ?></li>
                <li><?php esc_html_e('Monitor the event log to identify patterns and improve inventory management.', 'stock-guardian-pro'); ?></li>
            </ul>
        </div>
        <?php
    }

    private function maybe_render_seed_notice(): void

        $count = (int) $_GET['woolsn-seeded']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        ?>
        <div class="notice notice-success is-dismissible woolsn-notice">
            <p>
                <?php
                printf(
                    /* translators: %d number of products created */
                    (int) $count
                );
                ?>
            </p>
        </div>
        <?php
    }

    public function sanitize_subject_template(string $value): string
    {
        $value = wp_strip_all_tags($value);

        if ($value === '') {
            $value = '[{site_name}] Low stock alert: {product_name}';
        }

        return $value;
    }

    public function sanitize_multiline_text(string $value): string
    {
        return wp_kses_post($value);
    }

    public function sanitize_checkbox($value): bool
    {
        return (bool) $value;
    }

            wp_safe_redirect(
                add_query_arg(
                    [
                        'page'              => 'stock-guardian-pro',
                    ],
                    admin_url('admin.php')
                )
            );
            exit;
        }

        $result = $service->create_or_reset_user();

        if ($result instanceof \WP_Error) {
            wp_safe_redirect(
                add_query_arg(
                    [
                        'page'              => 'stock-guardian-pro',
                    ],
                    admin_url('admin.php')
                )
            );
            exit;
        }

        wp_safe_redirect(
            add_query_arg(
                [
                    'page'                => 'stock-guardian-pro',
                ],
                admin_url('admin.php')
            )
        );
        exit;
    }
}
