<?php
/**
 * Site Verification Module
 *
 * Allows users to add verification meta tags for webmaster tools
 * (Google Search Console, Yandex Webmaster, Bing Webmaster)
 * plus a custom meta tag field for any other service.
 *
 * This is a FREE feature — no PRO license required.
 *
 * @package    SEO_Fury
 * @subpackage Includes
 * @since      0.3.0
 */

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

class SEO_Fury_Site_Verification {

    /**
     * Singleton instance.
     *
     * @var SEO_Fury_Site_Verification|null
     */
    private static $instance = null;

    /**
     * Settings group name.
     *
     * @var string
     */
    private $settings_group = 'seo_fury_verification_group';

    /**
     * Verification services definition.
     *
     * @var array
     */
    private $services = array();

    // Option keys for custom meta tag.
    private $opt_custom_name    = 'seo_fury_verify_custom_name';
    private $opt_custom_content = 'seo_fury_verify_custom_content';

    // =========================================================================
    // Singleton
    // =========================================================================

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

    private function __construct() {
        $this->define_services();
        add_action( 'admin_init', array( $this, 'register_settings' ) );
        add_action( 'wp_head', array( $this, 'output_verification_meta' ), 1 );
    }

    /**
     * Define supported verification services.
     * Single source of truth for service metadata.
     */
    private function define_services() {
        $this->services = array(
            'google' => array(
                'label'       => __( 'Google Search Console', 'seo-fury' ),
                'meta_name'   => 'google-site-verification',
                'option'      => 'seo_fury_verify_google',
                'placeholder' => __( 'Enter code or paste full meta tag', 'seo-fury' ),
                'help_url'    => 'https://search.google.com/search-console',
                'description' => __( 'Get your code: Google Search Console > Settings > Ownership verification > HTML tag.', 'seo-fury' ),
                'icon'        => 'dashicons-google',
                'icon_color'  => '#4285F4',
            ),
            'yandex' => array(
                'label'       => __( 'Yandex Webmaster', 'seo-fury' ),
                'meta_name'   => 'yandex-verification',
                'option'      => 'seo_fury_verify_yandex',
                'placeholder' => __( 'Enter code or paste full meta tag', 'seo-fury' ),
                'help_url'    => 'https://webmaster.yandex.com/',
                'description' => __( 'Get your code: Yandex Webmaster > Add site > Verification > Meta tag.', 'seo-fury' ),
                'icon'        => 'dashicons-admin-site-alt3',
                'icon_color'  => '#FC3F1D',
            ),
            'bing' => array(
                'label'       => __( 'Bing Webmaster', 'seo-fury' ),
                'meta_name'   => 'msvalidate.01',
                'option'      => 'seo_fury_verify_bing',
                'placeholder' => __( 'Enter code or paste full meta tag', 'seo-fury' ),
                'help_url'    => 'https://www.bing.com/webmasters/',
                'description' => __( 'Get your code: Bing Webmaster Tools > Add site > HTML Meta Tag method.', 'seo-fury' ),
                'icon'        => 'dashicons-admin-site',
                'icon_color'  => '#00809D',
            ),
        );
    }

    /**
     * Get services array.
     *
     * @return array
     */
    public function get_services() {
        return $this->services;
    }

    // =========================================================================
    // Settings Registration
    // =========================================================================

    public function register_settings() {

        // Register each service verification code.
        foreach ( $this->services as $key => $service ) {
            register_setting( $this->settings_group, $service['option'], array(
                'type'              => 'string',
                'sanitize_callback' => array( $this, 'sanitize_verification_code' ),
                'default'           => '',
            ) );
        }

        // Register custom meta tag fields.
        register_setting( $this->settings_group, $this->opt_custom_name, array(
            'type'              => 'string',
            'sanitize_callback' => array( $this, 'sanitize_custom_meta_name' ),
            'default'           => '',
        ) );

        register_setting( $this->settings_group, $this->opt_custom_content, array(
            'type'              => 'string',
            'sanitize_callback' => array( $this, 'sanitize_verification_code' ),
            'default'           => '',
        ) );

        // Section.
        add_settings_section(
            'seo_fury_verification_section',
            __( 'Webmaster Verification Codes', 'seo-fury' ),
            array( $this, 'render_section_description' ),
            $this->settings_group
        );

        // Fields for each service.
        foreach ( $this->services as $key => $service ) {
            add_settings_field(
                $service['option'],
                $service['label'],
                array( $this, 'render_field' ),
                $this->settings_group,
                'seo_fury_verification_section',
                array( 'service' => $service )
            );
        }

        // Custom meta tag section.
        add_settings_section(
            'seo_fury_verification_custom_section',
            __( 'Custom Verification Meta Tag', 'seo-fury' ),
            array( $this, 'render_custom_section_description' ),
            $this->settings_group
        );

        add_settings_field(
            $this->opt_custom_name,
            __( 'Meta Tag Name', 'seo-fury' ),
            array( $this, 'render_custom_name_field' ),
            $this->settings_group,
            'seo_fury_verification_custom_section'
        );

        add_settings_field(
            $this->opt_custom_content,
            __( 'Meta Tag Content', 'seo-fury' ),
            array( $this, 'render_custom_content_field' ),
            $this->settings_group,
            'seo_fury_verification_custom_section'
        );
    }

    // =========================================================================
    // Sanitization
    // =========================================================================

    /**
     * Sanitize a verification code.
     *
     * Smart sanitization: if user pastes a full <meta> tag,
     * automatically extracts the value from content="...".
     *
     * @param string $value Raw input.
     * @return string Sanitized verification code.
     */
    public function sanitize_verification_code( $value ) {
        $value = trim( $value );

        if ( empty( $value ) ) {
            return '';
        }

        // If user pasted a full meta tag, extract content attribute.
        if ( preg_match( '/content=["\']([^"\']+)["\']/i', $value, $matches ) ) {
            $value = $matches[1];
        }

        // Strip any remaining HTML tags.
        $value = wp_strip_all_tags( $value );
        $value = sanitize_text_field( $value );

        return $value;
    }

    /**
     * Sanitize the custom meta tag name.
     *
     * Allows letters, numbers, hyphens, underscores, dots, colons.
     *
     * @param string $value Raw input.
     * @return string Sanitized meta name.
     */
    public function sanitize_custom_meta_name( $value ) {
        $value = trim( $value );

        if ( empty( $value ) ) {
            return '';
        }

        // If user pasted a full meta tag, extract name attribute.
        if ( preg_match( '/name=["\']([^"\']+)["\']/i', $value, $matches ) ) {
            $value = $matches[1];
        }

        // Allow only safe characters for meta name attribute.
        $value = preg_replace( '/[^a-zA-Z0-9_\-.:]+/', '', $value );

        return $value;
    }

    // =========================================================================
    // Section Descriptions
    // =========================================================================

    public function render_section_description() {
        echo '<p>' . esc_html__( 'Enter the verification codes provided by webmaster tools to prove ownership of your website. You can paste either the code itself or the full meta tag — the code will be extracted automatically.', 'seo-fury' ) . '</p>';
    }

    public function render_custom_section_description() {
        echo '<p>' . esc_html__( 'Add a custom verification meta tag for any service not listed above (e.g., Pinterest, Baidu, Facebook, Norton Safe Web).', 'seo-fury' ) . '</p>';
    }

    // =========================================================================
    // Field Renderers
    // =========================================================================

    /**
     * Render a service verification code field.
     *
     * @param array $args Arguments containing service definition.
     */
    public function render_field( $args ) {
        $service = $args['service'];
        $value   = get_option( $service['option'], '' );

        // Color dot indicator.
        echo '<div style="display: flex; align-items: center; gap: 8px;">';
        echo '<span style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: ' . esc_attr( $service['icon_color'] ) . ';"></span>';
        printf(
            '<input type="text" id="%1$s" name="%1$s" value="%2$s" class="regular-text" placeholder="%3$s" />',
            esc_attr( $service['option'] ),
            esc_attr( $value ),
            esc_attr( $service['placeholder'] )
        );

        // Status indicator.
        if ( ! empty( $value ) ) {
            echo '<span style="color: #16A34A; font-weight: 500;"><span class="dashicons dashicons-yes-alt" style="font-size: 16px; width: 16px; height: 16px; vertical-align: middle;"></span> ' . esc_html__( 'Active', 'seo-fury' ) . '</span>';
        }

        echo '</div>';

        echo '<p class="description">';
        echo esc_html( $service['description'] ) . ' ';
        echo '<a href="' . esc_url( $service['help_url'] ) . '" target="_blank" rel="noopener">';
        echo esc_html__( 'Open service', 'seo-fury' ) . ' &rarr;</a>';
        echo '</p>';
    }

    /**
     * Render the custom meta tag name field.
     */
    public function render_custom_name_field() {
        $value = get_option( $this->opt_custom_name, '' );
        printf(
            '<input type="text" id="%1$s" name="%1$s" value="%2$s" class="regular-text" placeholder="%3$s" />',
            esc_attr( $this->opt_custom_name ),
            esc_attr( $value ),
            esc_attr__( 'e.g., p:domain_verify or facebook-domain-verification', 'seo-fury' )
        );
        echo '<p class="description">' . esc_html__( 'The value of the "name" attribute in the meta tag. Example: for Pinterest enter "p:domain_verify", for Facebook enter "facebook-domain-verification".', 'seo-fury' ) . '</p>';
    }

    /**
     * Render the custom meta tag content field.
     */
    public function render_custom_content_field() {
        $value = get_option( $this->opt_custom_content, '' );
        printf(
            '<input type="text" id="%1$s" name="%1$s" value="%2$s" class="regular-text" placeholder="%3$s" />',
            esc_attr( $this->opt_custom_content ),
            esc_attr( $value ),
            esc_attr__( 'Enter verification code or paste full meta tag', 'seo-fury' )
        );
        echo '<p class="description">' . esc_html__( 'The verification code (content attribute value). You can paste the full meta tag — the code will be extracted automatically.', 'seo-fury' ) . '</p>';
    }

    // =========================================================================
    // Frontend: Output Verification Meta Tags (wp_head, priority 1)
    // =========================================================================

    /**
     * Output verification meta tags into <head>.
     */
    public function output_verification_meta() {
        $brand  = function_exists( 'seo_fury_get_brand_name' ) ? seo_fury_get_brand_name() : 'SEO Fury';
        $output = '';

        // Standard services.
        foreach ( $this->services as $key => $service ) {
            $code = get_option( $service['option'], '' );
            if ( ! empty( $code ) ) {
                $output .= '<meta name="' . esc_attr( $service['meta_name'] ) . '" content="' . esc_attr( $code ) . '" />' . "\n";
            }
        }

        // Custom meta tag.
        $custom_name    = get_option( $this->opt_custom_name, '' );
        $custom_content = get_option( $this->opt_custom_content, '' );
        if ( ! empty( $custom_name ) && ! empty( $custom_content ) ) {
            $output .= '<meta name="' . esc_attr( $custom_name ) . '" content="' . esc_attr( $custom_content ) . '" />' . "\n";
        }

        if ( ! empty( $output ) ) {
            echo "\n<!-- " . esc_html( $brand ) . " -->\n" . wp_kses( $output, array( 'meta' => array( 'name' => true, 'content' => true ) ) ) . "<!-- /" . esc_html( $brand ) . " -->\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
    }

    // =========================================================================
    // Admin Tab Render
    // =========================================================================

    public function render_admin_tab() {

        // --- Active Verifications Status ---
        $active_count = 0;
        foreach ( $this->services as $key => $service ) {
            if ( ! empty( get_option( $service['option'], '' ) ) ) {
                $active_count++;
            }
        }
        $custom_name    = get_option( $this->opt_custom_name, '' );
        $custom_content = get_option( $this->opt_custom_content, '' );
        if ( ! empty( $custom_name ) && ! empty( $custom_content ) ) {
            $active_count++;
        }

        if ( $active_count > 0 ) {
            echo '<div class="seo-card" style="margin-top: 20px; padding: 20px; background: var(--sf-success-light,#F0FDF4); border: 1px solid var(--sf-gray-200,#BBF7D0); border-radius: 8px;">';
            echo '<h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">';
            echo '<span class="dashicons dashicons-yes-alt" style="color: #16A34A;"></span>';
            /* translators: %d: number of active verifications */
            echo esc_html( sprintf( __( 'Active Verifications: %d', 'seo-fury' ), $active_count ) );
            echo '</h3>';
            echo '<ul style="margin: 0; padding-left: 20px; line-height: 1.8; color: var(--sf-gray-700,#334155);">';

            foreach ( $this->services as $key => $service ) {
                $code = get_option( $service['option'], '' );
                if ( ! empty( $code ) ) {
                    echo '<li>';
                    echo '<span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ' . esc_attr( $service['icon_color'] ) . '; margin-right: 6px;"></span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo '<strong>' . esc_html( $service['label'] ) . '</strong>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo ' — <code>&lt;meta name="' . esc_attr( $service['meta_name'] ) . '" content="' . esc_attr( substr( $code, 0, 12 ) ) . '..."&gt;</code>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    echo '</li>';
                }
            }

            if ( ! empty( $custom_name ) && ! empty( $custom_content ) ) {
                echo '<li>';
                echo '<span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: #6B7280; margin-right: 6px;"></span>';
                echo '<strong>' . esc_html__( 'Custom', 'seo-fury' ) . '</strong>';
                echo ' — <code>&lt;meta name="' . esc_attr( $custom_name ) . '" content="' . esc_attr( substr( $custom_content, 0, 12 ) ) . '..."&gt;</code>';
                echo '</li>';
            }

            echo '</ul>';
            echo '</div>';
        }

        // --- Info Card: How Verification Works ---
        echo '<div class="seo-card" style="margin-top: 16px; padding: 20px; background: var(--sf-gray-50,#F8FAFC); border: 1px solid var(--sf-gray-200,#E2E8F0); border-radius: 8px;">';
        echo '<h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">';
        echo '<span class="dashicons dashicons-info-outline" style="color: #2563EB;"></span>';
        echo esc_html__( 'How Site Verification Works', 'seo-fury' );
        echo '</h3>';

        echo '<ol style="margin: 0; padding-left: 20px; line-height: 1.8; color: var(--sf-gray-700,#334155);">';
        echo '<li>' . esc_html__( 'Open the webmaster tool you want to verify with (Google, Yandex, Bing, etc.).', 'seo-fury' ) . '</li>';
        echo '<li>' . esc_html__( 'Add your site and choose the "HTML meta tag" verification method.', 'seo-fury' ) . '</li>';
        echo '<li>' . esc_html__( 'Copy the verification code (or the entire meta tag) and paste it into the corresponding field above.', 'seo-fury' ) . '</li>';
        echo '<li>' . esc_html__( 'Save changes. The meta tag will be automatically added to every page of your site.', 'seo-fury' ) . '</li>';
        echo '<li>' . esc_html__( 'Go back to the webmaster tool and click "Verify".', 'seo-fury' ) . '</li>';
        echo '</ol>';
        echo '</div>';

        // --- Settings Form (collapsible) ---
        echo '<div class="seo-card" style="margin-top:25px;padding:20px;">';
        echo '<details>';
        echo '<summary style="cursor:pointer;font-weight:600;font-size:13px;color:var(--sf-gray-900,#23282d);">';
        echo '<span class="dashicons dashicons-admin-generic" style="vertical-align:middle;margin-right:4px;font-size:16px;width:16px;height:16px;"></span>';
        esc_html_e( 'Verification Settings', 'seo-fury' );
        echo '</summary>';
        echo '<div style="margin-top:12px;">';

        echo '<form method="post" action="options.php">';
        settings_fields( $this->settings_group );
        do_settings_sections( $this->settings_group );
        submit_button();
        echo '</form>';

        echo '</div>';
        echo '</details>';
        echo '</div>';

        // --- Common Services Reference Card ---
        echo '<div class="seo-card" style="margin-top: 16px; padding: 20px; background: var(--sf-warning-light,#FFFBEB); border: 1px solid var(--sf-gray-200,#FDE68A); border-radius: 8px;">';
        echo '<h3 style="margin-top: 0; display: flex; align-items: center; gap: 8px;">';
        echo '<span class="dashicons dashicons-lightbulb" style="color: #D97706;"></span>';
        echo esc_html__( 'Custom Meta Tag Examples', 'seo-fury' );
        echo '</h3>';
        echo '<p style="margin-top: 0; color: var(--sf-gray-700,#334155);">' . esc_html__( 'Use the custom field above for any service not listed. Common examples:', 'seo-fury' ) . '</p>';
        echo '<ul style="margin: 0; padding-left: 20px; line-height: 1.8; color: var(--sf-gray-700,#334155);">';
        echo '<li><strong>Pinterest</strong> — ' . esc_html__( 'Meta name:', 'seo-fury' ) . ' <code>p:domain_verify</code></li>';
        echo '<li><strong>Baidu</strong> — ' . esc_html__( 'Meta name:', 'seo-fury' ) . ' <code>baidu-site-verification</code></li>';
        echo '<li><strong>Facebook</strong> — ' . esc_html__( 'Meta name:', 'seo-fury' ) . ' <code>facebook-domain-verification</code></li>';
        echo '<li><strong>Norton Safe Web</strong> — ' . esc_html__( 'Meta name:', 'seo-fury' ) . ' <code>norton-safeweb-site-verification</code></li>';
        echo '<li><strong>Naver</strong> — ' . esc_html__( 'Meta name:', 'seo-fury' ) . ' <code>naver-site-verification</code></li>';
        echo '</ul>';
        echo '</div>';
    }
}
