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

class SEO_Fury_Post_Meta_Basic {

    public function __construct() {
    }

    public function render_basic_tab($post, $meta_data, $preview_data) {
        ?>
        <div class="seo-fury-tab-content active" id="tab-basic">
            <?php $sf_seo_score = get_post_meta($post->ID, '_seo_fury_seo_score', true); ?>
            <div class="seo-fury-section seo-fury-overall">
                <div class="seo-fury-overall-card">
                    <div class="seo-fury-overall-gauge seo-fury-score--warn" id="seo-fury-overall-gauge">
                        <span class="seo-fury-overall-value" id="seo-fury-overall-score"><?php echo esc_html($sf_seo_score !== '' ? (int) $sf_seo_score : 0); ?></span>
                        <span class="seo-fury-overall-max">/100</span>
                    </div>
                    <div class="seo-fury-overall-info">
                        <strong><?php esc_html_e('Overall SEO Score', 'seo-fury'); ?></strong>
                        <span class="description"><?php esc_html_e('Combined score from on-page SEO, readability, and extra checks. Shown as a column on your posts list.', 'seo-fury'); ?></span>
                    </div>
                </div>
            </div>
            <input type="hidden" id="seo_fury_seo_score" name="seo_fury_seo_score" value="<?php echo esc_attr($sf_seo_score !== '' ? (int) $sf_seo_score : ''); ?>">

            <div id="seo-fury-duplicate-warning" class="seo-fury-dup-warning" style="display:none;"></div>

            <?php
            $sf_gsc_url  = get_permalink($post->ID);
            $sf_show_gsc = $sf_gsc_url && in_array($post->post_status, array('publish', 'future', 'private'), true);
            if ($sf_show_gsc) :
            ?>
            <div class="seo-fury-section seo-fury-gsc-snippet" id="seo-fury-gsc-snippet"
                 data-url="<?php echo esc_attr($sf_gsc_url); ?>"
                 data-nonce="<?php echo esc_attr(wp_create_nonce('seo_fury_gsc_post_stats')); ?>"
                 style="display:none;">
                <h4><?php esc_html_e('Search Console (last 28 days)', 'seo-fury'); ?></h4>
                <div id="seo-fury-gsc-snippet-body"></div>
            </div>
            <script>
            (function($){
                var $p = $('#seo-fury-gsc-snippet'); if (!$p.length) { return; }
                $.post(ajaxurl, { action: 'seo_fury_gsc_post_stats', nonce: $p.data('nonce'), url: $p.data('url') }, function(r){
                    if (!r || !r.success || !r.data || !r.data.connected) { return; }
                    var d = r.data;
                    var fmt = function(n){ return (parseInt(n, 10) || 0).toLocaleString(); };
                    var html = '<div class="seo-fury-gsc-grid">' +
                        '<div><span class="v">' + fmt(d.clicks) + '</span><span class="l"><?php echo esc_js(__('Clicks', 'seo-fury')); ?></span></div>' +
                        '<div><span class="v">' + fmt(d.impressions) + '</span><span class="l"><?php echo esc_js(__('Impressions', 'seo-fury')); ?></span></div>' +
                        '<div><span class="v">' + ((d.ctr * 100).toFixed(1)) + '%</span><span class="l"><?php echo esc_js(__('CTR', 'seo-fury')); ?></span></div>' +
                        '<div><span class="v">' + (d.position ? d.position.toFixed(1) : '—') + '</span><span class="l"><?php echo esc_js(__('Position', 'seo-fury')); ?></span></div>' +
                        '</div>';
                    if (!d.has_data) { html += '<p class="description" style="margin:8px 0 0;"><?php echo esc_js(__('No Search Console data for this URL yet.', 'seo-fury')); ?></p>'; }
                    $('#seo-fury-gsc-snippet-body').html(html);
                    $p.show();
                });
            })(jQuery);
            </script>
            <?php endif; ?>

            <div class="seo-fury-section">
                <h4><?php esc_html_e('Google Preview', 'seo-fury'); ?></h4>
                <div class="google-preview">
                    <div class="preview-url"><?php echo esc_html(wp_parse_url($preview_data['current_url'], PHP_URL_HOST)); ?></div>
                    <div class="preview-title"><?php echo esc_html($preview_data['preview_title']); ?></div>
                    <div class="preview-description"><?php echo esc_html($preview_data['preview_description']); ?></div>
                    <div>
                        <button type="button" class="button button-primary seo-fury-edit-snippet" style="margin-top: 12px;">
                            <span class="dashicons dashicons-edit" style="margin-top: 3px;"></span>
                            <?php esc_html_e('Edit Snippet', 'seo-fury'); ?>
                        </button>
                    </div>
                </div>
            </div>

            <div class="seo-fury-section">
                <h4><?php esc_html_e('Focus Keywords', 'seo-fury'); ?></h4>
                <div class="seo-fury-field">
                    <input type="text" id="seo_fury_focus_keyword" name="seo_fury_focus_keyword" value="<?php echo esc_attr($meta_data['focus_keyword'] ?? ''); ?>" placeholder="<?php echo esc_attr__('Primary keyword, e.g. SEO plugin', 'seo-fury'); ?>">
                    <p class="description" style="margin-top:4px;"><?php esc_html_e('Primary keyword used for the main SEO analysis.', 'seo-fury'); ?></p>
                </div>
                <div class="seo-fury-field" style="margin-top:12px;">
                    <label for="seo_fury_secondary_keywords" style="font-weight:500;display:block;margin-bottom:4px;"><?php esc_html_e('Secondary Keywords', 'seo-fury'); ?></label>
                    <?php
                    $secondary_keywords = isset($meta_data['secondary_keywords']) ? $meta_data['secondary_keywords'] : '';
                    ?>
                    <div id="seo-fury-keywords-tags" class="seo-fury-keywords-tags">
                        <?php
                        if (!empty($secondary_keywords)) {
                            $kw_array = array_filter(array_map('trim', explode(',', $secondary_keywords)));
                            foreach ($kw_array as $kw) {
                                echo '<span class="seo-fury-keyword-tag">' . esc_html($kw) . '<button type="button" class="seo-fury-keyword-remove" data-keyword="' . esc_attr($kw) . '">&times;</button></span>';
                            }
                        }
                        ?>
                        <input type="text" id="seo_fury_secondary_keyword_input" placeholder="<?php echo esc_attr__('Type and press Enter to add...', 'seo-fury'); ?>" class="seo-fury-keyword-input">
                    </div>
                    <input type="hidden" id="seo_fury_secondary_keywords" name="seo_fury_secondary_keywords" value="<?php echo esc_attr($secondary_keywords); ?>">
                    <p class="description"><?php esc_html_e('Additional keywords to track. Press Enter or comma to add each keyword.', 'seo-fury'); ?></p>
                </div>
            </div>

            <div class="seo-fury-section seo-fury-analysis">
                <div class="seo-fury-analysis-header">
                    <h4><?php esc_html_e('Basic SEO', 'seo-fury'); ?></h4>
                    <span class="seo-fury-score" id="seo-fury-score">0/100</span>
                </div>
                <ul class="seo-fury-analysis-list" id="seo-fury-analysis-list"></ul>
                <div class="seo-fury-analysis-footer">
                    <span class="seo-fury-analysis-metric"><?php esc_html_e('Keyword Density:', 'seo-fury'); ?> <strong id="seo-fury-keyword-density">0%</strong></span>
                    <div class="seo-fury-meter">
                        <span class="seo-fury-meter-bar" id="seo-fury-keyword-density-bar"></span>
                    </div>
                </div>
            </div>

            <div class="seo-fury-section seo-fury-readability">
                <div class="seo-fury-analysis-header">
                    <h4><?php esc_html_e('Readability', 'seo-fury'); ?></h4>
                    <span class="seo-fury-score" id="seo-fury-readability-score">0/100</span>
                </div>
                <ul class="seo-fury-analysis-list" id="seo-fury-readability-list"></ul>
                <div class="seo-fury-analysis-footer">
                    <span class="seo-fury-analysis-metric"><?php esc_html_e('Readability:', 'seo-fury'); ?> <strong id="seo-fury-readability-text">&mdash;</strong></span>
                    <div class="seo-fury-meter">
                        <span class="seo-fury-meter-bar" id="seo-fury-readability-bar"></span>
                    </div>
                    <span class="seo-fury-analysis-metric" style="margin-top:6px;"><?php esc_html_e('Flesch Score:', 'seo-fury'); ?> <strong id="seo-fury-flesch-score">&mdash;</strong></span>
                </div>
            </div>

            <div class="seo-fury-section seo-fury-extra-seo">
                <div class="seo-fury-analysis-header">
                    <h4><?php esc_html_e('Additional SEO', 'seo-fury'); ?></h4>
                    <span class="seo-fury-score" id="seo-fury-extra-score">0/100</span>
                </div>
                <p class="description"><?php esc_html_e('Extra on-page checks to improve visibility.', 'seo-fury'); ?></p>
                <ul class="seo-fury-analysis-list" id="seo-fury-extra-list"></ul>
            </div>
        </div>
        <?php
    }

    public function render_advanced_tab($post, $meta_data) {
        ?>
        <div class="seo-fury-tab-content" id="tab-advanced">
            <div class="seo-fury-section">
                <h4><?php esc_html_e('Robots Meta', 'seo-fury'); ?></h4>
                <p class="description"><?php esc_html_e('These settings override global robots meta for this page', 'seo-fury'); ?></p>

                <div class="seo-fury-fields-grid">
                    <div class="seo-fury-field">
                        <label>
                            <input type="checkbox" name="seo_fury_page_robots_noindex" value="1" <?php checked($meta_data['page_robots_noindex'], 1); ?>>
                            <?php esc_html_e('NoIndex', 'seo-fury'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevent indexing of this page', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label>
                            <input type="checkbox" name="seo_fury_page_robots_nofollow" value="1" <?php checked($meta_data['page_robots_nofollow'], 1); ?>>
                            <?php esc_html_e('NoFollow', 'seo-fury'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevent following links', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label>
                            <input type="checkbox" name="seo_fury_page_robots_noarchive" value="1" <?php checked($meta_data['page_robots_noarchive'], 1); ?>>
                            <?php esc_html_e('NoArchive', 'seo-fury'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevent cached copy', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label>
                            <input type="checkbox" name="seo_fury_page_robots_nosnippet" value="1" <?php checked($meta_data['page_robots_nosnippet'], 1); ?>>
                            <?php esc_html_e('NoSnippet', 'seo-fury'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevent snippet display', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label>
                            <input type="checkbox" name="seo_fury_page_robots_noimageindex" value="1" <?php checked($meta_data['page_robots_noimageindex'], 1); ?>>
                            <?php esc_html_e('NoImageIndex', 'seo-fury'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevent image indexing', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label for="seo_fury_page_robots_max_snippet"><?php esc_html_e('Max Snippet', 'seo-fury'); ?></label>
                        <input type="number" id="seo_fury_page_robots_max_snippet" name="seo_fury_page_robots_max_snippet"
                               value="<?php echo esc_attr($meta_data['page_robots_max_snippet']); ?>" placeholder="-1">
                        <p class="description"><?php esc_html_e('Text length (-1 = unlimited)', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label for="seo_fury_page_robots_max_video"><?php esc_html_e('Max Video Preview', 'seo-fury'); ?></label>
                        <input type="number" id="seo_fury_page_robots_max_video" name="seo_fury_page_robots_max_video"
                               value="<?php echo esc_attr($meta_data['page_robots_max_video']); ?>" placeholder="-1">
                        <p class="description"><?php esc_html_e('Video length in seconds', 'seo-fury'); ?></p>
                    </div>

                    <div class="seo-fury-field">
                        <label for="seo_fury_page_robots_max_image"><?php esc_html_e('Max Image Preview', 'seo-fury'); ?></label>
                        <select id="seo_fury_page_robots_max_image" name="seo_fury_page_robots_max_image">
                            <option value=""><?php esc_html_e('Default', 'seo-fury'); ?></option>
                            <option value="none" <?php selected($meta_data['page_robots_max_image'], 'none'); ?>><?php esc_html_e('None', 'seo-fury'); ?></option>
                            <option value="standard" <?php selected($meta_data['page_robots_max_image'], 'standard'); ?>><?php esc_html_e('Standard', 'seo-fury'); ?></option>
                            <option value="large" <?php selected($meta_data['page_robots_max_image'], 'large'); ?>><?php esc_html_e('Large', 'seo-fury'); ?></option>
                        </select>
                        <p class="description"><?php esc_html_e('Preview size', 'seo-fury'); ?></p>
                    </div>
                </div>
            </div>

            <div class="seo-fury-section">
                <h4><?php esc_html_e('Canonical URL', 'seo-fury'); ?></h4>
                <div class="seo-fury-field">
                    <label for="seo_fury_canonical"><?php esc_html_e('Canonical URL', 'seo-fury'); ?></label>
                    <input type="url" id="seo_fury_canonical" name="seo_fury_canonical"
                           value="<?php echo esc_attr($meta_data['canonical_url']); ?>">
                    <p class="description"><?php esc_html_e('Defaults to current page URL', 'seo-fury'); ?></p>
                </div>
            </div>
        </div>
        <?php
    }

    public function save_meta($post_id) {
        // Persist the combined SEO score (0-100) computed in the editor, so the
        // posts-list column can show/sort it without re-running the analysis.
        if (isset($_POST['seo_fury_seo_score']) && $_POST['seo_fury_seo_score'] !== '') {
            update_post_meta($post_id, '_seo_fury_seo_score', max(0, min(100, (int) $_POST['seo_fury_seo_score'])));
        }

        update_post_meta($post_id, '_seo_fury_page_robots_noindex', isset($_POST['seo_fury_page_robots_noindex']) ? 1 : 0);
        update_post_meta($post_id, '_seo_fury_page_robots_nofollow', isset($_POST['seo_fury_page_robots_nofollow']) ? 1 : 0);
        update_post_meta($post_id, '_seo_fury_page_robots_noarchive', isset($_POST['seo_fury_page_robots_noarchive']) ? 1 : 0);
        update_post_meta($post_id, '_seo_fury_page_robots_nosnippet', isset($_POST['seo_fury_page_robots_nosnippet']) ? 1 : 0);
        update_post_meta($post_id, '_seo_fury_page_robots_noimageindex', isset($_POST['seo_fury_page_robots_noimageindex']) ? 1 : 0);

        if (isset($_POST['seo_fury_page_robots_max_snippet'])) {
            update_post_meta($post_id, '_seo_fury_page_robots_max_snippet', sanitize_text_field($_POST['seo_fury_page_robots_max_snippet']));
        }

        if (isset($_POST['seo_fury_page_robots_max_video'])) {
            update_post_meta($post_id, '_seo_fury_page_robots_max_video', sanitize_text_field($_POST['seo_fury_page_robots_max_video']));
        }

        if (isset($_POST['seo_fury_page_robots_max_image'])) {
            update_post_meta($post_id, '_seo_fury_page_robots_max_image', sanitize_text_field($_POST['seo_fury_page_robots_max_image']));
        }

        if (isset($_POST['seo_fury_canonical'])) {
            update_post_meta($post_id, '_seo_fury_canonical', esc_url_raw($_POST['seo_fury_canonical']));
        }
    }

    public function output_meta_tags($post) {
        // Per-page robots: only output if user explicitly set any per-page robots flags
        $page_robots_noindex = get_post_meta($post->ID, '_seo_fury_page_robots_noindex', true);
        $page_robots_nofollow = get_post_meta($post->ID, '_seo_fury_page_robots_nofollow', true);
        $page_robots_noarchive = get_post_meta($post->ID, '_seo_fury_page_robots_noarchive', true);
        $page_robots_nosnippet = get_post_meta($post->ID, '_seo_fury_page_robots_nosnippet', true);
        $page_robots_noimageindex = get_post_meta($post->ID, '_seo_fury_page_robots_noimageindex', true);
        $page_robots_max_snippet = get_post_meta($post->ID, '_seo_fury_page_robots_max_snippet', true);
        $page_robots_max_video = get_post_meta($post->ID, '_seo_fury_page_robots_max_video', true);
        $page_robots_max_image = get_post_meta($post->ID, '_seo_fury_page_robots_max_image', true);

        $has_custom_robots = $page_robots_noindex || $page_robots_nofollow || $page_robots_noarchive
            || $page_robots_nosnippet || $page_robots_noimageindex
            || ($page_robots_max_snippet !== '') || ($page_robots_max_video !== '')
            || !empty($page_robots_max_image);

        if ($has_custom_robots) {
            $robots_parts = array();

            $robots_parts[] = $page_robots_noindex ? 'noindex' : 'index';
            $robots_parts[] = $page_robots_nofollow ? 'nofollow' : 'follow';

            if ($page_robots_noarchive) {
                $robots_parts[] = 'noarchive';
            }
            if ($page_robots_nosnippet) {
                $robots_parts[] = 'nosnippet';
            }
            if ($page_robots_noimageindex) {
                $robots_parts[] = 'noimageindex';
            }
            if ($page_robots_max_snippet !== '') {
                $robots_parts[] = 'max-snippet:' . intval($page_robots_max_snippet);
            }
            if ($page_robots_max_video !== '') {
                $robots_parts[] = 'max-video-preview:' . intval($page_robots_max_video);
            }
            if ($page_robots_max_image && in_array($page_robots_max_image, array('none', 'standard', 'large'), true)) {
                $robots_parts[] = 'max-image-preview:' . $page_robots_max_image;
            }

            echo '<meta name="robots" content="' . esc_attr(implode(', ', $robots_parts)) . '">' . "\n";
        }
        // If no custom per-page robots set, meta-titles.php handles global/per-post-type robots

        // Canonical URL
        $canonical_url = get_post_meta($post->ID, '_seo_fury_canonical', true);
        if (!$canonical_url) {
            $canonical_url = get_permalink($post->ID);
        }

        if ($canonical_url) {
            echo '<link rel="canonical" href="' . esc_url($canonical_url) . '">' . "\n";
        }
    }
}
