<?php

if (!defined('ABSPATH')) exit;

require_once __DIR__ . '/../../../providers/WebsiteProvider.php';
require_once __DIR__ . '/../../../services/search-console/SearchConsoleService.php';
require_once __DIR__ . '/../../../services/search-console/WebsiteStatusChecker.php';
require_once __DIR__ . '/../../../helpers/license-helper.php';
require_once __DIR__ . '/search-console/AddWebsiteSection.php';
require_once __DIR__ . '/search-console/VerificationSection.php';
require_once __DIR__ . '/search-console/VerifiedSection.php';
require_once __DIR__ . '/search-console/PerformanceSection.php';

class ContaiSearchConsolePanel
{
    private ContaiWebsiteProvider $websiteProvider;
    private ContaiSearchConsoleService $service;
    private ContaiWebsiteStatusChecker $statusChecker;

    public function __construct()
    {
        $this->websiteProvider = new ContaiWebsiteProvider();
        $this->service         = new ContaiSearchConsoleService(null, $this->websiteProvider);
        $this->statusChecker   = new ContaiWebsiteStatusChecker();
    }

    public function render(): void
    {
        $this->enqueueAssets();

        if (!contai_has_active_license()) {
            $this->renderLicenseRequired();
            return;
        }

        $status = $this->websiteProvider->initializeWebsiteStatus();

        ?>
        <div class="contai-settings-panel contai-panel-search-console">
            <?php $this->renderMessage(); ?>
            <?php $this->renderContent($status); ?>
        </div>
        <?php
    }

    private function renderMessage(): void
    {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Display-only, no data modification.
        if (!isset($_GET['contai_sc_message']) || !isset($_GET['contai_sc_type'])) {
            return;
        }

        $message = urldecode(sanitize_text_field(wp_unslash($_GET['contai_sc_message'])));
        $type = sanitize_key(wp_unslash($_GET['contai_sc_type']));
        $trace_id = isset($_GET['contai_sc_trace_id']) ? sanitize_text_field(wp_unslash(urldecode($_GET['contai_sc_trace_id']))) : null;
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        $class = $type === 'success' ? 'notice-success' : 'notice-error';

        ?>
        <div class="notice <?php echo esc_attr($class); ?> is-dismissible">
            <p>
                <?php echo esc_html($message); ?>
                <?php if (!empty($trace_id)): ?>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=contai-logs&trace_id=' . urlencode($trace_id))); ?>">[Ref: <?php echo esc_html($trace_id); ?>]</a>
                <?php endif; ?>
            </p>
        </div>
        <?php
    }

    private function renderContent(array $status): void
    {
        $userProfile = $this->websiteProvider->getUserProfile();

        if (!$userProfile) {
            $this->renderUserNotConfigured();
            return;
        }

        if ($status['status'] === 'error') {
            $this->renderError($status['message'] ?? 'Unknown error');
            return;
        }

        if ($status['status'] === 'not_found') {
            $this->renderWebsiteNotFound();
            return;
        }

        $config = $status['config'];

        if ($this->statusChecker->isVerified($config)) {
            $verifiedSection = new ContaiSearchConsoleVerifiedSection($config);
            $verifiedSection->render();

            // Only a verified property has anything for Google to report on
            // (SCP-04) — same gate as the section above, not a second one.
            $performanceSection = new ContaiSearchConsolePerformanceSection();
            $performanceSection->render();
            $this->enqueuePerformanceAssets();
            return;
        }

        $hasSearchConsoleData = !empty($config['file_name']);

        if (!$hasSearchConsoleData) {
            $addSection = new ContaiSearchConsoleAddWebsiteSection(
                $this->websiteProvider->getSiteUrl(),
                $this->websiteProvider->getSitemapUrls()
            );
            $addSection->render();
            return;
        }

        $verificationSection = new ContaiSearchConsoleVerificationSection(
            $config,
            $this->service->verificationFileExists()
        );
        $verificationSection->render();
    }

    private function renderWebsiteNotFound(): void
    {
        ?>
        <div class="contai-settings-section">
            <div class="contai-info-box contai-info-box-warning">
                <span class="dashicons dashicons-warning"></span>
                <div>
                    <p><strong><?php esc_html_e('Website Not Registered', '1platform-content-ai'); ?></strong></p>
                    <p>
                        <?php esc_html_e('Your website has not been registered with Content AI yet. Please go to API Keys & Licenses and reactivate your license to register the website.', '1platform-content-ai'); ?>
                    </p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=contai-licenses')); ?>" class="button button-primary">
                        <?php esc_html_e('Go to API Keys & Licenses', '1platform-content-ai'); ?>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }

    private function renderUserNotConfigured(): void
    {
        ?>
        <div class="contai-settings-section">
            <div class="contai-info-box contai-info-box-error">
                <span class="dashicons dashicons-warning"></span>
                <div>
                    <p><strong><?php esc_html_e('User Profile Not Configured', '1platform-content-ai'); ?></strong></p>
                    <p>
                        <?php esc_html_e('Please configure your Content AI account in the API Keys & Licenses section first.', '1platform-content-ai'); ?>
                    </p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=contai-licenses')); ?>" class="button button-primary">
                        <?php esc_html_e('Go to API Keys & Licenses', '1platform-content-ai'); ?>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }

    private function renderError(string $message): void
    {
        ?>
        <div class="contai-settings-section">
            <div class="contai-info-box contai-info-box-error">
                <span class="dashicons dashicons-warning"></span>
                <div>
                    <p><strong><?php esc_html_e('Error', '1platform-content-ai'); ?></strong></p>
                    <p><?php echo esc_html($message); ?></p>
                </div>
            </div>
        </div>
        <?php
    }

    private function renderLicenseRequired(): void
    {
        ?>
        <div class="contai-settings-section">
            <div class="contai-info-box contai-info-box-warning">
                <span class="dashicons dashicons-lock"></span>
                <div>
                    <p><strong><?php esc_html_e('Active License Required', '1platform-content-ai'); ?></strong></p>
                    <p>
                        <?php esc_html_e('You need an active license to use the Search Console integration. Please activate your license to access this feature.', '1platform-content-ai'); ?>
                    </p>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=contai-licenses')); ?>" class="button button-primary">
                        <?php esc_html_e('Activate License', '1platform-content-ai'); ?>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }

    private function enqueueAssets(): void
    {
        $baseDir = dirname(__DIR__);
        $jsFile = $baseDir . '/assets/js/search-console.js';
        $jsUrl = plugins_url('assets/js/search-console.js', $baseDir . '/dummy.php');

        wp_enqueue_script(
            'contai-search-console',
            $jsUrl,
            ['jquery'],
            file_exists($jsFile) ? filemtime($jsFile) : '1.0.0',
            true
        );
    }

    /**
     * Performance panel script + its REST config (SCP-04). Enqueued only when
     * the section is actually rendered, so an unverified site never ships a
     * script that would immediately 409.
     */
    private function enqueuePerformanceAssets(): void
    {
        $baseDir = dirname(__DIR__);
        $jsFile = $baseDir . '/assets/js/search-console-performance.js';
        $jsUrl = plugins_url('assets/js/search-console-performance.js', $baseDir . '/dummy.php');

        wp_enqueue_script(
            'contai-search-console-performance',
            $jsUrl,
            [],
            file_exists($jsFile) ? filemtime($jsFile) : '1.0.0',
            true
        );

        wp_localize_script(
            'contai-search-console-performance',
            'contaiScPerformance',
            [
                'restUrl'     => rest_url('contai/v1/search-console/performance'),
                'sitemapsUrl' => rest_url('contai/v1/search-console/sitemaps'),
                'nonce'       => wp_create_nonce('wp_rest'),
                'i18n'        => [
                    'loading'     => __('Loading performance data…', '1platform-content-ai'),
                    'error'       => __('Could not load performance data.', '1platform-content-ai'),
                    'quota'       => __('Too many requests right now. Try again in a few minutes.', '1platform-content-ai'),
                    'notVerified' => __('This website is not verified in Search Console yet.', '1platform-content-ai'),
                    'colIndexed'  => __('Indexed / read', '1platform-content-ai'),
                    'colIssues'   => __('Issues', '1platform-content-ai'),
                    'errors'      => __('errors', '1platform-content-ai'),
                    'warnings'    => __('warnings', '1platform-content-ai'),
                    'noIssues'    => __('No issues', '1platform-content-ai'),
                    'keyHeader'   => [
                        'queries'   => __('Query', '1platform-content-ai'),
                        'pages'     => __('Page', '1platform-content-ai'),
                        'countries' => __('Country', '1platform-content-ai'),
                    ],
                ],
            ]
        );
    }
}
