<?php
if (!defined('ABSPATH')) { exit; }

class PTMS_Admin {
    private static $instance = null;
    private $slug = 'pw-merchant-api-system';

    public static function instance() {
        if (self::$instance === null) { self::$instance = new self(); }
        return self::$instance;
    }

    private function __construct() {
        add_action('admin_menu', array($this, 'menu'));
        add_action('admin_enqueue_scripts', array($this, 'assets'));
        add_action('admin_post_ptms_save_wizard', array($this, 'save_wizard'));
        add_action('admin_post_ptms_save_settings', array($this, 'save_settings'));
        add_action('admin_post_ptms_disconnect', array($this, 'disconnect'));
        add_action('admin_post_ptms_check_google_connection', array($this, 'check_google_connection'));
        add_action('admin_post_ptms_sync_test', array($this, 'sync_test'));
        add_action('admin_post_ptms_sync_all', array($this, 'sync_all'));
        add_action('admin_post_ptms_sync_toggle', array($this, 'sync_toggle'));
        add_action('admin_post_ptms_sync_control', array($this, 'sync_control'));
        add_action('admin_post_ptms_schedule_sync', array($this, 'schedule_sync'));
        add_action('admin_post_ptms_cancel_schedule', array($this, 'cancel_schedule'));
        add_action('admin_post_ptms_select_merchant', array($this, 'select_merchant'));
        add_action('wp_ajax_ptms_sync_status', array($this, 'ajax_sync_status'));
        add_action('wp_ajax_ptms_check_google_connection_status', array($this, 'ajax_check_google_connection_status'));
        add_action('add_meta_boxes_product', array($this, 'add_product_merchant_box'));
        add_action('save_post_product', array($this, 'save_product_merchant_box'), 30, 3);
        add_action('admin_post_ptms_clear_logs', array($this, 'clear_logs'));
        add_action('admin_post_ptms_refresh_merchant_issues', array($this, 'refresh_merchant_issues'));
        add_action('admin_post_ptms_delete_offer_manual', array($this, 'delete_offer_manual'));
        add_action('admin_post_ptms_activate_license', array($this, 'activate_license'));
        add_action('admin_post_ptms_refresh_license', array($this, 'refresh_license'));
        add_action('admin_notices', array($this, 'connection_reconnect_notice'));
    }

    public function menu() {
        // PW Feed API ana menüsü doğrudan Hazırlık Sihirbazı'nı açar.
        // Kullanıcıya ayrı bir “Kontrol Paneli” alt menüsü gösterilmez.
        add_menu_page('PW Feed', 'PW Feed API', 'manage_options', $this->slug, array($this, 'wizard'), PTMS_URL . 'assets/img/pw-logo.jpg', 56);

        // Version Lock: kullanıcı akışına göre sabit sol menü sırası.
        add_submenu_page($this->slug, __('Setup Wizard', 'pw-merchant-api-system'), __('Setup Wizard', 'pw-merchant-api-system'), 'manage_options', $this->slug, array($this, 'wizard'));
        add_submenu_page($this->slug, __('Google Connection', 'pw-merchant-api-system'), __('Google Connection', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-google', array($this, 'google_connection'));
        add_submenu_page($this->slug, __('Site Analysis', 'pw-merchant-api-system'), __('Site Analysis', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-site-analizi', array($this, 'site_analysis'));
        add_submenu_page($this->slug, __('Product Analysis', 'pw-merchant-api-system'), __('Product Analysis', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-urun-analizi', array($this, 'product_analysis'));
        add_submenu_page($this->slug, __('Product Submission Center', 'pw-merchant-api-system'), __('Product Submission', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-urun-gonderimi', array($this, 'product_sync'));
        add_submenu_page($this->slug, __('Merchant Issue Center', 'pw-merchant-api-system'), __('Issue Center', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-sorun-merkezi', array($this, 'merchant_issues'));
        add_submenu_page($this->slug, __('Merchant Health Center', 'pw-merchant-api-system'), __('Merchant Health', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-merchant-sagligi', array($this, 'merchant_health'));
        add_submenu_page($this->slug, __('API Usage', 'pw-merchant-api-system'), __('API Usage', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-api-kullanimi', array($this, 'api_usage'));
        add_submenu_page($this->slug, __('Logs', 'pw-merchant-api-system'), __('Logs', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-gunlukler', array($this, 'logs'));
        add_submenu_page($this->slug, __('Settings', 'pw-merchant-api-system'), __('Settings', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-ayarlar', array($this, 'settings'));
        add_submenu_page($this->slug, __('Help', 'pw-merchant-api-system'), __('Help', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-yardim', array($this, 'help'));
        add_submenu_page($this->slug, __('License', 'pw-merchant-api-system'), __('License', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-lisans', array($this, 'license'));

        // Eski bağlantıların çalışmaya devam etmesi için görünmeyen geriye uyumluluk alias'ı.
        add_submenu_page(null, __('Setup Wizard', 'pw-merchant-api-system'), __('Setup Wizard', 'pw-merchant-api-system'), 'manage_options', $this->slug . '-sihirbaz', array($this, 'wizard'));
    }

    public function assets($hook) {
        wp_enqueue_style('ptms-admin-menu', PTMS_URL . 'assets/css/admin-menu.css', array(), PTMS_VERSION);
        if (strpos((string) $hook, 'pw-merchant-api-system') === false) { return; }
        wp_enqueue_style('ptms-admin', PTMS_URL . 'assets/css/admin.css', array(), PTMS_VERSION);
        wp_enqueue_script('ptms-admin', PTMS_URL . 'assets/js/admin.js', array(), PTMS_VERSION, true);
        wp_localize_script('ptms-admin', 'PTMS_ADMIN', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'syncNonce' => wp_create_nonce('ptms_sync_status'),
            'connectionCheckNonce' => wp_create_nonce('ptms_check_google_connection_status'),
            'locale' => determine_locale(),
            'i18n' => array(
                'automaticCheckFinished' => __('Automatic checking has finished; use the manual check if necessary', 'pw-merchant-api-system'),
                'manualCheckAvailable' => __('You can check manually', 'pw-merchant-api-system'),
                'automaticCheckCountdown' => __('Google is connected; an automatic check will run in %d seconds', 'pw-merchant-api-system'),
                'checkingMerchantApi' => __('Merchant API status is being checked automatically', 'pw-merchant-api-system'),
                'checking' => __('Checking', 'pw-merchant-api-system'),
                'automaticCheckFailed' => __('Automatic checking could not be completed; use the manual check button', 'pw-merchant-api-system'),
                'manualCheckRequired' => __('Manual check required', 'pw-merchant-api-system'),
                'googlePreparationContinues' => __('Google preparation is still in progress', 'pw-merchant-api-system'),
                'connectionNotFound' => __('No completed Google connection was found', 'pw-merchant-api-system'),
                'googleConnectionRequired' => __('Google connection required', 'pw-merchant-api-system'),
                'googleReconnectionRequired' => __('Google connection must be re-established', 'pw-merchant-api-system'),
                'ready' => __('Ready', 'pw-merchant-api-system'),
                'total' => __('Total', 'pw-merchant-api-system'),
                'successful' => __('Successful', 'pw-merchant-api-system'),
                'failed' => __('Failed', 'pw-merchant-api-system'),
                'pendingQueue' => __('Pending queue', 'pw-merchant-api-system'),
                'working' => __('Working', 'pw-merchant-api-system'),
                'waiting' => __('Waiting', 'pw-merchant-api-system'),
                'liveRefreshHelp' => __('The status refreshes automatically every few seconds. You do not need to keep this page open.', 'pw-merchant-api-system'),
                'initialSyncCompletedResults' => __('The initial synchronization is complete. Updated results are being prepared.', 'pw-merchant-api-system'),
                'initialSyncCompleted' => __('Initial synchronization completed', 'pw-merchant-api-system'),
                'syncStatusUpdated' => __('Synchronization status updated', 'pw-merchant-api-system'),
                'bulkOperationLog' => __('Bulk operation log', 'pw-merchant-api-system'),
                'updatingAutomatically' => __('Updating automatically', 'pw-merchant-api-system'),
                'operationLog' => __('Operation log', 'pw-merchant-api-system'),
                'merchantScreenshot' => __('Merchant Center screenshot', 'pw-merchant-api-system'),
                'close' => __('Close', 'pw-merchant-api-system'),
            ),
        ));
    }

    private function header($title, $description = '') {
        $license = PTMS_License::label();
        $license_status = PTMS_License::status();
        $is_pro = ($license_status === 'pro');
        $license_action_label = $is_pro ? __('Pro License', 'pw-merchant-api-system') : __('Get Pro License', 'pw-merchant-api-system');
        $license_action_url = $is_pro
            ? admin_url('admin.php?page=' . $this->slug . '-lisans')
            : PTMS_LICENSE_PANEL_URL;
        $license_action_attrs = $is_pro ? '' : ' target="_blank" rel="noopener"';

        echo '<div class="wrap ptms-wrap">';
        echo '<div class="ptms-shell">';
        echo '<div class="ptms-topbar"><div class="ptms-heading"><div class="ptms-logo-box"><img src="' . esc_url(PTMS_URL . 'assets/img/pw-logo.jpg') . '" alt="PW Feed"></div><div><div class="ptms-brand">PW Core Standard · PW Feed</div><h1>' . esc_html($title) . '</h1><p>' . esc_html($description) . '</p></div></div><div class="ptms-top-actions"><span class="ptms-badge">v' . esc_html(PTMS_VERSION) . '</span><span class="ptms-badge soft">' . esc_html($license) . '</span><a class="ptms-btn secondary" href="' . esc_url($license_action_url) . '"' . $license_action_attrs . '>' . esc_html($license_action_label) . '</a></div></div>';
    }

    private function footer() {
        echo '<div class="ptms-footer"><div class="ptms-footer-brand"><img src="' . esc_url(PTMS_URL . 'assets/img/pw-logo.jpg') . '" alt="PW Feed"><div><strong>' . esc_html__('PW Feed, software and development.', 'pw-merchant-api-system') . '</strong><a href="https://www.pwfeed.com" target="_blank" rel="noopener">pwfeed.com</a></div></div><span>PW Core Standard + PW Design System</span></div></div></div>';
    }

    private function docs($purpose, $technology, $operation, $url) {
        echo '<div class="ptms-docs">';
        $items = array(
            __('What is this section for?', 'pw-merchant-api-system') => $purpose,
            __('Technology used', 'pw-merchant-api-system') => $technology,
            __('How does it work?', 'pw-merchant-api-system') => $operation,
        );
        foreach ($items as $title => $text) { echo '<div><h3>' . esc_html($title) . '</h3><p>' . wp_kses_post($text) . '</p></div>'; }
        echo '<div><h3>' . esc_html__('More information', 'pw-merchant-api-system') . '</h3><p><a href="' . esc_url($url) . '" target="_blank" rel="noopener">' . esc_html__('Open official Google help', 'pw-merchant-api-system') . '</a></p></div></div>';
    }

    private function merchant_context_label($context) {
        $context = strtoupper(trim((string) $context));
        $labels = array(
            'SHOPPING_ADS' => __('Shopping ads', 'pw-merchant-api-system'),
            'FREE_LISTINGS' => __('Free listings', 'pw-merchant-api-system'),
            'FREE_LOCAL_LISTINGS' => __('Free local listings', 'pw-merchant-api-system'),
            'LOCAL_INVENTORY_ADS' => __('Local inventory ads', 'pw-merchant-api-system'),
            'YOUTUBE_SHOPPING' => 'YouTube Shopping',
            'CLOUD_RETAIL' => 'Cloud Retail',
            'SURFACES_ACROSS_GOOGLE' => __('Impressions across Google', 'pw-merchant-api-system'),
        );
        return $labels[$context] ?? ($context !== '' ? ucwords(strtolower(str_replace('_', ' ', $context))) : 'Belirtilmedi');
    }

    private function merchant_resolution_label($resolution) {
        $resolution = strtoupper(trim((string) $resolution));
        $labels = array(
            'MERCHANT_ACTION' => __('User intervention required', 'pw-merchant-api-system'),
            'PENDING_PROCESSING' => __('Waiting for Google to process', 'pw-merchant-api-system'),
            'PENDING_INITIAL_CRAWL' => __('Waiting for Google first crawl', 'pw-merchant-api-system'),
            'PENDING_CRAWL' => __('Waiting for Google recrawl', 'pw-merchant-api-system'),
            'NOT_APPLICABLE' => __('No additional action required', 'pw-merchant-api-system'),
        );
        return $labels[$resolution] ?? ($resolution !== '' ? ucwords(strtolower(str_replace('_', ' ', $resolution))) : __('Google did not provide details', 'pw-merchant-api-system'));
    }

    private function merchant_issue_scope_html(array $issue) {
        $contexts = array_values(array_unique(array_filter(array_map('sanitize_text_field', (array) ($issue['reporting_contexts'] ?? array())))));
        $countries = array_values(array_unique(array_filter(array_map('sanitize_text_field', (array) ($issue['applicable_countries'] ?? array())))));
        $attribute = sanitize_text_field((string) ($issue['attribute'] ?? ''));
        $resolution = $this->merchant_resolution_label((string) ($issue['resolution'] ?? ''));
        $code = sanitize_text_field((string) ($issue['code'] ?? 'unknown_issue'));
        $occurrences = max(1, (int) ($issue['occurrence_count'] ?? 1));
        $documentation = (string) ($issue['documentation'] ?? '');

        $html = '<div class="ptms-issue-scope">';
        if ($occurrences > 1 || count($contexts) > 1) {
            $html .= __('<p class="ptms-issue-merged-note">Same issue', 'pw-merchant-api-system') . esc_html((string) max($occurrences, count($contexts))) . __('Combined into a single record from different broadcast scopes.</p>', 'pw-merchant-api-system');
        }
        $html .= '<dl>';
        if ($attribute !== '') $html .= '<dt>Etkilenen alan</dt><dd>' . esc_html($attribute) . '</dd>';
        if ($contexts) {
            $labels = array_map(array($this, 'merchant_context_label'), $contexts);
            $html .= __('<dt>Broadcast areas</dt><dd>', 'pw-merchant-api-system') . esc_html(implode(', ', $labels)) . '</dd>';
        }
        if ($countries) $html .= __('<dt>Affected countries</dt><dd>', 'pw-merchant-api-system') . esc_html(implode(', ', array_map('strtoupper', $countries))) . '</dd>';
        $html .= __('<dt>Solution status</dt><dd>', 'pw-merchant-api-system') . esc_html($resolution) . '</dd>';
        $html .= '<dt>Google sorun kodu</dt><dd><code>' . esc_html($code) . '</code></dd>';
        $html .= '</dl>';
        if ($documentation !== '') $html .= '<a class="ptms-inline-help" href="' . esc_url($documentation) . __('" target="_blank" rel="noopener">Open Google help →</a>', 'pw-merchant-api-system');
        $html .= '</div>';
        return $html;
    }

    private function render_account_merchant_issues(array $issues, $compact = false) {
        if (!$issues) return;

        if ($compact) {
            $count = count($issues);
            $first = is_array($issues[0] ?? null) ? $issues[0] : array();
            $title = (string) ($first['title'] ?? __('Merchant Center account setting', 'pw-merchant-api-system'));
            $url = admin_url('admin.php?page=' . $this->slug . '-sorun-merkezi#ptms-account-settings');
            echo __('<section class="ptms-account-issues is-compact" aria-label="Merchant Center account setting notification">', 'pw-merchant-api-system');
            echo __('<div class="ptms-account-issue-compact"><div><span class="ptms-eyebrow">Account setting</span><h3>', 'pw-merchant-api-system') . esc_html($title) . __('</h3><p>This issue is not product-based. Description and steps to follow <a href="', 'pw-merchant-api-system') . esc_url($url) . __('Located in ">Issue Center</a>.</p></div><a class="ptms-btn secondary" href="', 'pw-merchant-api-system') . esc_url($url) . __('">Review in Issue Center</a></div>', 'pw-merchant-api-system');
            if ($count > 1) echo '<p class="ptms-account-issue-count">' . esc_html(number_format_i18n($count)) . __('account setting notification found.</p>', 'pw-merchant-api-system');
            echo '</section>';
            return;
        }

        echo __('<section id="ptms-account-settings" class="ptms-account-issues" aria-label="Merchant Center account settings">', 'pw-merchant-api-system');
        foreach ($issues as $issue) {
            if (!is_array($issue)) continue;
            $title = (string) ($issue['title'] ?? __('Merchant Center account setting', 'pw-merchant-api-system'));
            $explanation = (string) ($issue['explanation'] ?? __('There is a product-independent settings alert in your Merchant Center account.', 'pw-merchant-api-system'));
            $solution = (string) ($issue['solution'] ?? __('Check Merchant Center settings.', 'pw-merchant-api-system'));
            $affected = max(0, (int) ($issue['affected_products'] ?? 0));
            $documentation = (string) ($issue['documentation'] ?? '');
            echo __('<div class="ptms-account-issue-card"><div class="ptms-account-issue-head"><div><span class="ptms-eyebrow">Account setting</span><h3>', 'pw-merchant-api-system') . esc_html($title) . __('</h3></div><span class="ptms-pill warn">Do not arrange products one by one</span></div>', 'pw-merchant-api-system');
            echo '<p>' . esc_html($explanation) . '</p>';
            if ($affected > 0) echo __('<p class="ptms-account-affected">This account setting', 'pw-merchant-api-system') . number_format_i18n($affected) . __('It may affect the product.</p>', 'pw-merchant-api-system');
            echo __('<div class="ptms-account-solution"><strong>What should you do?</strong><p>', 'pw-merchant-api-system') . esc_html($solution) . '</p></div>';

            if (stripos($title, 'yerel envanter') !== false || (string) ($issue['code'] ?? '') === 'local_inventory_data_missing') {
                echo '<div class="ptms-local-listing-guide">';
                echo __('<h4>Your online broadcasts continue for free</h4>', 'pw-merchant-api-system');
                echo __('<p><strong>Free listings</strong> allow products you sell online to appear on Google for free and should remain open.</p>', 'pw-merchant-api-system');
                echo __('<p><strong>Free local listings</strong> and <strong>Local inventory ads</strong> are for physical store stocks. If you don\'t have a physical store, just remove these two local features.</p>', 'pw-merchant-api-system');
                echo '<div class="ptms-local-listing-compare">';
                echo __('<div><span class="ptms-state-dot is-on"></span><strong>Must stay on</strong><p>Free listings<br>Shopping ads (if you use)</p></div>', 'pw-merchant-api-system');
                echo __('<div><span class="ptms-state-dot is-off"></span><strong>Should be closed</strong><p>Free local listings<br>Local inventory ads</p></div>', 'pw-merchant-api-system');
                echo '</div>';
                echo __('<ol class="ptms-local-listing-steps"><li>In Merchant Center, open <strong>Settings → Plugins → Your Plugins</strong>.</li><li><strong>Use the “Remove” option on the Free local listings</strong> card.</li><li><strong>Use the “Remove” option on the Local inventory ads</strong> card.</li><li>Normal. Do not turn off the <strong>Free listings</strong> feature.</li><li>Use the <strong>Update from Google</strong> button in PW Feed after Google processes the change.</li></ol>', 'pw-merchant-api-system');
                echo '<a class="ptms-help-image-link" href="' . esc_url(PTMS_URL . 'assets/img/merchant-local-features-settings.png') . '" data-ptms-lightbox="merchant-local-settings">';
                echo '<img src="' . esc_url(PTMS_URL . 'assets/img/merchant-local-features-settings.png') . __('" alt="Free local listings and Local inventory ads options on Your Merchant Center Add-ons screen">', 'pw-merchant-api-system');
                echo __('<span>Enlarge sample Merchant Center screen</span>', 'pw-merchant-api-system');
                echo '</a>';
                echo __('<p class="ptms-local-listing-note"><strong>Important:</strong> Removing these two local features will not stop the normal free listing of your products on Google.</p>', 'pw-merchant-api-system');
                echo '</div>';
            }

            if ($documentation !== '') echo '<a class="ptms-btn secondary" href="' . esc_url($documentation) . __('" target="_blank" rel="noopener">Open Google help</a>', 'pw-merchant-api-system');
            echo '</div>';
        }
        echo '</section>';
    }

    public function dashboard() {
        $analysis = PTMS_Core::analysis();
        $product = PTMS_Core::product_analysis(1, 50, false);
        $health = PTMS_Core::merchant_health_score();
        $connected = (bool)get_option('ptms_google_connected', false)
            && !(bool)get_option('ptms_connection_reconnect_required', false)
            && (string)get_option('ptms_connection_state', '') === 'active';
        $wizard = get_option('ptms_wizard_status', array());
        $wizard_score = (int) round((count(array_filter($wizard)) / 8) * 100);
        $this->header(__('Dashboard', 'pw-merchant-api-system'), __('Monitor your Google Merchant Center provisioning, WooCommerce store, and connection status in one screen.', 'pw-merchant-api-system'));
        $this->docs(__('Summarizes your store\'s Merchant readiness.', 'pw-merchant-api-system'), __('MÖKM, MAS, PWCM and MSM.', 'pw-merchant-api-system'), __('Site and product data are analyzed locally; The Google connection is carried out via PW Connect.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/');
        echo '<div class="ptms-grid four">';
        $cards = array(
            array(__('Google Link', 'pw-merchant-api-system'), $connected ? __('Connected', 'pw-merchant-api-system') : __('not connected', 'pw-merchant-api-system'), $connected ? 'ok' : 'warn'),
            array(__('Site readiness score', 'pw-merchant-api-system'), $analysis['score'] . '/100', $analysis['score'] >= 80 ? 'ok' : 'warn'),
            array(__('Wizard progress', 'pw-merchant-api-system'), $wizard_score . '%', $wizard_score >= 80 ? 'ok' : 'warn'),
            array(__('Merchant health', 'pw-merchant-api-system'), $health['score'] . '/100', $health['score'] >= 80 ? 'ok' : ($health['score'] >= 65 ? 'warn' : 'danger')),
        );
        foreach ($cards as $card) { echo '<div class="ptms-card metric"><span>' . esc_html($card[0]) . '</span><strong class="' . esc_attr($card[2]) . '">' . esc_html($card[1]) . '</strong></div>'; }
        echo '</div>';
        echo __('<div class="ptms-grid two"><div class="ptms-card"><h2>Priority transactions</h2>', 'pw-merchant-api-system');
        if (!$connected) { echo __('<p class="ptms-alert warn">Google account is not yet connected.</p><a class="ptms-btn" href="', 'pw-merchant-api-system') . esc_url(admin_url('admin.php?page=' . $this->slug . '-google')) . __('">Go to Google link</a>', 'pw-merchant-api-system'); }
        elseif ($analysis['score'] < 80) { echo __('<p class="ptms-alert warn">Site readiness score should be improved.</p><a class="ptms-btn" href="', 'pw-merchant-api-system') . esc_url(admin_url('admin.php?page=' . $this->slug . '-site-analizi')) . __('">Turn on site analysis</a>', 'pw-merchant-api-system'); }
        else { echo __('<p class="ptms-alert success">Basic readiness checks positive.</p>', 'pw-merchant-api-system'); }
        echo '</div><div class="ptms-card"><h2>' . esc_html__('System status', 'pw-merchant-api-system') . '</h2><ul class="ptms-status-list"><li><span>WooCommerce</span><strong>' . (class_exists('WooCommerce') ? esc_html__('Active', 'pw-merchant-api-system') : esc_html__('Inactive', 'pw-merchant-api-system')) . '</strong></li><li><span>PW Connect</span><strong>' . esc_html__('Configured', 'pw-merchant-api-system') . '</strong></li><li><span>' . esc_html__('Domain fingerprint', 'pw-merchant-api-system') . '</span><code>' . esc_html(substr(PTMS_Core::domain_fingerprint(), 0, 16)) . '…</code></li></ul></div></div>';
        $this->footer();
    }

    public function google_connection() {
        $remote_check = PTMS_Core::refresh_connection_status(true);
        $connected = (bool)get_option('ptms_google_connected', false)
            && !(bool)get_option('ptms_connection_reconnect_required', false)
            && (string)get_option('ptms_connection_state', '') === 'active';
        $reconnect_required = (bool)get_option('ptms_connection_reconnect_required', false);
        $email = (string) get_option('ptms_google_email', '');
        $merchant_id = (string) get_option('ptms_merchant_id', '');
        $connect_url = PTMS_Core::connect_start_url();
        $connect_error = is_wp_error($connect_url) ? $connect_url->get_error_message() : '';
        $pending_accounts = get_option('ptms_pending_merchant_accounts', array());
        $pending_email = (string) get_option('ptms_pending_google_email', '');
        $pending_connection_id = (string) get_option('ptms_pending_connection_id', '');
        $check_notice = get_transient('ptms_connect_check_' . get_current_user_id());
        if ($check_notice !== false) delete_transient('ptms_connect_check_' . get_current_user_id());
        $this->header(__('Google Link', 'pw-merchant-api-system'), __('The user simply selects the Google account; OAuth and token management are handled on PW Connect.', 'pw-merchant-api-system'));
        $this->docs(__('Manages Google account and Merchant Center connection.', 'pw-merchant-api-system'), 'PWCM, Google OAuth 2.0 ve Merchant API.', __('The Connect with Google button directs you to the secure PW Connect stream.', 'pw-merchant-api-system'), 'https://developers.google.com/merchant/api/guides/authorization/overview');
        if (is_array($check_notice) && !empty($check_notice['message'])) {
            $notice_class = !empty($check_notice['success']) ? 'success' : (!empty($check_notice['error']) ? 'danger' : 'info');
            echo '<div class="ptms-alert ' . esc_attr($notice_class) . '"><strong>' . esc_html((string)$check_notice['message']) . '</strong></div>';
        }
        if ($reconnect_required) {
            $reconnect_message = (string)get_option('ptms_connection_status_message', __('Google Merchant connection must be re-established.', 'pw-merchant-api-system'));
            echo '<div class="ptms-alert danger"><strong>' . esc_html__('Google connection must be re-established.', 'pw-merchant-api-system') . '</strong> '
                . esc_html($reconnect_message) . ' '
                . esc_html__('Pending product transactions are protected and will resume automatically after reconnection.', 'pw-merchant-api-system')
                . '</div>';
        } elseif (is_wp_error($remote_check)) {
            echo '<div class="ptms-alert warn"><strong>' . esc_html__('The server connection status could not be verified temporarily.', 'pw-merchant-api-system') . '</strong> '
                . esc_html($remote_check->get_error_message()) . '</div>';
        }
        if ($connect_error !== '') { echo __('<div class="ptms-alert danger"><strong>Connection could not be prepared:</strong>', 'pw-merchant-api-system') . esc_html($connect_error) . '</div>'; }
        if (is_array($pending_accounts) && !empty($pending_accounts) && !$connected) {
            echo __('<div class="ptms-card ptms-account-picker"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Connection successful</span><h2>Select Merchant Center account</h2></div><span class="ptms-connection-badge is-connected">Google connected</span></div>', 'pw-merchant-api-system');
            echo '<p><strong>' . esc_html($pending_email) . __('Select the Merchant Center accounts that </strong> has access to that you want to manage.</p>', 'pw-merchant-api-system');
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_select_merchant">'; wp_nonce_field('ptms_select_merchant');
            echo '<div class="ptms-account-list">';
            foreach ($pending_accounts as $index => $account) {
                if (!is_array($account)) continue;
                $id = preg_replace('/\D+/', '', (string)($account['accountId'] ?? ''));
                $name = sanitize_text_field((string)($account['accountName'] ?? __('Merchant Center Account', 'pw-merchant-api-system')));
                if ($id === '') continue;
                echo '<label class="ptms-account-option"><input type="radio" name="merchant_account" value="' . esc_attr($id) . '" ' . checked($index, 0, false) . '><span><strong>' . esc_html($name) . __('</strong><small>Merchant Center ID:', 'pw-merchant-api-system') . esc_html($id) . '</small></span></label>';
            }
            echo '</div><button class="ptms-btn large" type="submit">Bu hesapla devam et</button></form></div>';
        }

        echo '<div class="ptms-connection-layout"><div class="ptms-card ptms-connect-card ' . ($connected ? 'is-connected' : 'is-waiting') . __('"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Google connection</span><h2>Connection status</h2></div><span class="ptms-connection-badge', 'pw-merchant-api-system') . ($connected ? 'is-connected' : 'is-waiting') . '">' . ($connected ? __('Connected', 'pw-merchant-api-system') : __('Waiting for connection', 'pw-merchant-api-system')) . '</span></div>';
        if ($connected) {
            echo __('<p class="ptms-alert success"><strong>Google connection is active.</strong> Secure communication can be established with Merchant API.</p><dl class="ptms-details"><dt>Google account</dt><dd>', 'pw-merchant-api-system') . esc_html($email ?: __('Linked account', 'pw-merchant-api-system')) . __('</dd><dt>Merchant Center ID</dt><dd>', 'pw-merchant-api-system') . esc_html($merchant_id ?: __('Not yet selected', 'pw-merchant-api-system')) . __('</dd><dt>PW Connect</dt><dd>Running</dd><dt>Merchant API</dt><dd>Ready</dd></dl>', 'pw-merchant-api-system');
            echo '<div class="ptms-connect-actions"><a class="ptms-btn secondary" href="' . esc_url(is_wp_error($connect_url) ? '#' : $connect_url) . __('" target="_blank" rel="noopener">Refresh link</a><form method="post" action="', 'pw-merchant-api-system') . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_disconnect">'; wp_nonce_field('ptms_disconnect'); echo __('<button class="ptms-btn danger" type="submit">Disconnect</button></form></div>', 'pw-merchant-api-system');
        } else {
            echo '<div class="ptms-connect-fixed-layout" style="display:grid!important;grid-template-columns:minmax(0,1fr)!important;row-gap:20px!important;width:100%!important;align-items:start!important">';
            echo __('<p class="ptms-alert warn" style="display:block!important;width:100%!important;box-sizing:border-box!important;margin:0!important">The Google account is not yet connected to the system. The transaction is renewed in a new tab and is carried out via the secure PW Connect service. These processes are designed not to burden your website.</p>', 'pw-merchant-api-system');
            echo '<div style="display:block!important;margin:0!important"><a id="ptms-google-connect" class="ptms-btn large" href="' . esc_url(is_wp_error($connect_url) ? '#' : $connect_url) . __('" target="_blank" rel="noopener">Connect with Google</a></div>', 'pw-merchant-api-system');
            echo __('<p class="ptms-muted" style="display:block!important;width:100%!important;margin:0!important;line-height:1.6!important">Select your Google account in the new tab and allow it. The connection status is automatically checked on this page.</p>', 'pw-merchant-api-system');
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="ptms-connect-check-form" style="display:block!important;margin:0!important"><input type="hidden" name="action" value="ptms_check_google_connection">';
            wp_nonce_field('ptms_check_google_connection');
            echo __('<button class="ptms-btn secondary" type="submit">Recheck connection</button></form>', 'pw-merchant-api-system');
            echo __('<div class="ptms-alert info" style="display:grid!important;grid-template-columns:minmax(0,1fr)!important;row-gap:14px!important;width:100%!important;box-sizing:border-box!important;margin:0!important;padding:16px!important"><strong style="margin:0!important">About the connection process</strong><p style="margin:0!important">After the Google connection is completed, your Merchant Center accounts are automatically read. If there is a temporary preparation period due to the initial system installation, you can wait a few minutes and use the “Recheck connection” button.</p><p style="margin:0!important">This button only checks the status of the current connection; It does not create a new Google link. If your connection is complete, you do not need to use it again.</p></div>', 'pw-merchant-api-system');
            echo '</div>';
        }
        $has_pending_accounts = is_array($pending_accounts) && !empty($pending_accounts);
        $has_pending_connection = $pending_connection_id !== '';
        $flow_stage = $connected ? 'connected' : ($has_pending_accounts ? 'account_selection' : ($has_pending_connection ? 'merchant_preparing' : 'not_started'));
        echo '</div><div class="ptms-card ptms-health-flow-card" data-stage="' . esc_attr($flow_stage) . __('"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Actual status</span><h2>Connection health report</h2></div><span class="ptms-live-dot">Server verification</span></div><p class="ptms-muted ptms-flow-intro">Each step is shown according to the actual connection status recorded on PW Connect and WordPress.</p><ol class="ptms-connection-flow">', 'pw-merchant-api-system');
        $steps = array(
            array('pw-connect', __('Access to PW Connect service', 'pw-merchant-api-system'), __('Service response and secure connection are checked.', 'pw-merchant-api-system')),
            array('secure-request', __('Preparing secure request', 'pw-merchant-api-system'), __('Timestamp, nonce and signature checks are prepared.', 'pw-merchant-api-system')),
            array('google-account', __('Google account selection', 'pw-merchant-api-system'), __('The user is expected to select the Google account.', 'pw-merchant-api-system')),
            array('oauth', 'Google izinleri inceleniyor', __('OAuth permissions and Merchant scope are verified.', 'pw-merchant-api-system')),
            array('merchant-api', __('Merchant API connection', 'pw-merchant-api-system'), __('Merchant Center accounts are read securely.', 'pw-merchant-api-system')),
            array('merchant-select', __('Merchant Center account selection', 'pw-merchant-api-system'), __('The Merchant Center account to be managed is determined.', 'pw-merchant-api-system')),
        );
        foreach ($steps as $index => $step) {
            $state = 'waiting';
            $label = __('not started yet', 'pw-merchant-api-system');
            if ($connected) {
                $state = 'completed';
                $label = __('completed', 'pw-merchant-api-system');
            } elseif ($has_pending_accounts) {
                if ($index <= 4) { $state = 'completed'; $label = __('completed', 'pw-merchant-api-system'); }
                elseif ($index === 5) { $state = 'reviewing'; $label = __('Make your account selection', 'pw-merchant-api-system'); }
            } elseif ($has_pending_connection) {
                if ($index <= 3) { $state = 'completed'; $label = __('completed', 'pw-merchant-api-system'); }
                elseif ($index === 4) { $state = 'reviewing'; $label = __('Google preparations continue', 'pw-merchant-api-system'); }
                else { $label = 'Merchant API bekleniyor'; }
            } elseif ($index === 0) {
                $state = 'completed';
                $label = __('completed', 'pw-merchant-api-system');
            }
            echo '<li class="ptms-flow-step is-' . esc_attr($state) . '" data-step="' . esc_attr($step[0]) . '"><span class="ptms-flow-icon"><i></i></span><div class="ptms-flow-copy"><strong>' . esc_html($step[1]) . '</strong><small>' . esc_html($step[2]) . '</small></div><span class="ptms-flow-status">' . esc_html($label) . '</span></li>';
        }
        $flow_summary = __('Google link is waiting to be initialized', 'pw-merchant-api-system');
        if ($connected) $flow_summary = __('All connection checks completed', 'pw-merchant-api-system');
        elseif ($has_pending_accounts) $flow_summary = __('Merchant Center account waiting to be selected', 'pw-merchant-api-system');
        elseif ($has_pending_connection) $flow_summary = __('Google connected; Merchant API preparation continues', 'pw-merchant-api-system');
        echo __('</ol><div class="ptms-flow-summary"><span>Overall connection health</span><strong>', 'pw-merchant-api-system') . esc_html($flow_summary) . '</strong></div></div></div>';
        echo __('<div class="ptms-card ptms-security-card"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Security layer</span><h2>What should the user know?</h2></div></div><ul class="ptms-check-list"><li>OAuth Client Private Key is not kept within WordPress.</li><li>Access and refresh tokens are encrypted on PW Connect.</li><li>Requests are verified with HMAC, nonce, and timestamp.</li><li>The user does not log into the Google Cloud Console and does not see the token.</li></ul></div>', 'pw-merchant-api-system');
        $this->footer();
    }

    public function wizard() {
        $steps = $this->wizard_steps(); $saved = get_option('ptms_wizard_status', array());
        $this->header(__('Preparation Wizard', 'pw-merchant-api-system'), __('Complete the Merchant Center installation step by step without going into technical details.', 'pw-merchant-api-system'));
        $this->docs(__('It makes the deficiencies in the Merchant preparation visible.', 'pw-merchant-api-system'), __('PTDS and MÖKM.', 'pw-merchant-api-system'), __('Mark and save each step as you complete it.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/');
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_save_wizard">'; wp_nonce_field('ptms_save_wizard'); echo '<div class="ptms-card"><div class="ptms-step-list">';
        foreach ($steps as $key => $step) { echo '<label class="ptms-step"><input type="checkbox" name="steps[' . esc_attr($key) . ']" value="1" ' . checked(!empty($saved[$key]), true, false) . '><span><strong>' . esc_html($step[0]) . '</strong><small>' . esc_html($step[1]) . '</small></span></label>'; }
        echo '</div><button class="ptms-btn" type="submit">' . esc_html__('Save status', 'pw-merchant-api-system') . '</button></div></form>';
        $this->footer();
    }

    private function wizard_steps() {
        return array(
            'merchant_account' => array(__('Merchant Center Account', 'pw-merchant-api-system'), __('Google Merchant Center account must exist.', 'pw-merchant-api-system')),
            'merchant_id' => array(__('Merchant Center ID', 'pw-merchant-api-system'), __('It is read automatically after connection or shown in account selection.', 'pw-merchant-api-system')),
            'website' => array(__('Website Verification', 'pw-merchant-api-system'), __('Google must verify that the site belongs to you.', 'pw-merchant-api-system')),
            'domain' => array(__('Domain Verification', 'pw-merchant-api-system'), __('The domain name must have been requested in the Merchant Center account.', 'pw-merchant-api-system')),
            'data_source' => array(__('Data Source', 'pw-merchant-api-system'), __('The source from which product information will be transferred to Google must be ready.', 'pw-merchant-api-system')),
            'google_ads' => array('Google Ads', __('The optional ad account link should be checked.', 'pw-merchant-api-system')),
            'final' => array(__('Final Check', 'pw-merchant-api-system'), __('Critical deficiencies must be closed.', 'pw-merchant-api-system')),
            'score' => array(__('Preparation Score', 'pw-merchant-api-system'), __('The overall preparation score should be evaluated.', 'pw-merchant-api-system')),
        );
    }

    public function save_wizard() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_save_wizard');
        $steps = isset($_POST['steps']) && is_array($_POST['steps']) ? array_map('absint', wp_unslash($_POST['steps'])) : array();
        update_option('ptms_wizard_status', $steps, false);
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '&saved=1')); exit;
    }

    public function site_analysis() {
        $analysis = PTMS_Core::analysis();
        $this->header(__('Site Analysis', 'pw-merchant-api-system'), __('MÖKM checks the technical and store preparation before Merchant Center.', 'pw-merchant-api-system'));
        $this->docs(__('Finds critical readiness issues at the site level.', 'pw-merchant-api-system'), __('WordPress Site Health, WooCommerce and MÖKM.', 'pw-merchant-api-system'), __('Checks are carried out locally; The data is not sent to Google.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/answer/6363310');
        echo '<div class="ptms-score"><strong>' . esc_html($analysis['score']) . __('</strong><span>/100 preparation score</span></div><div class="ptms-card"><table class="ptms-table"><thead><tr><th>Control</th><th>Status</th><th>Description</th></tr></thead><tbody>', 'pw-merchant-api-system');
        foreach ($analysis['checks'] as $check) { echo '<tr><td><strong>' . esc_html($check['title']) . '</strong></td><td><span class="ptms-pill ' . ($check['ok'] ? 'ok' : 'warn') . '">' . ($check['ok'] ? 'Uygun' : 'Dikkat') . '</span></td><td>' . esc_html($check['message']) . '</td></tr>'; }
        echo '</tbody></table></div>';
        $this->footer();
    }

    public function product_analysis() {
        $page = isset($_GET['ptms_product_page']) ? max(1, (int) $_GET['ptms_product_page']) : 1;
        $filter = isset($_GET['ptms_filter']) ? sanitize_key(wp_unslash($_GET['ptms_filter'])) : 'all';
        $data = PTMS_Core::product_analysis($page, 50, true, $filter);
        $this->header(__('Product Analysis', 'pw-merchant-api-system'), __('MAS scans all live WooCommerce products for Merchant requirements. Results are displayed at 50 products per page.', 'pw-merchant-api-system'));
        $this->docs(__('Shows missing price, image, description, brand and stock status.', 'pw-merchant-api-system'), __('WooCommerce product data and MAS.', 'pw-merchant-api-system'), __('Analysis is done only in the WordPress database.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/answer/7052112');
        if (!class_exists('WooCommerce')) { echo __('<div class="ptms-alert danger">WooCommerce is not active.</div>', 'pw-merchant-api-system'); $this->footer(); return; }
        $base_url = admin_url('admin.php?page=' . $this->slug . '-urun-analizi');
        $all_url = remove_query_arg(array('ptms_filter', 'ptms_product_page'), $base_url);
        $issues_url = add_query_arg('ptms_filter', 'issues', $all_url);
        $suitable_url = add_query_arg('ptms_filter', 'suitable', $all_url);
        echo '<div class="ptms-grid three">';
        echo '<a class="ptms-card metric ptms-metric-link ' . ($data['filter'] === 'all' ? 'active' : '') . '" href="' . esc_url($all_url) . __('"><span>Product reviewed</span><strong>', 'pw-merchant-api-system') . esc_html($data['total']) . __('</strong><small>Show all products</small></a>', 'pw-merchant-api-system');
        echo '<a class="ptms-card metric ptms-metric-link ' . ($data['filter'] === 'issues' ? 'active danger-card' : '') . '" href="' . esc_url($issues_url) . __('"><span>Problem product</span><strong class="danger">', 'pw-merchant-api-system') . esc_html($data['issues']) . __('</strong><small>Show only problems</small></a>', 'pw-merchant-api-system');
        echo '<a class="ptms-card metric ptms-metric-link ' . ($data['filter'] === 'suitable' ? 'active success-card' : '') . '" href="' . esc_url($suitable_url) . __('"><span>Suitable product</span><strong class="ok">', 'pw-merchant-api-system') . esc_html($data['suitable']) . __('</strong><small>Show available only</small></a>', 'pw-merchant-api-system');
        echo '</div>';
        if ($data['filter'] === 'issues') { echo __('<div class="ptms-alert danger"><strong>Problem products are listed:</strong>', 'pw-merchant-api-system') . esc_html($data['filtered_total']) . __('product.</div>', 'pw-merchant-api-system'); }
        elseif ($data['filter'] === 'suitable') { echo __('<div class="ptms-alert success"><strong>Suitable products are listed:</strong>', 'pw-merchant-api-system') . esc_html($data['filtered_total']) . __('product.</div>', 'pw-merchant-api-system'); }
        echo __('<div class="ptms-card"><table class="ptms-table"><thead><tr><th>Product</th><th>Brand</th><th>Data source</th><th>Status</th><th>Transaction</th></tr></thead><tbody>', 'pw-merchant-api-system');
        foreach ($data['items'] as $item) {
            $brand_value = isset($item['brand']) ? (string) $item['brand'] : '';
            $brand_source = isset($item['brand_source']) ? (string) $item['brand_source'] : '';
            $brand_key = isset($item['brand_key']) ? (string) $item['brand_key'] : '';
            echo '<tr>';
            echo '<td><strong>' . esc_html($item['name']) . '</strong><br><small>#' . esc_html($item['id']) . '</small></td>';
            echo '<td>' . ($brand_value !== '' ? '<span class="ptms-pill ok">' . esc_html($brand_value) . '</span>' : __('<span class="ptms-pill warn">Not Found</span>', 'pw-merchant-api-system')) . '</td>';
            echo '<td>' . ($brand_source !== '' ? '<strong>' . esc_html($brand_source) . '</strong>' . ($brand_key !== '' ? '<br><code>' . esc_html($brand_key) . '</code>' : '') : '<span class="ptms-muted">—</span>') . '</td>';
            echo '<td>' . (empty($item['issues']) ? '<span class="ptms-pill ok">Uygun</span>' : '<ul class="ptms-issues"><li>' . implode('</li><li>', array_map('esc_html', $item['issues'])) . '</li></ul>') . '</td>';
            echo '<td><a class="ptms-btn secondary small" href="' . esc_url($item['edit']) . __('">Edit product</a></td>', 'pw-merchant-api-system');
            echo '</tr>';
        }
        echo '</tbody></table>';
        if ($data['total_pages'] > 1) {
            $pagination_base = add_query_arg(array(
                'ptms_filter' => $data['filter'],
                'ptms_product_page' => '%#%',
            ), $base_url);
            $start_item = (($data['page'] - 1) * $data['per_page']) + 1;
            $end_item = min($data['filtered_total'], $data['page'] * $data['per_page']);
            echo '<div class="ptms-pagination-card">';
            echo '<div class="ptms-pagination-meta"><strong>' . esc_html($data['filtered_total']) . __('product</strong><span>Page', 'pw-merchant-api-system') . esc_html($data['page']) . ' / ' . esc_html($data['total_pages']) . '</span><span>' . esc_html($start_item) . '–' . esc_html($end_item) . __('showing</span></div>', 'pw-merchant-api-system');
            echo __('<nav class="ptms-pagination" aria-label="Product pages">', 'pw-merchant-api-system');
            echo wp_kses_post(paginate_links(array(
                'base'      => $pagination_base,
                'format'    => '',
                'current'   => $data['page'],
                'total'     => $data['total_pages'],
                'prev_text' => __('< Former', 'pw-merchant-api-system'),
                'next_text' => __('Next ›', 'pw-merchant-api-system'),
                'type'      => 'plain',
                'mid_size'  => 2,
                'end_size'  => 1,
                'show_all'  => false,
            )));
            echo '</nav></div>';
        }
        echo '</div>';
        $this->footer();
    }

    public function refresh_merchant_issues() {
        if (!current_user_can('manage_options')) wp_die('Yetkiniz bulunmuyor.');
        check_admin_referer('ptms_refresh_merchant_issues');
        $result = PTMS_Core::refresh_merchant_issues(true);
        $url = admin_url('admin.php?page=' . $this->slug . '-sorun-merkezi');
        if (is_wp_error($result)) $url = add_query_arg(array('ptms_notice'=>'error','ptms_message'=>$result->get_error_message()), $url);
        else $url = add_query_arg('ptms_notice','refreshed',$url);
        wp_safe_redirect($url); exit;
    }

    public function merchant_issues() {
        $page=max(1,(int)($_GET['paged']??1)); $filter=sanitize_key((string)($_GET['ptms_status']??'all')); $code=sanitize_key((string)($_GET['ptms_issue']??''));
        $data=PTMS_Core::merchant_issues($page,50,$filter,$code);
        $this->header('Merchant Sorun Merkezi',__('Review product problems reported by Google Merchant Center with Turkish explanations and solution suggestions.', 'pw-merchant-api-system'));
        $this->docs(__('It reads the problems of the products evaluated by Google, classifies them and explains the solution.', 'pw-merchant-api-system'),'Merchant API v1, PW Feed Intelligence Reader ve PT Smart Cache Engine.',__('Data is cached for 15 minutes. The “Refresh Google status” button retrieves new data only when needed. Google messages in English are not shown to the user.', 'pw-merchant-api-system'),'https://support.google.com/merchants/answer/12159029');
        if(isset($_GET['ptms_notice']) && $_GET['ptms_notice']==='refreshed') echo __('<div class="ptms-alert success">Merchant issues have been updated from Google.</div>', 'pw-merchant-api-system');
        if(isset($_GET['ptms_notice']) && $_GET['ptms_notice']==='error') echo '<div class="ptms-alert danger">'.esc_html(sanitize_text_field(wp_unslash($_GET['ptms_message']??__('Problems not received.', 'pw-merchant-api-system')))).'</div>';
        echo __('<div class="ptms-card"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Current Google data</span><h2>Recheck Google status</h2><p class="ptms-muted">When you correct a setting or clear a warning in Google Merchant Center, the change may not be reflected in the plugin immediately. This button does not resend existing products; It refreshes the Issue Center by receiving Google\'s current product and account notifications.</p></div><form method="post" action="', 'pw-merchant-api-system').esc_url(admin_url('admin-post.php')).'"><input type="hidden" name="action" value="ptms_refresh_merchant_issues">';
        wp_nonce_field('ptms_refresh_merchant_issues');
        echo '<button class="ptms-btn" type="submit">'.esc_html__('Refresh Google status', 'pw-merchant-api-system').'</button></form></div></div>';
        if(is_wp_error($data)){ echo __('<div class="ptms-alert danger"><strong>Problems not received:</strong>', 'pw-merchant-api-system').esc_html($data->get_error_message()).'</div>'; $this->footer(); return; }
        $cache=(array)$data['cache']; $summary=(array)($cache['summary']??array()); $severity=(array)($cache['severity_counts']??array()); $checked=(int)($cache['checked_timestamp']??0);
        $this->render_account_merchant_issues((array)($cache['account_issues'] ?? array()));
        echo '<div class="ptms-grid four">';
        $cards=array(array(__('unique product', 'pw-merchant-api-system'),(int)($summary['total']??0),'ok'),array(__('Problematic product', 'pw-merchant-api-system'),(int)($summary['with_issues']??count($cache['products']??array())),'danger'),array(__('problem free product', 'pw-merchant-api-system'),(int)($summary['clean']??0),'ok'),array(__('critical product', 'pw-merchant-api-system'),(int)($summary['critical_products']??0),'warn'));
        foreach($cards as $c) echo '<div class="ptms-card metric"><span>'.esc_html($c[0]).'</span><strong class="'.esc_attr($c[2]).'">'.esc_html((string)$c[1]).'</strong></div>';
        echo '</div>';
        echo '<div class="ptms-card ptms-issue-summary"><div class="ptms-grid four"><div><span>'.esc_html__('Total findings', 'pw-merchant-api-system').'</span><strong>'.esc_html((string)($summary['total_findings']??0)).'</strong></div><div><span>'.esc_html__('Unapproved product', 'pw-merchant-api-system').'</span><strong>'.esc_html((string)($summary['disapproved']??0)).'</strong></div><div><span>'.esc_html__('Limited product', 'pw-merchant-api-system').'</span><strong>'.esc_html((string)($summary['limited']??0)).'</strong></div><div><span>'.esc_html__('Pending review', 'pw-merchant-api-system').'</span><strong>'.esc_html((string)($summary['pending']??0)).'</strong></div></div><p class="ptms-muted ptms-source-scope-note">'.esc_html__('These numbers only represent unique products in the PW Merchant API data source. If the same problem is repeated in different publication areas, it is combined under a single finding.', 'pw-merchant-api-system').'</p></div>';
        echo __('<div class="ptms-card"><div class="ptms-card-head"><div><span class="ptms-eyebrow">PW Feed Intelligence Reader</span><h2>Google product reviews</h2><p class="ptms-muted">Last check:', 'pw-merchant-api-system').esc_html($checked?wp_date('d.m.Y H:i',$checked):__('Not updated yet', 'pw-merchant-api-system')).'</p></div></div>';
        echo '<form method="get" class="ptms-filter-row"><input type="hidden" name="page" value="'.esc_attr($this->slug.'-sorun-merkezi').'"><select name="ptms_status"><option value="all" '.selected($filter,'all',false).__('>All issues</option><option value="disapproved"', 'pw-merchant-api-system').selected($filter,'disapproved',false).'>Onaylanmayanlar</option><option value="limited" '.selected($filter,'limited',false).__('>Limited ones</option><option value="pending"', 'pw-merchant-api-system').selected($filter,'pending',false).__('>Pending review</option></select><select name="ptms_issue"><option value="">All issue types</option>', 'pw-merchant-api-system');
        foreach((array)($cache['issue_counts']??array()) as $issue_code=>$count){$tr=PTMS_Core::translate_merchant_issue(array('code'=>$issue_code)); echo '<option value="'.esc_attr($issue_code).'" '.selected($code,$issue_code,false).'>'.esc_html($tr['title'].' ('.$count.')').'</option>';}
        echo '</select><button class="ptms-btn secondary" type="submit">Filtrele</button></form></div>';
        if(empty($data['rows'])) echo __('<div class="ptms-card"><p class="ptms-empty">No problematic product was found in the selected filter.</p></div>', 'pw-merchant-api-system');
        else {
            echo '<div class="ptms-issues-list">';
            foreach($data['rows'] as $product){
                echo '<div class="ptms-card ptms-issue-product"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Offer ID: '.esc_html((string)$product['offer_id']).'</span><h2>'.esc_html((string)($product['title']?:__('Product name could not be retrieved', 'pw-merchant-api-system'))).'</h2><p class="ptms-muted">'.esc_html((string)($product['brand']?:__('Brand not specified', 'pw-merchant-api-system'))).'</p></div>';
                if(!empty($product['link'])) echo '<a class="ptms-btn secondary" target="_blank" rel="noopener" href="'.esc_url($product['link']).__('">Open Product</a>', 'pw-merchant-api-system');
                echo '</div><div class="ptms-issue-items">';
                foreach((array)$product['issues'] as $issue){
                    $priority=(string)($issue['priority']??'medium');
                    echo '<div class="ptms-issue-item is-'.esc_attr($priority).'"><div><span class="ptms-issue-level">'.esc_html($priority==='high'?__('Important', 'pw-merchant-api-system'):($priority==='low'?'Bilgi':__('Should be fixed', 'pw-merchant-api-system'))).'</span><h3>'.esc_html((string)$issue['title']).'</h3></div>';
                    echo '<p><strong>Neden?</strong> '.esc_html((string)$issue['explanation']).__('</p><p><strong>Solution:</strong>', 'pw-merchant-api-system').esc_html((string)$issue['solution']).'</p>';
                    echo $this->merchant_issue_scope_html((array)$issue);
                    echo '</div>';
                }
                echo '</div></div>';
            }
            echo '</div>';
        }
        if((int)$data['pages']>1){$base=remove_query_arg('paged'); echo '<div class="ptms-pagination">'; if((int)$data['page']>1) echo '<a class="ptms-page" href="'.esc_url(add_query_arg('paged',(int)$data['page']-1,$base)).'">'.esc_html__('Previous', 'pw-merchant-api-system').'</a>'; for($i=1;$i<=(int)$data['pages'];$i++){ if($i>2 && $i<(int)$data['page']-2 || $i<(int)$data['pages']-1 && $i>(int)$data['page']+2) continue; echo '<a class="ptms-page '.($i===(int)$data['page']?'active':'').'" href="'.esc_url(add_query_arg('paged',$i,$base)).'">'.$i.'</a>'; } if((int)$data['page']<(int)$data['pages']) echo '<a class="ptms-page" href="'.esc_url(add_query_arg('paged',(int)$data['page']+1,$base)).'">'.esc_html__('Next', 'pw-merchant-api-system').'</a>'; echo '</div>';}
        if(empty($cache['collection_complete'])) echo __('<div class="ptms-alert warn"><strong>List could not be completed:</strong> Because the entire Google product list cannot be retrieved, counters are based on read records only. Reuse the Update from Google button.</div>', 'pw-merchant-api-system');
        $this->footer();
    }

    public function merchant_health() {
        $health = PTMS_Core::merchant_health_score();
        $this->header(__('Merchant Health Center', 'pw-merchant-api-system'), __('PMHS; scores site, product, staging and Google link data with real analysis results.', 'pw-merchant-api-system'));
        $this->docs(__('Provides dynamic health score that can explain the reasons for Merchant preparation.', 'pw-merchant-api-system'), __('PW Feed Health Score (PMHS), MSM, MÖKM, MAS and PWCM.', 'pw-merchant-api-system'), __('Each category is calculated according to its own weight. Fixed or sample scores are not used.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/');

        $score_class = $health['score'] >= 80 ? 'good' : ($health['score'] >= 65 ? 'medium' : 'low');
        echo '<div class="ptms-health-hero ' . esc_attr($score_class) . '">';
        echo '<div class="ptms-health-score"><strong>' . esc_html($health['score']) . '</strong><span>/100</span></div>';
        echo '<div class="ptms-health-summary"><span class="ptms-health-label">' . esc_html($health['label']) . __('</span><h2>Overall Merchant health</h2><p>This score was calculated from real site and product data. Each title shows why points were gained or lost.</p><div class="ptms-progress"><i style="width:', 'pw-merchant-api-system') . esc_attr($health['score']) . '%"></i></div></div>';
        echo '</div>';

        if (!empty($health['best_action'])) {
            $best = $health['best_action'];
            $gain = max(0, (int) $best['weight'] - (int) $best['score']);
            echo __('<div class="ptms-best-action"><div><span>The action that will earn the most points</span><strong>', 'pw-merchant-api-system') . esc_html($best['action']) . __('</strong><small>Estimated gain: +', 'pw-merchant-api-system') . esc_html($gain) . ' puana kadar</small></div><a class="ptms-btn" href="' . esc_url($best['url']) . __('">Review</a></div>', 'pw-merchant-api-system');
        }

        echo '<div class="ptms-health-breakdown">';
        foreach ($health['categories'] as $category) {
            $percent = $category['weight'] > 0 ? (int) round(($category['score'] / $category['weight']) * 100) : 0;
            $state = $percent >= 90 ? 'ok' : ($percent >= 60 ? 'warn' : 'danger');
            echo '<details class="ptms-health-item" ' . ($state === 'danger' ? 'open' : '') . '><summary><div><strong>' . esc_html($category['title']) . '</strong><span>' . esc_html($category['detail']) . '</span></div><div class="ptms-health-points ' . esc_attr($state) . '">' . esc_html($category['score']) . ' / ' . esc_html($category['weight']) . '</div></summary>';
            echo '<div class="ptms-health-item-body"><div class="ptms-mini-progress"><i style="width:' . esc_attr($percent) . '%"></i></div><p>' . esc_html($category['action']) . '</p><a href="' . esc_url($category['url']) . __('">Open the relevant section →</a></div></details>', 'pw-merchant-api-system');
        }
        echo '</div>';

        if (!empty($health['history'])) {
            echo __('<div class="ptms-card"><h2>Health score history</h2><div class="ptms-history">', 'pw-merchant-api-system');
            foreach (array_slice($health['history'], -7, null, true) as $date => $value) {
                echo '<div><span>' . esc_html(wp_date('d.m', strtotime($date))) . '</span><strong>' . esc_html($value) . '</strong></div>';
            }
            echo '</div></div>';
        }
        $this->footer();
    }

    public function logs() {
        $logs=PTMS_Core::user_sync_logs(100);
        $this->header(__('diaries', 'pw-merchant-api-system'), __('Monitor OAuth, API and sync events from a single center.', 'pw-merchant-api-system'));
        $this->docs(__('Shows submit, delete, retry, and worker events.', 'pw-merchant-api-system'), __('PW Worker Engine event log.', 'pw-merchant-api-system'), __('The newest record is shown at the top; sensitive keys are not saved.', 'pw-merchant-api-system'), 'https://developers.google.com/merchant/api/guides/error-messages');
        echo __('<div class="ptms-card"><div class="ptms-card-head"><div><h2>System events</h2><p class="ptms-muted">Showing the last 100 records.</p></div>', 'pw-merchant-api-system');
        echo '<form method="post" action="'.esc_url(admin_url('admin-post.php')).'">'; wp_nonce_field('ptms_clear_logs'); echo __('<input type="hidden" name="action" value="ptms_clear_logs"><button class="ptms-btn secondary" type="submit">Clear logs</button></form></div>', 'pw-merchant-api-system');
        if(!$logs) echo __('<p class="ptms-empty">No records yet.</p>', 'pw-merchant-api-system'); else { echo '<div class="ptms-log-list">'; foreach($logs as $log){$level=sanitize_key((string)($log['level']??'info'));$time=!empty($log['time'])?wp_date('d.m.Y H:i:s',(int)$log['time']):'—';$detail=(string)($log['detail']??''); echo '<div class="ptms-log-row is-'.esc_attr($level).'"><span class="ptms-log-dot"></span><div><strong>'.esc_html((string)($log['message']??'')).'</strong>'.($detail!==''?'<p class="ptms-log-detail">'.esc_html($detail).'</p>':'').'<small>'.esc_html($time).'</small></div></div>'; } echo '</div>'; }
        echo '</div>'; $this->footer();
    }

    public function clear_logs(){ if(!current_user_can('manage_options')) wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); check_admin_referer('ptms_clear_logs'); update_option('ptms_sync_logs',array(),false); wp_safe_redirect(admin_url('admin.php?page='.$this->slug.'-gunlukler&cleared=1')); exit; }

    public function api_usage(){ $u=PTMS_Core::api_usage_status(); $t=$u['today']; $this->header(__('API Usage', 'pw-merchant-api-system'),__('Track Google Merchant API requests and product quantities processed.', 'pw-merchant-api-system')); $this->docs(__('Locally counts API calls made by PW Feed.', 'pw-merchant-api-system'),__('Native API usage monitor.', 'pw-merchant-api-system'),__('This screen shows PW Feed usage, not the official quota limit of the Google account.', 'pw-merchant-api-system'),'https://developers.google.com/merchant/api/guides/quotas'); echo __('<div class="ptms-grid four"><div class="ptms-card metric"><span>Today\'s request</span><strong>', 'pw-merchant-api-system').(int)$t['requests'].__('</strong></div><div class="ptms-card metric"><span>Processed product</span><strong>', 'pw-merchant-api-system').(int)$t['products'].__('</strong></div><div class="ptms-card metric"><span>Successful call</span><strong class="ok">', 'pw-merchant-api-system').(int)$t['success'].__('</strong></div><div class="ptms-card metric"><span>Failed call</span><strong class="danger">', 'pw-merchant-api-system').(int)$t['failed'].__('</strong></div></div><div class="ptms-alert warn"><strong>Important:</strong> Google quota limits may vary by account and API method. This panel only measures calls made by PW Feed; It does not show a fake fixed quota.</div>', 'pw-merchant-api-system'); echo __('<div class="ptms-card"><h2>Last 31 days</h2><table class="ptms-table"><thead><tr><th>Date</th><th>Request</th><th>Product</th><th>Successful</th><th>Failure</th></tr></thead><tbody>', 'pw-merchant-api-system'); foreach(array_reverse($u['history'],true) as $d=>$r) echo '<tr><td>'.esc_html($d).'</td><td>'.(int)$r['requests'].'</td><td>'.(int)$r['products'].'</td><td>'.(int)$r['success'].'</td><td>'.(int)$r['failed'].'</td></tr>'; echo '</tbody></table></div>'; $this->footer(); }

    public function add_product_merchant_box(){ add_meta_box('ptms-product-merchant','PW Feed',array($this, 'render_product_merchant_box'),'product','side','high'); }

    public function render_product_merchant_box($post){
        wp_nonce_field('ptms_product_merchant','ptms_product_merchant_nonce');
        $excluded=get_post_meta($post->ID,'_ptms_exclude',true)==='yes';
        $gtin=(string)get_post_meta($post->ID,'_ptms_gtin',true);
        $mpn=(string)get_post_meta($post->ID,'_ptms_mpn',true);
        echo '<p><label><input type="checkbox" name="ptms_exclude" value="yes" ' . checked($excluded,true,false) . '> '
            . esc_html__('Exclude from Google Merchant submission', 'pw-merchant-api-system') . '</label></p>';
        echo '<p><label><strong>GTIN / EAN</strong></label><input class="widefat" name="ptms_gtin" value="'
            . esc_attr($gtin) . '" placeholder="' . esc_attr__('Ex. 8691234567890', 'pw-merchant-api-system') . '"></p>';
        echo '<p><label><strong>MPN</strong></label><input class="widefat" name="ptms_mpn" value="'
            . esc_attr($mpn) . '" placeholder="' . esc_attr__('Manufacturer part number', 'pw-merchant-api-system') . '"></p>';
        echo '<p class="description">'
            . esc_html__('If left blank, PW Smart Detection Engine will automatically scan available product areas.', 'pw-merchant-api-system')
            . '</p>';
    }

    public function save_product_merchant_box($post_id,$post,$update){ if(!isset($_POST['ptms_product_merchant_nonce'])||!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['ptms_product_merchant_nonce'])),'ptms_product_merchant')) return; if(!current_user_can('edit_post',$post_id)||wp_is_post_revision($post_id)) return; $was=get_post_meta($post_id,'_ptms_exclude',true)==='yes'; $now=isset($_POST['ptms_exclude']); update_post_meta($post_id,'_ptms_exclude',$now?'yes':'no'); update_post_meta($post_id,'_ptms_gtin',sanitize_text_field(wp_unslash($_POST['ptms_gtin']??''))); update_post_meta($post_id,'_ptms_mpn',sanitize_text_field(wp_unslash($_POST['ptms_mpn']??''))); if($now && !$was && get_option('ptms_has_completed_initial_sync',false)){ PTMS_Core::queue_offer_delete(PTMS_Core::product_offer_id($post_id),$post_id,get_the_title($post_id)); } }

    public function product_sync() {
        $merchant = (string) get_option('ptms_merchant_id', '');
        $name = (string) get_option('ptms_merchant_name', '');
        $sync = PTMS_Core::sync_status();
        $schedule = PTMS_Core::sync_schedule_status();
        $status = (string) ($sync['status'] ?? 'ready');
        $total = (int) ($sync['total'] ?? 0);
        $done = (int) ($sync['done'] ?? 0);
        $failed = (int) ($sync['failed'] ?? 0);
        $remaining = (int) ($sync['remaining'] ?? 0);
        $failed_queue = (int) ($sync['failed_queue'] ?? 0);
        $eta_label = (string) ($sync['eta_label'] ?? '—');
        $auto = (bool) ($sync['auto_sync'] ?? true);
        $logs = PTMS_Core::user_sync_logs(8);
        $live_events = PTMS_Core::live_sync_events(8);
        $preflight = PTMS_Core::bulk_preflight();
        $history = PTMS_Core::history_stats();
        $problem_page = isset($_GET['ptms_problem_page']) ? max(1, (int) $_GET['ptms_problem_page']) : 1;
        $problem_data = PTMS_Core::cached_problem_products($problem_page, 20);
        $queue_blocked = !empty($preflight['queue_blocked']);
        $has_synced = (bool) get_option('ptms_has_completed_initial_sync', false);
        $processed = (int) ($sync['processed'] ?? 0);
        $pct = (int) ($sync['percent'] ?? 0);
        $status_label = (string) ($sync['label'] ?? __('Ready', 'pw-merchant-api-system'));
        $status_description = (string) ($sync['description'] ?? __('There is no active bulk synchronization yet.', 'pw-merchant-api-system'));
        $progress_help = (string) ($sync['progress_help'] ?? __('When bulk synchronization is started, progress is shown here.', 'pw-merchant-api-system'));
        $metric_labels = (array) ($sync['metric_labels'] ?? array());
        $metric_values = (array) ($sync['metric_values'] ?? array());

        $this->header(__('Overview', 'pw-merchant-api-system'), __('Manage the Google Merchant status of your products in a simple and understandable way.', 'pw-merchant-api-system'));

        $connected = (bool) get_option('ptms_google_connected', false) && $merchant !== '';
        $product_counts = wp_count_posts('product');
        $wc_total = isset($product_counts->publish) ? (int) $product_counts->publish : 0;
        $issue_cache = (array) get_option('ptms_merchant_issues_cache', array());
        $issue_summary = (array) ($issue_cache['summary'] ?? array());
        $has_google_snapshot = !empty($issue_cache['ok']);
        $google_total = $has_google_snapshot ? max(0, (int) ($issue_summary['total'] ?? 0)) : null;
        $problem_total = $has_google_snapshot ? max(0, (int) ($issue_summary['with_issues'] ?? 0)) : 0;
        $account_merchant_issues = (array) ($issue_cache['account_issues'] ?? array());
        $not_sent = $google_total === null ? null : max(0, $wc_total - $google_total);
        $last_google_check = (int) ($issue_cache['checked_timestamp'] ?? 0);
        $last_sync_activity = (int) ($sync['last_activity'] ?? 0);
        $last_update_at = max($last_google_check, $last_sync_activity);
        $system_state = !$connected ? __('Connection required', 'pw-merchant-api-system') : (!empty($sync['worker_active']) ? __('Sync is working', 'pw-merchant-api-system') : __('System ready', 'pw-merchant-api-system'));
        $system_state_class = !$connected ? 'danger' : (!empty($sync['worker_active']) ? 'warn' : 'success');

        $general_label = __('All products have been shipped', 'pw-merchant-api-system');
        $general_text = __('Your WooCommerce products are synced with Google Merchant Center.', 'pw-merchant-api-system');
        $general_class = 'success';
        $general_action = '';

        if (!$connected) {
            $general_label = __('Google link required', 'pw-merchant-api-system');
            $general_text = __('Complete the Google and Merchant Center link to submit products.', 'pw-merchant-api-system');
            $general_class = 'danger';
            $general_action = 'connect';
        } elseif ($status === 'running') {
            $general_label = __('Shipping continues', 'pw-merchant-api-system');
            $general_text = number_format_i18n($processed) . ' / ' . number_format_i18n($total) . __('The product has been processed. You do not need to keep this page open.', 'pw-merchant-api-system');
            $general_class = 'warn';
        } elseif (in_array($status, array('paused', 'stopped'), true) && $remaining > 0) {
            $general_label = __('Bulk sending is paused', 'pw-merchant-api-system');
            $general_text = number_format_i18n($remaining) . __('The product remained. You can safely continue where you left off.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'resume';
        } elseif ($failed > 0) {
            $general_label = __('Some products could not be sent', 'pw-merchant-api-system');
            $general_text = number_format_i18n($failed) . __('The product could not be sent. You can investigate the issues or just try these products again.', 'pw-merchant-api-system');
            $general_class = 'danger';
            $general_action = 'retry';
        } elseif (in_array($status, array('cleared', 'incomplete'), true)) {
            $general_label = __('Last batch was interrupted', 'pw-merchant-api-system');
            $general_text = __('The last batch was not completed. You can safely send the missing items by checking the products again.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'recheck';
        } elseif (!$has_synced) {
            $general_label = __('Bulk shipment has not been made yet', 'pw-merchant-api-system');
            $general_text = number_format_i18n($wc_total) . __('Published product found. You can start the first synchronization.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'initial';
        } elseif ($not_sent !== null && $not_sent > 0) {
            $general_label = __('Some products do not yet appear on Google', 'pw-merchant-api-system');
            $general_text = number_format_i18n($not_sent) . __('Google status for the product should be checked again.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'recheck';
        } elseif ($problem_total > 0) {
            $general_label = __('There is a Google problem in some products', 'pw-merchant-api-system');
            $general_text = number_format_i18n($problem_total) . __('The product requires attention for approval, data quality, or review reasons.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'problems';
        } elseif (!$has_google_snapshot) {
            $general_label = __('Google status should be updated', 'pw-merchant-api-system');
            $general_text = __('Refresh Merchant data to see the current number of products on Google.', 'pw-merchant-api-system');
            $general_class = 'warn';
            $general_action = 'refresh';
        }

        echo __('<nav class="ptms-module-tabs" aria-label="PW Feed sections">', 'pw-merchant-api-system');
        echo '<a class="is-active" href="' . esc_url(admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')) . __('">Overview</a>', 'pw-merchant-api-system');
        echo __('<a href="#ptms-full-sync">Bulk Send</a>', 'pw-merchant-api-system');
        echo __('<a href="#ptms-live-console">Live Sync</a>', 'pw-merchant-api-system');
        echo __('<a href="#ptms-problem-products">Problem Products</a>', 'pw-merchant-api-system');
        echo '<a href="#ptms-summary-status">' . esc_html__('Google Status', 'pw-merchant-api-system') . '</a>';
        echo __('<a href="#ptms-technical-details">Transaction History</a>', 'pw-merchant-api-system');
        echo '<a href="' . esc_url(admin_url('admin.php?page=' . $this->slug . '-ayarlar')) . '">' . esc_html__('Settings', 'pw-merchant-api-system') . '</a>';
        echo '</nav>';

        $google_display = $google_total === null ? max(0, (int) ($history['successful'] ?? 0)) : $google_total;
        $not_sent_display = $not_sent === null ? 0 : max(0, $not_sent);
        // Son toplu işlemde gerçekten başarısız olan benzersiz ürünler ile
        // Google tarafında henüz görünmeyen/işlenmesi beklenen ürünleri ayır.
        $bulk_failed_display = min($not_sent_display, max(0, $failed));
        $google_processing_display = max(0, $not_sent_display - $bulk_failed_display);
        echo '<div class="ptms-summary-grid">';
        echo '<a class="ptms-summary-card is-blue" href="' . esc_url(admin_url('edit.php?post_type=product')) . __('"><span>WooCommerce Products</span><strong>', 'pw-merchant-api-system') . number_format_i18n($wc_total) . __('</strong><small>Published product</small><b>See All →</b></a>', 'pw-merchant-api-system');
        echo '<a class="ptms-summary-card is-green" href="#ptms-summary-status"><span>'.esc_html__('Added to Google', 'pw-merchant-api-system').'</span><strong>' . number_format_i18n($google_display) . '</strong><small>'.esc_html__('Product appearing on Google', 'pw-merchant-api-system').'</small><b>'.esc_html__('See Status →', 'pw-merchant-api-system').'</b></a>';
        echo '<a class="ptms-summary-card is-orange" href="#ptms-problem-products"><span>Google’da Bulunmayan</span><strong>' . number_format_i18n($not_sent_display) . __('</strong><small>Cannot be sent:', 'pw-merchant-api-system') . number_format_i18n($bulk_failed_display) . __('· Expected to be processed:', 'pw-merchant-api-system') . number_format_i18n($google_processing_display) . __('</small><b>See Details →</b></a>', 'pw-merchant-api-system');
        echo __('<a class="ptms-summary-card is-red" href="#ptms-problem-products"><span>Problem Products</span><strong>', 'pw-merchant-api-system') . number_format_i18n($problem_total) . __('</strong><small>Needs editing</small><b>See Problems →</b></a>', 'pw-merchant-api-system');
        echo '</div>';
        $this->render_account_merchant_issues($account_merchant_issues, true);

        echo '<div id="ptms-summary-status" class="ptms-dashboard-focus-grid">';
        echo __('<section id="ptms-live-console" class="ptms-card ptms-command-console ptms-anchor-target"><div class="ptms-command-head"><div><span class="ptms-eyebrow">Live synchronization</span><h2>Product update transactions</h2><p>New product, editing and deletion operations can be instantly recorded here watch.</p></div><span class="ptms-console-live"><i></i> Live</span></div>', 'pw-merchant-api-system');
        if (!$live_events) {
            if ($status === 'running') {
                echo '<div class="ptms-console-empty ptms-bulk-activity" role="status" aria-live="polite">';
                echo __('<span class="ptms-activity-spinner" aria-hidden="true"></span><div><strong data-live-title>Initial sync in progress</strong>', 'pw-merchant-api-system');
                echo '<p><span data-live-processed>' . number_format_i18n($processed) . '</span> / <span data-live-total>' . number_format_i18n($total) . __('</span> product processed. Products are sent to Google Merchant in secure groups.</p>', 'pw-merchant-api-system');
                echo __('<small data-live-message>Status is automatically updated every few seconds. You do not need to keep this page open.</small></div></div>', 'pw-merchant-api-system');
            } else {
                echo __('<div class="ptms-console-empty">There are no product movements yet. When you add a new product or update a product, the action will appear here.</div>', 'pw-merchant-api-system');
            }
        } else {
            echo __('<div class="ptms-console-scroll" role="log" aria-label="Product update transactions">', 'pw-merchant-api-system');
            foreach ($live_events as $event) {
                $level = sanitize_key((string) ($event['level'] ?? 'info'));
                $time = !empty($event['time']) ? wp_date('H:i:s', (int) $event['time']) : '—';
                $date = !empty($event['time']) ? wp_date('d.m.Y', (int) $event['time']) : '';
                $name = (string) ($event['product_name'] ?? __('Product', 'pw-merchant-api-system'));
                $offer = (string) ($event['offer_id'] ?? '—');
                $title = (string) ($event['title'] ?? __('Process', 'pw-merchant-api-system'));
                $detail = (string) ($event['detail'] ?? '');
                $duration = (float) ($event['duration'] ?? 0);
                echo '<article class="ptms-console-line is-' . esc_attr($level) . '"><time>' . esc_html($time) . '</time><span class="ptms-console-mark"></span><div><strong>' . esc_html($title) . '</strong><p>' . esc_html($name) . ' <b>· Offer ID: ' . esc_html($offer) . '</b></p>';
                if ($detail !== '') echo '<small>' . esc_html($detail) . '</small>';
                echo '<em>' . esc_html($date) . ($duration > 0 ? ' · ' . esc_html(number_format_i18n($duration, 2)) . ' sn' : '') . '</em></div></article>';
            }
            echo '</div>';
        }
        echo '<div class="ptms-console-bulk-log" data-live-log-list>';
        if ($logs) {
            echo __('<div class="ptms-console-log-heading"><strong>Bulk transaction dump</strong><small>Last transactions</small></div>', 'pw-merchant-api-system');
            foreach (array_slice($logs, 0, 6) as $log) {
                $level = sanitize_key((string) ($log['level'] ?? 'info'));
                $time = !empty($log['time']) ? wp_date('H:i:s', (int) $log['time']) : '—';
                $message = (string) ($log['message'] ?? __('transaction record', 'pw-merchant-api-system'));
                $detail = (string) ($log['detail'] ?? '');
                echo '<div class="ptms-console-log-row is-' . esc_attr($level) . '"><time>' . esc_html($time) . '</time><span></span><div><strong>' . esc_html($message) . '</strong>';
                if ($detail !== '') echo '<small>' . esc_html($detail) . '</small>';
                echo '</div></div>';
            }
        }
        echo '</div>';
        echo __('<a class="ptms-console-link" href="#ptms-technical-details">View full transaction details →</a></section>', 'pw-merchant-api-system');

        echo '<aside id="ptms-system-status" class="ptms-card ptms-system-strip ptms-anchor-target"><div class="ptms-system-strip-head"><div><span class="ptms-eyebrow">PW Feed</span><h2>' . esc_html__('System status', 'pw-merchant-api-system') . '</h2></div><span class="ptms-pill ' . esc_attr($system_state_class) . '">' . esc_html($system_state) . '</span></div>';
        echo '<div class="ptms-system-strip-items">';
        echo '<div><span>Google</span><strong>' . ($connected ? __('Connected', 'pw-merchant-api-system') : __('Connection required', 'pw-merchant-api-system')) . '</strong></div>';
        echo __('<div><span>Merchant account</span><strong>', 'pw-merchant-api-system') . ($merchant !== '' ? __('Connected', 'pw-merchant-api-system') : __('Not Selected', 'pw-merchant-api-system')) . '</strong></div>';
        echo __('<div><span>Auto sync</span><strong>', 'pw-merchant-api-system') . ($auto ? __('Open', 'pw-merchant-api-system') : __('Closed', 'pw-merchant-api-system')) . '</strong></div>';
        echo '<div><span>' . esc_html__('Background worker', 'pw-merchant-api-system') . '</span><strong>' . (!empty($sync['worker_active']) ? esc_html__('Working', 'pw-merchant-api-system') : esc_html__('Ready', 'pw-merchant-api-system')) . '</strong></div>';
        echo __('<div><span>Finishing</span><strong>', 'pw-merchant-api-system') . ($last_update_at > 0 ? esc_html(wp_date('d.m.Y H:i', $last_update_at)) : __('not yet', 'pw-merchant-api-system')) . '</strong></div>';
        echo __('</div><div class="ptms-system-guidance"><p>PW Feed sends new products, updates changes and removes deleted products from Google.</p><p>It is recommended not to interfere with synchronization processes as much as possible. The system does what is necessary for you.</p><p>Transactions are carried out at regular intervals to avoid tiring your website.</p></div><a class="ptms-text-link" href="', 'pw-merchant-api-system') . esc_url(admin_url('admin.php?page=' . $this->slug . '-google')) . __('">Connection details →</a></aside>', 'pw-merchant-api-system');
        echo '</div>';

        echo '<div id="ptms-sync-status" class="ptms-card ptms-sync-live ptms-anchor-target ptms-last-bulk-card" data-status="' . esc_attr($status) . '">';
        echo __('<div class="ptms-sync-head"><div><span class="ptms-eyebrow">Historical transaction summary</span><h2 data-sync-title>Last batch transaction</h2><p class="ptms-muted" data-sync-description>', 'pw-merchant-api-system') . esc_html($status_description) . '</p></div><span class="ptms-sync-status is-' . esc_attr($status) . '">' . esc_html($status_label) . '</span></div>';
        echo '<div class="ptms-progress"><span style="width:' . (int) $pct . '%"></span></div>';
        echo '<div class="ptms-progress-meta"><strong data-sync-progress>' . (int) $processed . ' / ' . (int) $total . '</strong><span data-sync-percent>%' . (int) $pct . '</span></div>';
        echo '<p class="ptms-progress-help" data-sync-progress-help>' . esc_html($progress_help) . '</p>';
        echo '<div class="ptms-sync-metrics">';
        echo '<div><span data-sync-label-first>' . esc_html((string) ($metric_labels['first'] ?? __('Total', 'pw-merchant-api-system'))) . '</span><strong data-sync-value-first>' . (int) ($metric_values['first'] ?? $total) . '</strong></div>';
        echo '<div><span data-sync-label-second>' . esc_html((string) ($metric_labels['second'] ?? __('Successful', 'pw-merchant-api-system'))) . '</span><strong data-sync-value-second>' . (int) ($metric_values['second'] ?? $done) . '</strong></div>';
        echo '<div><span data-sync-label-third>' . esc_html((string) ($metric_labels['third'] ?? __('Unsuccessful', 'pw-merchant-api-system'))) . '</span><strong data-sync-value-third>' . (int) ($metric_values['third'] ?? $failed) . '</strong></div>';
        echo '<div><span data-sync-label-fourth>' . esc_html((string) ($metric_labels['fourth'] ?? __('Pending queue', 'pw-merchant-api-system'))) . '</span><strong data-sync-value-fourth>' . (int) ($metric_values['fourth'] ?? $remaining) . '</strong></div>';
        echo '</div><div class="ptms-worker-meta"><span>Worker: <strong data-worker-state>' . (!empty($sync['worker_active']) ? __('Working', 'pw-merchant-api-system') : __('Waiting', 'pw-merchant-api-system')) . __('</strong></span><span>Estimated remaining time: <strong data-sync-eta>', 'pw-merchant-api-system') . esc_html($eta_label) . '</strong></span></div></div>';
        echo __('<div class="ptms-alert info ptms-google-processing-note"><strong>When do Google transactions appear?</strong><p>PW Feed sends your products to Google Merchant Center. Google processes added, updated or deleted products separately in its system. Therefore, it may take a few minutes for the changes to appear in Merchant Center. In some cases, it may take longer for Google to re-evaluate products.</p></div>', 'pw-merchant-api-system');

        $problem_rows = (array) ($problem_data['rows'] ?? array());
        $problem_summary = (array) ($problem_data['summary'] ?? array());
        echo __('<div id="ptms-problem-products" class="ptms-card ptms-problem-products ptms-anchor-target"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Google Merchant status</span><h2>Problems not included</h2><p class="ptms-muted">Products not approved by Google or pending review are listed here. Queue clearing does not delete these records.</p></div><div class="ptms-card-actions"><form method="post" action="', 'pw-merchant-api-system') . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_refresh_merchant_issues">';
        wp_nonce_field('ptms_refresh_merchant_issues');
        echo __('<button class="ptms-btn secondary" type="submit">Update from Google</button></form><a class="ptms-btn secondary" href="', 'pw-merchant-api-system') . esc_url(admin_url('admin.php?page=' . $this->slug . '-sorun-merkezi')) . __('">Open All</a></div></div>', 'pw-merchant-api-system');
        if (isset($_GET['ptms_delete_offer'])) { $ok = sanitize_key((string) $_GET['ptms_delete_offer']) === 'success'; $msg = $ok ? __('The product has been removed from Google Merchant Center.', 'pw-merchant-api-system') : sanitize_text_field(rawurldecode((string) ($_GET['ptms_delete_message'] ?? __('Deletion failed.', 'pw-merchant-api-system')))); echo '<div class="ptms-alert ' . ($ok ? 'success' : 'danger') . '"><strong>' . esc_html($msg) . '</strong></div>'; }
        if ($has_google_snapshot && $not_sent_display > 0) {
            echo '<div class="ptms-merchant-gap-summary">';
            echo '<div><span>' . esc_html__('Not found on Google', 'pw-merchant-api-system') . '</span><strong>' . number_format_i18n($not_sent_display) . '</strong></div>';
            echo __('<div><span>Sending request failed</span><strong>', 'pw-merchant-api-system') . number_format_i18n($bulk_failed_display) . __('</strong><small>Only products that actually received errors in the final batch.</small></div>', 'pw-merchant-api-system');
            echo __('<div><span>Not yet visible on Google</span><strong>', 'pw-merchant-api-system') . number_format_i18n($google_processing_display) . __('</strong><small>It may be being processed by Google or the current issue may not have been renewed yet.</small></div>', 'pw-merchant-api-system');
            echo '</div>';
            if ($google_processing_display > 0) {
                echo __('<div class="ptms-alert info"><strong>Information:</strong> Even if the bulk sending request is completed successfully, Google products may process it with a delay of several minutes. You can re-read the current issues with “Update from Google”.</div>', 'pw-merchant-api-system');
            }
        }
        echo '<form class="ptms-manual-offer-delete" method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
        echo '<input type="hidden" name="action" value="ptms_delete_offer_manual">';
        wp_nonce_field('ptms_delete_offer_manual');
        echo '<label for="ptms-manual-offer-id"><strong>'
            . esc_html__('Remove deleted product remaining on Google', 'pw-merchant-api-system')
            . '</strong><span>'
            . esc_html__('Automatic removal is active. Use this backup only for a previously deleted product that still appears on Google.', 'pw-merchant-api-system')
            . '</span></label>';
        echo '<div class="ptms-inline-actions"><input id="ptms-manual-offer-id" name="offer_id" type="text" maxlength="150" required placeholder="'
            . esc_attr__('Offer ID or SKU', 'pw-merchant-api-system') . '">';
        echo '<button class="ptms-btn danger" type="submit">'
            . esc_html__('Delete from Google', 'pw-merchant-api-system') . '</button></div></form>';
        if (empty($problem_data['has_cache'])) {
            echo __('<p class="ptms-empty">Google issue data has not been received yet. Use the “Update from Google” button.</p>', 'pw-merchant-api-system');
        } elseif (!$problem_rows) {
            echo __('<div class="ptms-alert success"><strong>There are no products blocked by Google.</strong> There are no products that are disapproved or awaiting review in the last received Merchant data.</div>', 'pw-merchant-api-system');
        } else {
            echo '<div class="ptms-alert warning"><strong>' . (int) ($problem_data['total'] ?? ($problem_summary['with_issues'] ?? count($problem_rows))) . __('Problematic product found.</strong>A maximum of 20 records are displayed on this page.</div>', 'pw-merchant-api-system');
            echo __('<table class="ptms-table"><thead><tr><th>Product</th><th>Offer ID</th><th>Status</th><th>Google description</th></tr></thead><tbody>', 'pw-merchant-api-system');
            foreach ($problem_rows as $product) {
                $pstatus = sanitize_key((string) ($product['status'] ?? 'pending'));
                $status_text = $pstatus === 'disapproved' ? __('Not confirmed', 'pw-merchant-api-system') : __('Pending review', 'pw-merchant-api-system');
                $issues = (array) ($product['issues'] ?? array());
                $issue_text = $issues ? (string) ($issues[0]['title'] ?? __('Google product compatibility issue', 'pw-merchant-api-system')) : __('Google is checking product status.', 'pw-merchant-api-system');
                $issue_detail_html = '';
                if ($issues) {
                    $detail_parts = array();
                    foreach ($issues as $issue_row) {
                        if (!is_array($issue_row)) { continue; }
                        $detail_title = sanitize_text_field((string) ($issue_row['title'] ?? __('Product suitability issue', 'pw-merchant-api-system')));
                        $detail_explanation = sanitize_text_field((string) ($issue_row['explanation'] ?? __('Google has reported an availability or data quality issue for this product.', 'pw-merchant-api-system')));
                        $detail_solution = sanitize_text_field((string) ($issue_row['solution'] ?? __('Check the product information, complete the required fields and save the product. PW Feed automatically pushes changes to Google.', 'pw-merchant-api-system')));
                        $detail_parts[] = '<div class="ptms-issue-detail-item"><strong>' . esc_html($detail_title) . '</strong><p><b>Neden?</b> ' . esc_html($detail_explanation) . __('</p><p><b>How to solve?</b>', 'pw-merchant-api-system') . esc_html($detail_solution) . '</p>' . $this->merchant_issue_scope_html((array) $issue_row) . '</div>';
                    }
                    if ($detail_parts) {
                        $issue_detail_html = __('<details class="ptms-issue-details"><summary>Issue Detail</summary><div class="ptms-issue-details-body">', 'pw-merchant-api-system') . implode('', $detail_parts) . '</div></details>';
                    }
                }
                $offer_id = sanitize_text_field((string) ($product['offer_id'] ?? ''));
                $product_id = 0;
                if ($offer_id !== '' && function_exists('wc_get_product_id_by_sku')) {
                    $product_id = (int) wc_get_product_id_by_sku($offer_id);
                }
                if ($product_id <= 0 && $offer_id !== '' && ctype_digit($offer_id)) {
                    $candidate_id = absint($offer_id);
                    $candidate = function_exists('wc_get_product') ? wc_get_product($candidate_id) : null;
                    if ($candidate) { $product_id = $candidate_id; }
                }
                $edit_url = $product_id > 0 ? get_edit_post_link($product_id, '') : '';
                $product_title = (string) ($product['title'] ?? __('Product name could not be retrieved', 'pw-merchant-api-system'));
                $title_html = $edit_url
                    ? '<a class="ptms-product-edit-link" href="' . esc_url($edit_url) . '"><strong>' . esc_html($product_title) . __('</strong><span>Edit product →</span></a>', 'pw-merchant-api-system')
                    : '<strong>' . esc_html($product_title) . __('</strong><small class="ptms-product-missing">WooCommerce record not found.</small>', 'pw-merchant-api-system');
                echo '<tr><td>' . $title_html . '</td><td>' . esc_html($offer_id !== '' ? $offer_id : '—') . '</td><td><span class="ptms-pill ' . ($pstatus === 'disapproved' ? 'danger' : 'warn') . '">' . esc_html($status_text) . '</span></td><td><div class="ptms-issue-summary-text">' . esc_html($issue_text) . '</div>' . $issue_detail_html . '</td></tr>';
            }
            echo '</tbody></table>';
            $problem_total_pages = (int) ($problem_data['total_pages'] ?? 1);
            if ($problem_total_pages > 1) {
                $problem_base = str_replace('999999999', '%#%', add_query_arg(array(
                    'page' => $this->slug . '-urun-gonderimi',
                    'ptms_problem_page' => 999999999,
                ), admin_url('admin.php'))) . '#ptms-problem-products';
                echo __('<nav class="ptms-compact-pagination" aria-label="Problem product pages">', 'pw-merchant-api-system');
                echo wp_kses_post(paginate_links(array(
                    'base' => $problem_base,
                    'format' => '',
                    'current' => (int) ($problem_data['page'] ?? 1),
                    'total' => $problem_total_pages,
                    'prev_text' => '‹',
                    'next_text' => '›',
                    'type' => 'plain',
                    'mid_size' => 2,
                    'end_size' => 1,
                )));
                echo '</nav>';
            }
        }
        echo '</div>';

        $show_sync_control = ($status === 'running')
            || (in_array($status, array('paused', 'stopped'), true) && $remaining > 0)
            || $failed_queue > 0
            || $remaining > 0;

        if ($show_sync_control) {
            echo __('<div class="ptms-card ptms-worker-dashboard ptms-contextual-control"><div class="ptms-card-head"><div><span class="ptms-eyebrow">Bulk sending</span><h2>Synchronization control center</h2>', 'pw-merchant-api-system');
            if ($status === 'running') {
                echo __('<p class="ptms-muted">Bulk submission continues in the background. If you want, you can pause it temporarily or stop it completely.</p>', 'pw-merchant-api-system');
            } elseif (in_array($status, array('paused', 'stopped'), true) && $remaining > 0) {
                echo __('<p class="ptms-muted"><strong>The previous batch submission was not completed.</strong>', 'pw-merchant-api-system') . number_format_i18n($remaining) . __('The product has not yet been processed. You can continue where you left off or cancel the temporary process and start fresh.</p>', 'pw-merchant-api-system');
            } elseif ($failed > 0) {
                echo '<p class="ptms-muted">' . number_format_i18n($failed) . __('The product could not be sent. If there are failed products registered, you can only resend them.</p>', 'pw-merchant-api-system');
            } else {
                echo __('<p class="ptms-muted">There are pending temporary batch submission operations.</p>', 'pw-merchant-api-system');
            }
            echo '</div></div><div class="ptms-worker-actions">';
            if ($status === 'running') {
                $this->sync_control_form('pause', 'Duraklat', 'secondary');
                $this->sync_control_form('stop', __('Stop', 'pw-merchant-api-system'), 'danger');
            } elseif (in_array($status, array('paused', 'stopped'), true) && $remaining > 0) {
                $this->sync_control_form('resume', __('Continue Where You Left Off', 'pw-merchant-api-system'), '');
            }
            if ($failed_queue > 0) {
                $this->sync_control_form('retry', __('Retry Failed to Send', 'pw-merchant-api-system'), 'secondary');
            }
            if ($remaining > 0 || $failed_queue > 0 || in_array($status, array('paused', 'stopped'), true)) {
                $this->sync_control_form('clear', __('Cancel Transaction', 'pw-merchant-api-system'), 'secondary', true);
            }
            echo __('</div><p class="ptms-worker-guidance"><strong>Information:</strong> These operations only manage the temporary PW Feed submission process. Existing products in Google Merchant will not be deleted.</p></div>', 'pw-merchant-api-system');
        }

        echo '<div id="ptms-full-sync" class="ptms-card ptms-primary-action ptms-anchor-target">';
        echo '<div><span class="ptms-eyebrow">' . ($has_synced ? __('Smart sync', 'pw-merchant-api-system') : __('initial setup', 'pw-merchant-api-system')) . '</span>';
        echo '<h2>' . ($has_synced ? __('Schedule full synchronization', 'pw-merchant-api-system') : __('Start first sync', 'pw-merchant-api-system')) . '</h2>';
        echo '<p>' . ($has_synced ? __('Normally only new and replacement items are automatically shipped. If needed, you can resynchronize the entire catalog now or during low traffic hours.', 'pw-merchant-api-system') : __('All your live products are delivered via secure background processing now or at the time you choose.', 'pw-merchant-api-system')) . '</p></div>';
        if (!empty($schedule['timestamp'])) {
            echo __('<div class="ptms-alert success"><strong>Synchronization scheduled:</strong>', 'pw-merchant-api-system') . esc_html(wp_date('d.m.Y H:i', (int)$schedule['timestamp'])) . '</div>';
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_cancel_schedule">'; wp_nonce_field('ptms_cancel_schedule'); echo __('<button class="ptms-btn secondary" type="submit">Cancel Plan</button></form>', 'pw-merchant-api-system');
        } else {
            echo '<form class="ptms-scheduler-form" method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_schedule_sync">';
            wp_nonce_field('ptms_schedule_sync');
            echo __('<div class="ptms-field"><label for="ptms_start_mode">Start time</label><select id="ptms_start_mode" name="start_mode"><option value="now">Start now</option><option value="30m">In 30 minutes</option><option value="1h">In 1 hour</option><option value="3h">3 hours after</option><option value="night">Start at 02:00 (recommended)</option><option value="custom">Specific date and time</option></select></div>', 'pw-merchant-api-system');
            echo __('<div class="ptms-field"><label for="ptms_custom_time">Date and time</label><input id="ptms_custom_time" name="custom_time" type="datetime-local"><small>Only used in the “Specific date and time” option.</small></div>', 'pw-merchant-api-system');
            echo '<button class="ptms-btn large" type="submit" ' . (($status === 'running' || $queue_blocked) ? 'disabled' : '') . __('>Start / Schedule Sync</button></form>', 'pw-merchant-api-system');
        }
        echo '</div>';

        echo __('<div class="ptms-card ptms-auto-sync-card"><div><span class="ptms-eyebrow">Live protection</span><h2>Automatic Synchronization</h2><p>Your product is automatically sent to Google when the price, stock, title, description or image changes.</p></div>', 'pw-merchant-api-system');
        echo '<div class="ptms-auto-state"><span class="ptms-toggle-dot ' . ($auto ? 'on' : 'off') . '"></span><strong>' . ($auto ? __('Open', 'pw-merchant-api-system') : __('Closed', 'pw-merchant-api-system')) . '</strong></div>';
        if (!$auto) {
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_sync_toggle">';
            wp_nonce_field('ptms_sync_toggle');
            echo __('<input type="hidden" name="enabled" value="1"><button class="ptms-btn secondary" type="submit">Turn on Auto Sync</button></form>', 'pw-merchant-api-system');
        } else {
            echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_sync_toggle">';
            wp_nonce_field('ptms_sync_toggle');
            echo '<input type="hidden" name="enabled" value="0"><button class="ptms-btn danger" type="submit">' . esc_html__('Disable Automatic Synchronization', 'pw-merchant-api-system') . '</button></form>';
        }
        echo '</div>';

        echo __('<details id="ptms-technical-details" class="ptms-card ptms-technical-details ptms-anchor-target"><summary><span><strong>Technical status and developer logs</strong><small>View worker, scheduler and technical transaction logs as needed.</small></span></summary><div class="ptms-technical-details-body">', 'pw-merchant-api-system');
        echo '<div class="ptms-technical-columns"><section><h3>' . esc_html__('System checks', 'pw-merchant-api-system') . '</h3><div class="ptms-preflight-list">';
        foreach ((array) ($preflight['checks'] ?? array()) as $check) {
            $ok = !empty($check['ok']);
            echo '<div class="ptms-preflight-item ' . ($ok ? 'is-ok' : 'is-warning') . '"><strong>' . esc_html((string) ($check['label'] ?? __('Check', 'pw-merchant-api-system'))) . '</strong><span>' . esc_html((string) ($check['message'] ?? '')) . '</span></div>';
        }
        echo '</div></section><section><h3>' . esc_html__('Worker activity', 'pw-merchant-api-system') . '</h3>';
        if (!$logs) {
            echo __('<p class="ptms-empty">There are no technical worker records yet.</p>', 'pw-merchant-api-system');
        } else {
            echo '<div class="ptms-log-list ptms-technical-log-list">';
            foreach ($logs as $log) {
                $level = sanitize_key((string) ($log['level'] ?? 'info'));
                $time = !empty($log['time']) ? wp_date('d.m.Y H:i:s', (int) $log['time']) : '—';
                $message = (string) ($log['message'] ?? '');
                $detail = (string) ($log['detail'] ?? '');
                echo '<div class="ptms-log-row is-' . esc_attr($level) . '"><span class="ptms-log-dot"></span><div><strong>' . esc_html($message) . '</strong>' . ($detail !== '' ? '<p class="ptms-log-detail">' . esc_html($detail) . '</p>' : '') . '<small>' . esc_html($time) . '</small></div></div>';
            }
            echo '</div>';
        }
        echo '</section></div></div></details>';

        if (isset($_GET['ptms_msg'])) echo '<div class="ptms-alert success">' . esc_html(sanitize_text_field(wp_unslash($_GET['ptms_msg']))) . '</div>';
        $err = (string) get_option('ptms_last_sync_error', '');
        if ($err !== '') {
            $err = PTMS_Core::friendly_sync_error($err);
            echo '<div class="ptms-alert danger"><strong>' . esc_html__('Last error:', 'pw-merchant-api-system') . '</strong> ' . esc_html($err) . '</div>';
        }
        $this->footer();
    }

    private function sync_control_form($command, $label, $class = '', $confirm = false) {
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"' . ($confirm ? __('onsubmit="return confirm(\'Cancel temporary bulk shipping? Existing products in Google Merchant will not be deleted. You can start a new bulk sending later.\');"', 'pw-merchant-api-system') : '') . '>';
        echo '<input type="hidden" name="action" value="ptms_sync_control"><input type="hidden" name="command" value="' . esc_attr($command) . '">';
        wp_nonce_field('ptms_sync_control');
        echo '<button class="ptms-btn ' . esc_attr($class) . '" type="submit">' . esc_html($label) . '</button></form>';
    }

    public function ajax_sync_status() {
        if (!current_user_can('manage_options')) wp_send_json_error(array('message' => __('Unauthorized transaction.', 'pw-merchant-api-system')), 403);
        check_ajax_referer('ptms_sync_status', 'nonce');
        wp_send_json_success(PTMS_Core::sync_status());
    }

    public function ajax_check_google_connection_status() {
        if (!current_user_can('manage_options')) wp_send_json_error(array('message' => __('Unauthorized transaction.', 'pw-merchant-api-system')), 403);
        check_ajax_referer('ptms_check_google_connection_status', 'nonce');

        $result = PTMS_Core::refresh_connection_status(true);
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()), 502);
        }
        if ((string)($result['connection_state'] ?? '') === 'active') {
            wp_send_json_success(array('status' => 'connected'));
        }
        if ((string)($result['connection_state'] ?? '') === 'reconnect_required') {
            wp_send_json_success(array('status' => 'reconnect_required'));
        }
        if (!empty($result['accounts'])) {
            wp_send_json_success(array('status' => 'ready'));
        }
        if (!empty($result['connection_found'])) {
            wp_send_json_success(array('status' => 'preparing'));
        }
        wp_send_json_success(array('status' => 'not_connected'));
    }

    public function sync_test() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_sync_test');

        $id = absint($_POST['product_id'] ?? 0);
        if ($id < 1 || get_post_type($id) !== 'product') {
            $msg = __('Error: No valid product selected.', 'pw-merchant-api-system');
            wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
            exit;
        }

        $scope = PTMS_License_Client_V2::require_scope('merchant.send', true);
        if (is_wp_error($scope)) {
            PTMS_Core::add_sync_log(
                'warning',
                __('Single product shipment was not initiated due to license security check.', 'pw-merchant-api-system'),
                array(
                    'product_id' => $id,
                    'scope' => 'merchant.send',
                    'error_code' => $scope->get_error_code(),
                )
            );
            $msg = 'Hata: ' . $scope->get_error_message();
            wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
            exit;
        }

        $res = PTMS_Core::sync_products(array($id));
        $msg = is_wp_error($res)
            ? 'Hata: ' . $res->get_error_message()
            : __('The product was sent to Google Merchant Center with secure license verification.', 'pw-merchant-api-system');

        wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
        exit;
    }
    public function sync_all() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_sync_all');

        $scope = PTMS_License_Client_V2::require_scope('merchant.bulk_send', true);
        if (is_wp_error($scope)) {
            PTMS_Core::add_sync_log('warning', __('Bulk submission was not initiated due to license security check.', 'pw-merchant-api-system'), array(
                'scope' => 'merchant.bulk_send',
                'error_code' => $scope->get_error_code(),
            ));
            wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode('Hata: ' . $scope->get_error_message()), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
            exit;
        }

        $count = PTMS_Core::start_full_sync('manual');
        $msg = is_wp_error($count) ? 'Hata: ' . $count->get_error_message() : $count . __('Secure synchronization for the product is started in the background.', 'pw-merchant-api-system');
        wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
        exit;
    }
    public function sync_toggle(){if(!current_user_can('manage_options'))wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system'));check_admin_referer('ptms_sync_toggle');update_option('ptms_auto_sync_enabled',!empty($_POST['enabled']),false);wp_safe_redirect(admin_url('admin.php?page='.$this->slug.'-urun-gonderimi'));exit;}
    public function sync_control() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_sync_control');

        $command = sanitize_key((string) ($_POST['command'] ?? ''));

        // Güvenlik ve kurtarma komutları lisans kontrolü olmadan da her zaman kullanılabilir.
        // Yalnız Google'a yeniden gönderim başlatan komutlar yetki kapısından geçer.
        if ($command === 'retry') {
            $scope = PTMS_License_Client_V2::require_scope('merchant.bulk_send', true);
            if (is_wp_error($scope)) {
                PTMS_Core::add_sync_log('warning', __('Reshipment of failed products was not initiated due to license security check.', 'pw-merchant-api-system'), array(
                    'scope' => 'merchant.bulk_send',
                    'error_code' => $scope->get_error_code(),
                ));
                $msg = 'Hata: ' . $scope->get_error_message();
                wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
                exit;
            }
        } elseif ($command === 'resume') {
            $scope = PTMS_License_Client_V2::require_scope('merchant.sync', true);
            if (is_wp_error($scope)) {
                PTMS_Core::add_sync_log('warning', __('Worker continuation process was not started due to license security check.', 'pw-merchant-api-system'), array(
                    'scope' => 'merchant.sync',
                    'error_code' => $scope->get_error_code(),
                ));
                $msg = 'Hata: ' . $scope->get_error_message();
                wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
                exit;
            }
        }

        $msg = PTMS_Core::control_sync($command);
        wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
        exit;
    }

    public function schedule_sync() {
        if (!current_user_can('manage_options')) wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system'));
        check_admin_referer('ptms_schedule_sync');
        $mode = sanitize_key((string) ($_POST['start_mode'] ?? 'now'));

        $scope = PTMS_License_Client_V2::require_scope('merchant.bulk_send', true);
        if (is_wp_error($scope)) {
            PTMS_Core::add_sync_log('warning', __('Scheduled bulk sync was not created due to license security check.', 'pw-merchant-api-system'), array(
                'scope' => 'merchant.bulk_send',
                'error_code' => $scope->get_error_code(),
            ));
            wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode('Hata: ' . $scope->get_error_message()), admin_url('admin.php?page=' . $this->slug . '-urun-gonderimi')));
            exit;
        }

        $now = time();
        if ($mode === 'now') {
            $count = PTMS_Core::start_full_sync('manual');
            $msg = is_wp_error($count) ? 'Hata: ' . $count->get_error_message() : $count . __('Synchronization for the product is started in the background.', 'pw-merchant-api-system');
        } else {
            if ($mode === '30m') $timestamp = $now + 30 * MINUTE_IN_SECONDS;
            elseif ($mode === '1h') $timestamp = $now + HOUR_IN_SECONDS;
            elseif ($mode === '3h') $timestamp = $now + 3 * HOUR_IN_SECONDS;
            elseif ($mode === 'night') {
                $tz = wp_timezone();
                $current = new DateTimeImmutable('now', $tz);
                $night = $current->setTime(2, 0, 0);
                if ($night <= $current) $night = $night->modify('+1 day');
                $timestamp = $night->getTimestamp();
            } else {
                $raw = sanitize_text_field((string) ($_POST['custom_time'] ?? ''));
                try { $dt = new DateTimeImmutable($raw, wp_timezone()); $timestamp = $dt->getTimestamp(); }
                catch (Exception $e) { $timestamp = 0; }
                if ($timestamp <= $now) wp_die(__('Please select a date and time in the future.', 'pw-merchant-api-system'));
            }
            PTMS_Core::schedule_full_sync($timestamp, $mode);
            $msg = 'Senkronizasyon ' . wp_date('d.m.Y H:i', $timestamp) . __('was planned for.', 'pw-merchant-api-system');
        }
        wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode($msg), admin_url('admin.php?page='.$this->slug.'-urun-gonderimi'))); exit;
    }

    public function cancel_schedule() {
        if (!current_user_can('manage_options')) wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system'));
        check_admin_referer('ptms_cancel_schedule');
        PTMS_Core::cancel_scheduled_sync();
        wp_safe_redirect(add_query_arg('ptms_msg', rawurlencode('Planlanan senkronizasyon iptal edildi.'), admin_url('admin.php?page='.$this->slug.'-urun-gonderimi'))); exit;
    }

    public function license() {
        $license = PTMS_License::display_data();
        $status = PTMS_License::status();
        $last_error = (string) get_option('ptms_license_last_error', '');
        $checked = (int) get_option('ptms_license_checked_at', 0);
        $notice = sanitize_key((string) ($_GET['ptms_license'] ?? ''));
        $this->header(__('License', 'pw-merchant-api-system'), __('Activate the license code generated in the PW Trust system and monitor the license status.', 'pw-merchant-api-system'));
        if ($notice === 'activated') echo __('<div class="ptms-alert success"><strong>License activated.</strong> Domain and installation match verified.</div>', 'pw-merchant-api-system');
        if ($notice === 'refreshed') echo '<div class="ptms-alert success"><strong>' . esc_html__('License status refreshed.', 'pw-merchant-api-system') . '</strong></div>';
        if ($notice === 'error' && $last_error !== '') echo __('<div class="ptms-alert danger"><strong>The operation could not be completed:</strong>', 'pw-merchant-api-system') . esc_html($last_error) . '</div>';
        echo __('<div class="ptms-grid two"><div class="ptms-card"><h2>Activate license code</h2><p>Enter the license code generated from the PW Trust panel. The code is sent during verification and is not stored explicitly in the WordPress database.</p>', 'pw-merchant-api-system');
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_activate_license">'; wp_nonce_field('ptms_activate_license');
        echo __('<p><label for="ptms-license-code"><strong>License code</strong></label><input id="ptms-license-code" class="widefat" type="text" name="license_code" maxlength="24" autocomplete="off" spellcheck="false" placeholder="PWM-XXXX-XXXX-XXXX-XXXX" required></p><button class="ptms-btn" type="submit">Activate License</button></form></div>', 'pw-merchant-api-system');
        $license_type = sanitize_key((string)($license['type'] ?? ''));
        $license_type_label = $license_type === 'pro'
            ? 'Pro'
            : ($license_type === 'demo'
                ? 'Demo'
                : ($license_type === 'unlicensed' ? __('Unlicensed version', 'pw-merchant-api-system') : '—'));
        $days_left_label = isset($license['days_left']) ? max(0, (int) $license['days_left']) . __('day', 'pw-merchant-api-system') : '—';
        echo '<div class="ptms-card"><h2>'.esc_html__('Current license status', 'pw-merchant-api-system').'</h2><dl class="ptms-details"><dt>'.esc_html__('Status', 'pw-merchant-api-system').'</dt><dd><strong>' . esc_html(PTMS_License::label()) . '</strong></dd><dt>'.esc_html__('License type', 'pw-merchant-api-system').'</dt><dd>' . esc_html($license_type_label) . '</dd><dt>'.esc_html__('Start', 'pw-merchant-api-system').'</dt><dd>' . esc_html((string) ($license['starts_at'] ?? '—')) . '</dd><dt>'.esc_html__('End', 'pw-merchant-api-system').'</dt><dd>' . esc_html((string) ($license['expires_at'] ?? '—')) . '</dd><dt>'.esc_html__('Remaining time', 'pw-merchant-api-system').'</dt><dd><strong>' . esc_html($days_left_label) . '</strong></dd>';
        if($license_type==='demo'){
            echo '<dt>'.esc_html__('Product rights', 'pw-merchant-api-system').'</dt><dd><strong>'
                .esc_html(max(0,(int)($license['remaining']??0)).' / '.max(0,(int)($license['product_limit']??20)))
                .'</strong><br><small>'.esc_html__('Connecting a Google account does not use product rights. Updating or resending the same product is not counted again.', 'pw-merchant-api-system').'</small></dd>';
        }
        echo '<dt>'.esc_html__('Installation ID', 'pw-merchant-api-system').'</dt><dd><code>' . esc_html((string) get_option('ptms_trust_installation_id', __('Not yet created', 'pw-merchant-api-system'))) . '</code></dd><dt>'.esc_html__('Last check', 'pw-merchant-api-system').'</dt><dd>' . ($checked ? esc_html(wp_date('d.m.Y H:i', $checked)) : esc_html__('Not checked yet', 'pw-merchant-api-system')) . '</dd></dl>';
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_refresh_license">'; wp_nonce_field('ptms_refresh_license'); echo '<button class="ptms-btn secondary" type="submit">' . esc_html__('Refresh license status', 'pw-merchant-api-system') . '</button></form></div></div>';
        echo '<div class="ptms-alert ' . ($status === 'pro' ? 'success' : ($status === 'demo' ? 'warn' : 'danger')) . __('"><strong>Domain name:</strong>', 'pw-merchant-api-system') . esc_html(PTMS_Core::domain()) . '</div>';
        $this->footer();
    }

    public function delete_offer_manual() {
        if (!current_user_can('manage_options')) wp_die(__('You are not authorized for this operation.', 'pw-merchant-api-system'));
        check_admin_referer('ptms_delete_offer_manual');
        $offer_id = sanitize_text_field(wp_unslash($_POST['offer_id'] ?? ''));
        $result = PTMS_Core::delete_offer_now($offer_id);
        $args = array('page' => $this->slug . '-urun-gonderimi', 'ptms_delete_offer' => is_wp_error($result) ? 'error' : 'success');
        if (is_wp_error($result)) $args['ptms_delete_message'] = rawurlencode($result->get_error_message());
        wp_safe_redirect(add_query_arg($args, admin_url('admin.php')) . '#ptms-problem-products');
        exit;
    }

    public function activate_license() {
        if (!current_user_can('manage_options')) wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system'));
        check_admin_referer('ptms_activate_license');
        $code = isset($_POST['license_code']) ? sanitize_text_field(wp_unslash($_POST['license_code'])) : '';
        $result = PTMS_License::activate($code);
        $state = is_wp_error($result) ? 'error' : 'activated';
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-lisans&ptms_license=' . $state)); exit;
    }

    public function refresh_license() {
        if (!current_user_can('manage_options')) wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system'));
        check_admin_referer('ptms_refresh_license');
        $result = PTMS_License::refresh(true);
        $state = is_wp_error($result) ? 'error' : 'refreshed';
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-lisans&ptms_license=' . $state)); exit;
    }

    public function settings() {
        $merchant_id = (string) get_option('ptms_merchant_id', '');
        $this->header(__('Settings', 'pw-merchant-api-system'), __('Manage PW Feed behavior.', 'pw-merchant-api-system'));
        $this->docs('Temel eklenti tercihlerini saklar.', 'WordPress Options API.', __('The saved settings are kept only in this WordPress installation.', 'pw-merchant-api-system'), 'https://support.google.com/merchants/');
        echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '"><input type="hidden" name="action" value="ptms_save_settings">'; wp_nonce_field('ptms_save_settings'); echo __('<div class="ptms-card"><div class="ptms-field"><label for="ptms_merchant_id">Merchant Center ID</label><input id="ptms_merchant_id" name="merchant_id" type="text" inputmode="numeric" value="', 'pw-merchant-api-system') . esc_attr($merchant_id) . __('" placeholder="Automatically determined after connection"><small>It is not mandatory for the normal user; it is intended to be read automatically after connection.</small></div><button class="ptms-btn" type="submit">Save settings</button></div></form>', 'pw-merchant-api-system');
        $this->footer();
    }

    public function save_settings() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_save_settings');
        $merchant_id = isset($_POST['merchant_id']) ? preg_replace('/\D+/', '', (string) wp_unslash($_POST['merchant_id'])) : '';
        update_option('ptms_merchant_id', $merchant_id, false);
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-ayarlar&saved=1')); exit;
    }


    public function select_merchant() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_select_merchant');
        $merchant_id = isset($_POST['merchant_account']) ? preg_replace('/\D+/', '', (string) wp_unslash($_POST['merchant_account'])) : '';
        $accounts = get_option('ptms_pending_merchant_accounts', array());
        $selected = null;
        if (is_array($accounts)) {
            foreach ($accounts as $account) {
                if (is_array($account) && preg_replace('/\D+/', '', (string)($account['accountId'] ?? '')) === $merchant_id) { $selected = $account; break; }
            }
        }
        if (!$selected) { wp_die(__('The selected Merchant Center account could not be verified.', 'pw-merchant-api-system')); }
        update_option('ptms_merchant_id', $merchant_id, false);
        update_option('ptms_merchant_name', sanitize_text_field((string)($selected['accountName'] ?? '')), false);
        $accepted = PTMS_Core::accept_verified_connection(
            sanitize_text_field((string)get_option('ptms_pending_connection_id', '')),
            sanitize_email((string)get_option('ptms_pending_google_email', '')),
            is_array($accounts) ? $accounts : array(),
            $merchant_id
        );
        if (!$accepted) { wp_die(__('The verified Google connection could not be activated. Please recheck the connection.', 'pw-merchant-api-system')); }
        delete_option('ptms_pending_merchant_accounts');
        delete_option('ptms_pending_google_email');
        delete_option('ptms_pending_connection_id');
        delete_option('ptms_connect_error');
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-google&connected=1')); exit;
    }

    public function check_google_connection() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_check_google_connection');

        $result = PTMS_Core::refresh_connection_status(true);
        if (is_wp_error($result)) {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'error' => true,
                'message' => $result->get_error_message(),
            ), 5 * MINUTE_IN_SECONDS);
        } elseif ((string)($result['connection_state'] ?? '') === 'active') {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'success' => true,
                'message' => __('The link to Google and Merchant Center is active and verified on the server.', 'pw-merchant-api-system'),
            ), 5 * MINUTE_IN_SECONDS);
        } elseif ((string)($result['connection_state'] ?? '') === 'reconnect_required') {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'error' => true,
                'message' => __('Google Merchant connection must be re-established.', 'pw-merchant-api-system'),
            ), 5 * MINUTE_IN_SECONDS);
        } elseif (!empty($result['accounts'])) {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'success' => true,
                'message' => __('Google link verified. Select the Merchant Center account to manage.', 'pw-merchant-api-system'),
            ), 5 * MINUTE_IN_SECONDS);
        } elseif (!empty($result['connection_found'])) {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'message' => __('Google connection received but Merchant API preparation is not completed yet. Check again in a few minutes.', 'pw-merchant-api-system'),
            ), 5 * MINUTE_IN_SECONDS);
        } else {
            set_transient('ptms_connect_check_' . get_current_user_id(), array(
                'message' => __('No completed Google links found yet. Complete the “Connect with Google” process first.', 'pw-merchant-api-system'),
            ), 5 * MINUTE_IN_SECONDS);
        }

        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-google'));
        exit;
    }

    public function disconnect() {
        if (!current_user_can('manage_options')) { wp_die(__('Unauthorized transaction.', 'pw-merchant-api-system')); }
        check_admin_referer('ptms_disconnect');
        delete_option('ptms_google_connected'); delete_option('ptms_google_email'); delete_option('ptms_merchant_id'); delete_option('ptms_merchant_name'); delete_option('ptms_connection_id'); delete_option('ptms_pending_merchant_accounts'); delete_option('ptms_pending_google_email'); delete_option('ptms_pending_connection_id'); delete_option('ptms_connection_reconnect_required'); delete_option('ptms_connection_status_message'); delete_option('ptms_previous_connection_id'); update_option('ptms_connection_state', 'not_connected', false); delete_transient('ptms_verified_connection_status');
        wp_safe_redirect(admin_url('admin.php?page=' . $this->slug . '-google&disconnected=1')); exit;
    }

    public function connection_reconnect_notice() {
        if (!current_user_can('manage_options') || !(bool)get_option('ptms_connection_reconnect_required', false)) return;
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ($screen && strpos((string)$screen->id, 'pw-merchant-api-system') === false) return;
        $url = admin_url('admin.php?page=' . $this->slug . '-google');
        echo '<div class="notice notice-error"><p><strong>'
            . esc_html__('PW Feed: Google connection must be re-established.', 'pw-merchant-api-system')
            . '</strong> '
            . esc_html__('Pending product updates are protected and will continue automatically after reconnection.', 'pw-merchant-api-system')
            . ' <a href="' . esc_url($url) . '">'
            . esc_html__('Open Google connection', 'pw-merchant-api-system')
            . '</a></p></div>';
    }

    public function help() {
        $this->header(__('Help', 'pw-merchant-api-system'), __('PW Feed user guide, features and frequently asked questions.', 'pw-merchant-api-system'));

        echo '<div class="ptms-help-hero">';
        echo __('<div><span class="ptms-help-kicker">PW Feed Help Center</span><h2>Manage your Google Merchant processes more easily</h2><p>PW Feed; It was developed to send and update your WooCommerce products to Google Merchant Center, understand problems and track the general status of your Merchant account.</p></div>', 'pw-merchant-api-system');
        echo '<div class="ptms-help-actions"><a class="ptms-btn primary" href="' . esc_url(PTMS_SUPPORT_URL) . '" target="_blank" rel="noopener">' . esc_html__('Support', 'pw-merchant-api-system') . '</a><a class="ptms-btn secondary" href="' . esc_url(PTMS_LICENSE_PANEL_URL) . '" target="_blank" rel="noopener">' . esc_html__('Get License', 'pw-merchant-api-system') . '</a></div>';
        echo '</div>';

        echo '<div class="ptms-help-layout">';
        echo __('<aside class="ptms-help-toc"><strong>On this page</strong><a href="#ptms-help-what is it">What is PW Feed?</a><a href="#ptms-help-isleyis">How does it work?</a><a href="#ptms-help-bolumler">Sections</a><a href="#ptms-help-benefits">Benefits</a><a href="#ptms-help-important">Important information</a><a href="#ptms-help-faq">Frequently asked questions</a></aside>', 'pw-merchant-api-system');
        echo '<main class="ptms-help-content">';

        echo __('<section id="ptms-help-what is" class="ptms-card ptms-help-section"><h2>What is PW Feed?</h2><p>PW Feed is a professional Merchant management system developed to send, update, control and manage products on WooCommerce-based e-commerce sites to Google Merchant Center.</p><p>PW Feed is not a classic XML feed plugin that only sends products. It manages the product flow between WooCommerce and Google Merchant Center, automatically sends new products, detects product changes, removes deleted products from Google, and presents the problems reported by Google to the user with Turkish explanations.</p><p>The main purpose of the system is; To facilitate Google Merchant processes, improve product quality, reduce errors, create a reliable bridge between WooCommerce and Google Merchant Center and offer the user a more professional Merchant management experience.</p><div class="ptms-help-highlight"><strong>Basic approach:</strong> The user manages his products on WooCommerce; PW Feed performs the necessary Google Merchant operations in the background.</div></section>', 'pw-merchant-api-system');

        echo __('<section id="ptms-help-isleyis" class="ptms-card ptms-help-section"><h2>How does PW Feed work?</h2>', 'pw-merchant-api-system');
        echo '<div class="ptms-help-feature-grid">';
        echo __('<article><h3>First synchronization</h3><p>During the initial setup, the published products in your WooCommerce store are sent to Google Merchant Center in secure groups. Large catalogs are not processed all at once; It is fragmented in the background to reduce server load.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>New products</h3><p>When you add a new product to your WooCommerce store, PW Feed automatically detects the product and sends it to Google without waiting for the cron time.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Product updates</h3><p>When price, stock, title, description, image, brand, category and product features change, only the relevant product is updated. The user also does not need to press the sync button.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Deleting a product</h3><p>The product deleted from WooCommerce is automatically removed from Google Merchant Center. It may take a few minutes for Google to display this process on the panel.</p></article>', 'pw-merchant-api-system');
        echo '</div>';
        echo __('<h3>Auto-detected major changes</h3><ul class="ptms-help-list"><li>Product title and description</li><li>Regular and discounted price</li><li>Stock quantity and availability</li><li>Main and additional product images</li><li>Brand, GTIN/EAN, MPN and SKU</li><li>Category, variation and product features</li></ul>', 'pw-merchant-api-system');
        echo __('<div class="ptms-help-note"><strong>Google processing time:</strong> PW Feed sends the request to Google; Google processes the product separately in its own system. While price and stock changes usually appear quickly, visual and availability evaluations can take longer.</div></section>', 'pw-merchant-api-system');

        echo __('<section id="ptms-help-sections" class="ptms-card ptms-help-section"><h2>PW Feed sections</h2>', 'pw-merchant-api-system');
        $modules = array(
            array(__('1. Preparation Wizard', 'pw-merchant-api-system'), __('It prepares users who do not have technical knowledge about Merchant step by step. Google Merchant account, required site pages, connection and first pre-synchronization checks are explained here.', 'pw-merchant-api-system')),
            array(__('2. Google Link', 'pw-merchant-api-system'), __('A connection is established with the Google account, Merchant accounts are read and the Merchant account to be used is selected. OAuth and access information are managed securely through the PW Connect infrastructure.', 'pw-merchant-api-system')),
            array(__('3. Site Analysis', 'pw-merchant-api-system'), __('SSL controls important site elements for Google Merchant, such as site accessibility, communication, shipping, returns, privacy, distance selling and product pages.', 'pw-merchant-api-system')),
            array(__('4. Product Analysis', 'pw-merchant-api-system'), __('Examines basic product data such as title, description, price, stock, image, brand, GTIN, MPN, SKU, category and product link.', 'pw-merchant-api-system')),
            array(__('5. Product Shipping', 'pw-merchant-api-system'), __('WooCommerce shows the number of products, products added to Google and not included in Google, problematic products, live product transactions, and last batch transaction status. You do not need to continuously initiate transactions in daily use, except for the first batch submission.', 'pw-merchant-api-system')),
            array('6. Sorun Merkezi', __('Explains Google\'s product and account problems in Turkish. The cause of the issue, affected area, post scope, proposed solution, product edit link, and Google help link are shown here.', 'pw-merchant-api-system')),
            array(__('7. Merchant Health', 'pw-merchant-api-system'), __('Monitors overall Merchant health by leveraging Google link, Merchant link, product quality, brand, GTIN/MPN, price, stock, image and policy statuses.', 'pw-merchant-api-system')),
            array(__('8. API Usage', 'pw-merchant-api-system'), __('It shows API calls made by PW Feed, successful and unsuccessful transactions, products processed, and usage history.', 'pw-merchant-api-system')),
            array(__('9. Diaries', 'pw-merchant-api-system'), __('It lists events such as new product submission, product update, stock change, image update, deletion and retry with user-friendly Turkish explanations.', 'pw-merchant-api-system')),
            array(__('10. Settings', 'pw-merchant-api-system'), __('Automatic synchronization, bulk delivery scheduling, night operation and other working preferences are managed.', 'pw-merchant-api-system')),
            array(__('11. Help', 'pw-merchant-api-system'), __('The purpose of the system, operating logic, sections, important usage information and frequently asked questions are found on this page.', 'pw-merchant-api-system')),
            array(__('12. License', 'pw-merchant-api-system'), __('Demo or Pro license status, remaining time and license activations are managed here.', 'pw-merchant-api-system'))
        );
        echo '<div class="ptms-help-module-list">';
        foreach ($modules as $module) { echo '<article><h3>' . esc_html($module[0]) . '</h3><p>' . esc_html($module[1]) . '</p></article>'; }
        echo '</div></section>';

        echo __('<section id="ptms-help-benefits" class="ptms-card ptms-help-section"><h2>PW Feed benefits</h2><div class="ptms-help-feature-grid">', 'pw-merchant-api-system');
        echo __('<article><h3>Reduces the need for technical knowledge</h3><p>Technical processes such as Merchant API, data source, Offer ID, queue, Worker and retry are managed on behalf of the user.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Reduces daily workload</h3><p>New products, price, stock, content and visual changes are automatically transmitted to Google.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Uses the server in a controlled manner</h3><p>Batch operations are divided into small groups; product registration, cart and checkout flow do not wait for a Google response.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Makes problems understandable</h3><p>Google\'s technical messages are translated into Turkish and the user is presented with reason and solution information.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Helps prevent data loss</h3><p>In case of temporary connection problems, transactions are taken to the retry system and product information is preserved.</p></article>', 'pw-merchant-api-system');
        echo __('<article><h3>Demo and Pro in one package</h3><p>No separate ZIP required for Demo and Pro. When the license code is entered, the current installation, settings and products are preserved and switched to Pro.</p></article>', 'pw-merchant-api-system');
        echo '</div></section>';

        echo __('<section id="ptms-help-important" class="ptms-card ptms-help-section"><h2>Important usage information</h2><ul class="ptms-help-list"><li>It may take a few minutes for Google to display added, updated or deleted products in Merchant Center.</li><li>It may take longer because image changes are scanned separately by Google.</li><li>You have to start the same process repeatedly. It is not necessary.</li><li>It is recommended not to interfere with synchronization processes as much as possible.</li><li>In order not to tire your website, bulk transactions are carried out at regular intervals and in secure groups.</li><li>Successful submission indicates that the product data has reached Google; Google approval is evaluated separately.</li><li>Account level warnings and product level issues are evaluated separately.</li><li>Normal Free listings and Free local listings for physical stores are different features.</li></ul></section>', 'pw-merchant-api-system');

        echo __('<section id="ptms-help-faq" class="ptms-card ptms-help-section"><h2>Frequently asked questions</h2><div class="ptms-faq">', 'pw-merchant-api-system');
        $faqs = array(
            array('PW Feed XML feed eklentisi midir?', __('No. PW Feed is a Merchant management system that works via Google Merchant API.', 'pw-merchant-api-system')),
            array(__('Can I send all my products for the first installation?', 'pw-merchant-api-system'), __('Yes. With an active licence, you can send all published products in bulk from the First Synchronization section.', 'pw-merchant-api-system')),
            array(__('What should I do when I add a new product?', 'pw-merchant-api-system'), __('Just publish the product on WooCommerce. PW Feed automatically submits the product to Google.', 'pw-merchant-api-system')),
            array(__('Should I resync if price or stock changes?', 'pw-merchant-api-system'), __('No. Price and stock changes are automatically detected and only the relevant product is updated.', 'pw-merchant-api-system')),
            array(__('If I delete the product from my website, will it remain on Google?', 'pw-merchant-api-system'), __('No. The current PW Feed automatically removes the deleted product from Google Merchant Center.', 'pw-merchant-api-system')),
            array(__('Why didn\'t the change on Google appear immediately?', 'pw-merchant-api-system'), __('PW Feed sends the request; Google processes the product separately in its own system. Price and stock may appear shortly, images and some availability reviews may take longer.', 'pw-merchant-api-system')),
            array(__('What does the Google accepted request message mean?', 'pw-merchant-api-system'), __('Indicates that the request was received by Google. Processing and approval of the product may also take time.', 'pw-merchant-api-system')),
            array(__('Has the product sent successfully been approved?', 'pw-merchant-api-system'), __('No. Successful submission indicates that the data has reached Google; Google then evaluates the product for policy and data quality.', 'pw-merchant-api-system')),
            array(__('How do I edit problematic products?', 'pw-merchant-api-system'), __('Click the name of the problem product or the Edit Product link. When you save the product, PW Feed automatically sends the changes.', 'pw-merchant-api-system')),
            array(__('What is the local inventory data missing alert?', 'pw-merchant-api-system'), __('This warning relates to physical store sales. However, if you are selling online, you do not need to organize the products one by one; Free local listings and Local inventory ads in Merchant Center can be turned off.', 'pw-merchant-api-system')),
            array(__('If I turn off free local listings, will regular free listings turn off?', 'pw-merchant-api-system'), __('No. Free listings are for online products, Free local listings are for physical store inventory.', 'pw-merchant-api-system')),
            array(__('Should I keep the page open during bulk posting?', 'pw-merchant-api-system'), __('No. The process continues in the background.', 'pw-merchant-api-system')),
            array(__('Will Pause or Stop harm my Google account?', 'pw-merchant-api-system'), __('No. These transactions govern PW Feed\'s native transaction flow only; It does not harm existing products or policies in the Google account.', 'pw-merchant-api-system')),
            array(__('Does clearing the queue delete products from Google?', 'pw-merchant-api-system'), __('No. Queue purging only affects local and temporary transaction records.', 'pw-merchant-api-system')),
            array(__('If the same product is sent again, will there be a duplicate?', 'pw-merchant-api-system'), __('No. When the same Offer ID is used, Google updates the existing product.', 'pw-merchant-api-system')),
            array(__('How to ship non-SKU products?', 'pw-merchant-api-system'), __('If there is an SKU, the SKU is used as the Offer ID; If there is no SKU, the WooCommerce product ID is used.', 'pw-merchant-api-system')),
            array(__('How does the Demo license work?', 'pw-merchant-api-system'), __('The Demo license is valid for 30 days and 20 unique products. Connecting a Google account does not consume quota; updating or resending the same product is not counted again.', 'pw-merchant-api-system')),
            array(__('Do I need to re-send my products when I upgrade to the Pro version?', 'pw-merchant-api-system'), __('No. When you activate the license code, your existing settings, connection and product data are preserved.', 'pw-merchant-api-system')),
            array(__('How many domains can the license be used on?', 'pw-merchant-api-system'), __('Each license is valid for one domain and one installation.', 'pw-merchant-api-system')),
            array(__('When does the license period start?', 'pw-merchant-api-system'), __('The 365-day Pro license period starts on the first successful activation, not when the license code is generated.', 'pw-merchant-api-system')),
            array(__('Will the data be deleted when the license expires?', 'pw-merchant-api-system'), __('No. Your settings and records are preserved; When the license is renewed, the system can continue where it left off.', 'pw-merchant-api-system'))
        );
        foreach ($faqs as $faq) { echo '<details><summary>' . esc_html($faq[0]) . '</summary><p>' . esc_html($faq[1]) . '</p></details>'; }
        echo '</div></section>';

        echo '<section class="ptms-card ptms-help-section ptms-help-contact"><h2>' . esc_html__('Support and license', 'pw-merchant-api-system') . '</h2><p>' . esc_html__('Use PW Feed channels for technical support and licensing.', 'pw-merchant-api-system') . '</p><div class="ptms-help-actions"><a class="ptms-btn primary" href="' . esc_url(PTMS_SUPPORT_URL) . '" target="_blank" rel="noopener">' . esc_html__('Support', 'pw-merchant-api-system') . '</a><a class="ptms-btn secondary" href="' . esc_url(PTMS_LICENSE_PANEL_URL) . '" target="_blank" rel="noopener">' . esc_html__('Get License', 'pw-merchant-api-system') . '</a></div></section>';

        echo '</main></div>';
        $this->footer();
    }
}
