<?php

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

class SEO_Fury_WooCommerce {

    public function __construct() {
        if (!class_exists('WooCommerce')) {
            return;
        }

        $this->init_hooks();
    }

    private function init_hooks() {
        add_action('save_post_product', array($this, 'auto_populate_product_schema'), 20, 2);

        add_action('product_cat_edit_form_fields', array($this, 'render_taxonoseo_fury_fields'), 10, 1);
        add_action('product_tag_edit_form_fields', array($this, 'render_taxonoseo_fury_fields'), 10, 1);
        add_action('product_cat_add_form_fields', array($this, 'render_taxonoseo_fury_fields_add'), 10);
        add_action('product_tag_add_form_fields', array($this, 'render_taxonoseo_fury_fields_add'), 10);

        add_action('edited_product_cat', array($this, 'save_taxonoseo_fury_fields'), 10, 1);
        add_action('edited_product_tag', array($this, 'save_taxonoseo_fury_fields'), 10, 1);
        add_action('created_product_cat', array($this, 'save_taxonoseo_fury_fields'), 10, 1);
        add_action('created_product_tag', array($this, 'save_taxonoseo_fury_fields'), 10, 1);

        add_action('wp_head', array($this, 'output_taxonomy_meta'), 5);

        if (get_option('seo_fury_wc_remove_default_schema', 0)) {
            add_action('init', array($this, 'remove_wc_default_schema'));
        }
    }

    public function auto_populate_product_schema($post_id, $post) {
        if (!get_option('seo_fury_wc_auto_schema', 1)) {
            return;
        }

        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        $product = wc_get_product($post_id);
        if (!$product) {
            return;
        }

        $schema_data = array();
        $schema_data['name'] = $product->get_name();

        if (get_option('seo_fury_wc_schema_price', 1)) {
            $schema_data['price'] = $product->get_price();
            $schema_data['currency'] = get_woocommerce_currency();

            if ($product->is_on_sale() && $product->get_sale_price()) {
                $schema_data['price'] = $product->get_sale_price();
            }
        }

        $sku = $product->get_sku();
        if ($sku) {
            $schema_data['sku'] = $sku;
        }

        $stock_status = $product->get_stock_status();
        $availability_map = array(
            'instock'     => 'InStock',
            'outofstock'  => 'OutOfStock',
            'onbackorder' => 'BackOrder',
        );
        $schema_data['availability'] = isset($availability_map[$stock_status])
            ? $availability_map[$stock_status]
            : 'InStock';

        if (get_option('seo_fury_wc_schema_brand', 0)) {
            $brand_attr = get_option('seo_fury_wc_brand_attribute', 'pa_brand');
            $brand = $product->get_attribute($brand_attr);
            if (!$brand) {
                $brand = $product->get_attribute(str_replace('pa_', '', $brand_attr));
            }
            if ($brand) {
                $schema_data['brand'] = $brand;
            }
        }

        if (get_option('seo_fury_wc_schema_reviews', 1)) {
            $rating_count = $product->get_rating_count();
            $average_rating = $product->get_average_rating();
            if ($rating_count > 0 && $average_rating > 0) {
                $schema_data['rating_value'] = $average_rating;
                $schema_data['review_count'] = $rating_count;
            }
        }

        $image_id = $product->get_image_id();
        if ($image_id) {
            $image_url = wp_get_attachment_url($image_id);
            if ($image_url) {
                $schema_data['image'] = $image_url;
            }
        }

        $short_desc = $product->get_short_description();
        if ($short_desc) {
            $schema_data['description'] = wp_strip_all_tags($short_desc);
        }

        $existing_schemas = get_post_meta($post_id, '_seo_fury_schema_items', true);
        $has_manual_product_schema = false;

        if (is_array($existing_schemas)) {
            foreach ($existing_schemas as $schema) {
                if (isset($schema['type']) && $schema['type'] === 'product' && isset($schema['manual']) && $schema['manual']) {
                    $has_manual_product_schema = true;
                    break;
                }
            }
        }

        if (!$has_manual_product_schema) {
            $auto_schema = array(
                'id' => 'wc_product_auto',
                'type' => 'product',
                'mode' => 'generator',
                'data' => $schema_data,
                'auto' => true,
            );

            if (!is_array($existing_schemas)) {
                $existing_schemas = array();
            }

            $existing_schemas = array_filter($existing_schemas, function($s) {
                return !(isset($s['auto']) && $s['auto']);
            });

            $existing_schemas[] = $auto_schema;

            update_post_meta($post_id, '_seo_fury_schema_items', array_values($existing_schemas));
        }
    }

    public function remove_wc_default_schema() {
        remove_action('wp_footer', array(WC()->structured_data, 'output_structured_data'), 10);
        remove_action('woocommerce_email_order_details', array(WC()->structured_data, 'output_email_structured_data'), 30);
    }

    public function render_taxonoseo_fury_fields($term) {
        $term_id = is_object($term) ? $term->term_id : 0;
        $title = get_term_meta($term_id, '_seo_fury_title', true);
        $description = get_term_meta($term_id, '_seo_fury_description', true);
        $og_image = get_term_meta($term_id, '_seo_fury_og_image', true);
        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';
        ?>
        <tr class="form-field">
            <th scope="row" colspan="2">
                <h3 style="margin: 20px 0 10px; padding-top: 20px; border-top: 2px solid #4F46E5;">
                    <span class="dashicons dashicons-search" style="color: #4F46E5; vertical-align: middle;"></span>
                    <?php echo esc_html($brand); ?> — <?php esc_html_e('SEO', 'seo-fury'); ?>
                </h3>
            </th>
        </tr>
        <tr class="form-field">
            <th scope="row"><label for="seo_fury_title"><?php esc_html_e('SEO Title', 'seo-fury'); ?></label></th>
            <td>
                <input type="text" id="seo_fury_title" name="seo_fury_title" value="<?php echo esc_attr($title); ?>" style="width: 100%; max-width: 500px;" />
                <p class="description"><?php
                /* translators: 1: %term_title% variable, 2: %sitename% variable, 3: %sep% variable */
                printf( esc_html__('Custom SEO title for this taxonomy. Variables: %1$s, %2$s, %3$s', 'seo-fury'), '<code>%term_title%</code>', '<code>%sitename%</code>', '<code>%sep%</code>' ); ?></p>
            </td>
        </tr>
        <tr class="form-field">
            <th scope="row"><label for="seo_fury_description"><?php esc_html_e('Meta Description', 'seo-fury'); ?></label></th>
            <td>
                <textarea id="seo_fury_description" name="seo_fury_description" rows="3" style="width: 100%; max-width: 500px;"><?php echo esc_textarea($description); ?></textarea>
                <p class="description"><?php esc_html_e('Custom meta description for this taxonomy page.', 'seo-fury'); ?></p>
            </td>
        </tr>
        <tr class="form-field">
            <th scope="row"><label for="seo_fury_og_image"><?php esc_html_e('Open Graph Image', 'seo-fury'); ?></label></th>
            <td>
                <input type="url" id="seo_fury_og_image" name="seo_fury_og_image" value="<?php echo esc_url($og_image); ?>" style="width: 100%; max-width: 500px;" placeholder="https://" />
                <p class="description"><?php esc_html_e('Custom social sharing image for this taxonomy page.', 'seo-fury'); ?></p>
            </td>
        </tr>
        <?php
        wp_nonce_field('seo_fury_taxonomy_seo', 'seo_fury_taxonomy_nonce');
    }

    public function render_taxonoseo_fury_fields_add($taxonomy) {
        $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';
        ?>
        <div class="form-field" style="border-top: 2px solid #4F46E5; padding-top: 15px; margin-top: 20px;">
            <h3>
                <span class="dashicons dashicons-search" style="color: #4F46E5; vertical-align: middle;"></span>
                <?php echo esc_html($brand); ?> — <?php esc_html_e('SEO', 'seo-fury'); ?>
            </h3>
        </div>
        <div class="form-field">
            <label for="seo_fury_title"><?php esc_html_e('SEO Title', 'seo-fury'); ?></label>
            <input type="text" id="seo_fury_title" name="seo_fury_title" value="" />
            <p><?php
            /* translators: 1: %term_title% variable, 2: %sitename% variable, 3: %sep% variable */
            printf( esc_html__('Custom SEO title. Variables: %1$s, %2$s, %3$s', 'seo-fury'), '<code>%term_title%</code>', '<code>%sitename%</code>', '<code>%sep%</code>' ); ?></p>
        </div>
        <div class="form-field">
            <label for="seo_fury_description"><?php esc_html_e('Meta Description', 'seo-fury'); ?></label>
            <textarea id="seo_fury_description" name="seo_fury_description" rows="3"></textarea>
            <p><?php esc_html_e('Custom meta description for this taxonomy page.', 'seo-fury'); ?></p>
        </div>
        <?php
        wp_nonce_field('seo_fury_taxonomy_seo', 'seo_fury_taxonomy_nonce');
    }

    public function save_taxonoseo_fury_fields($term_id) {
        if (!isset($_POST['seo_fury_taxonomy_nonce']) || !wp_verify_nonce($_POST['seo_fury_taxonomy_nonce'], 'seo_fury_taxonomy_seo')) {
            return;
        }

        if (isset($_POST['seo_fury_title'])) {
            update_term_meta($term_id, '_seo_fury_title', sanitize_text_field($_POST['seo_fury_title']));
        }
        if (isset($_POST['seo_fury_description'])) {
            update_term_meta($term_id, '_seo_fury_description', sanitize_textarea_field($_POST['seo_fury_description']));
        }
        if (isset($_POST['seo_fury_og_image'])) {
            update_term_meta($term_id, '_seo_fury_og_image', esc_url_raw($_POST['seo_fury_og_image']));
        }
    }

    public function output_taxonomy_meta() {
        if (!is_tax('product_cat') && !is_tax('product_tag')) {
            return;
        }

        $term = get_queried_object();
        if (!$term || !isset($term->term_id)) {
            return;
        }

        $title = get_term_meta($term->term_id, '_seo_fury_title', true);
        $description = get_term_meta($term->term_id, '_seo_fury_description', true);
        $og_image = get_term_meta($term->term_id, '_seo_fury_og_image', true);

        if ($title || $description || $og_image) {
            $brand = function_exists('seo_fury_get_brand_name') ? seo_fury_get_brand_name() : 'SEO Fury';
            echo "\n<!-- " . esc_html($brand) . " -->\n";
        }

        if ($title) {
            $title = str_replace(
                array('%term_title%', '%sitename%', '%sep%'),
                array($term->name, get_bloginfo('name'), get_option('seo_fury_title_separator', '—')),
                $title
            );
            echo '<meta name="title" content="' . esc_attr($title) . '">' . "\n";
        }

        if ($description) {
            $description = str_replace(
                array('%term_title%', '%sitename%', '%term_description%'),
                array($term->name, get_bloginfo('name'), $term->description),
                $description
            );
            echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
        }

        if ($og_image) {
            echo '<meta property="og:image" content="' . esc_url($og_image) . '">' . "\n";
        }

        if ($title || $description || $og_image) {
            echo "<!-- /" . esc_html($brand) . " -->\n";
        }
    }

    public function render_settings_page() {
        if (!class_exists('WooCommerce')) {
            echo '<div class="seo-content-box"><p>' . esc_html__('WooCommerce is not installed or activated. This module requires WooCommerce to function.', 'seo-fury') . '</p></div>';
            return;
        }

        if (isset($_POST['seo_fury_wc_save']) && check_admin_referer('seo_fury_wc_settings')) {
            update_option('seo_fury_wc_auto_schema', isset($_POST['seo_fury_wc_auto_schema']) ? 1 : 0);
            update_option('seo_fury_wc_schema_price', isset($_POST['seo_fury_wc_schema_price']) ? 1 : 0);
            update_option('seo_fury_wc_schema_reviews', isset($_POST['seo_fury_wc_schema_reviews']) ? 1 : 0);
            update_option('seo_fury_wc_schema_brand', isset($_POST['seo_fury_wc_schema_brand']) ? 1 : 0);
            update_option('seo_fury_wc_brand_attribute', sanitize_text_field($_POST['seo_fury_wc_brand_attribute'] ?? 'pa_brand'));
            update_option('seo_fury_wc_remove_default_schema', isset($_POST['seo_fury_wc_remove_default_schema']) ? 1 : 0);

            update_option('seo_fury_wc_product_title_template', sanitize_text_field($_POST['seo_fury_wc_product_title_template'] ?? ''));
            update_option('seo_fury_wc_product_desc_template', sanitize_textarea_field($_POST['seo_fury_wc_product_desc_template'] ?? ''));
            update_option('seo_fury_wc_cat_title_template', sanitize_text_field($_POST['seo_fury_wc_cat_title_template'] ?? ''));
            update_option('seo_fury_wc_tag_title_template', sanitize_text_field($_POST['seo_fury_wc_tag_title_template'] ?? ''));

            echo '<div class="notice notice-success inline" style="margin: 0 0 15px;"><p>' . esc_html__('WooCommerce SEO settings saved.', 'seo-fury') . '</p></div>';
        }

        $auto_schema = get_option('seo_fury_wc_auto_schema', 1);
        $schema_price = get_option('seo_fury_wc_schema_price', 1);
        $schema_reviews = get_option('seo_fury_wc_schema_reviews', 1);
        $schema_brand = get_option('seo_fury_wc_schema_brand', 0);
        $brand_attribute = get_option('seo_fury_wc_brand_attribute', 'pa_brand');
        $remove_default = get_option('seo_fury_wc_remove_default_schema', 0);
        $product_title_tpl = get_option('seo_fury_wc_product_title_template', '%title% %sep% %sitename%');
        $product_desc_tpl = get_option('seo_fury_wc_product_desc_template', '%excerpt%');
        $cat_title_tpl = get_option('seo_fury_wc_cat_title_template', '%term_title% %sep% %sitename%');
        $tag_title_tpl = get_option('seo_fury_wc_tag_title_template', '%term_title% %sep% %sitename%');

        $product_count = wp_count_posts('product');
        $total_products = isset($product_count->publish) ? $product_count->publish : 0;
        $cats_count = wp_count_terms(array('taxonomy' => 'product_cat', 'hide_empty' => false));
        ?>

        <form method="post" action="">
            <?php wp_nonce_field('seo_fury_wc_settings'); ?>

            <!-- Overview -->
            <div class="seo-content-box">
                <h3><?php esc_html_e('WooCommerce Overview', 'seo-fury'); ?></h3>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-top: 10px;">
                    <div style="padding: 15px; background: var(--sf-primary-light, #EEF2FF); border-radius: 8px; text-align: center;">
                        <div style="font-size: 28px; font-weight: 700; color: var(--sf-primary, #4F46E5);"><?php echo intval($total_products); ?></div>
                        <div style="font-size: 12px; color: var(--sf-gray-500, #64748B); margin-top: 4px;"><?php esc_html_e('Products', 'seo-fury'); ?></div>
                    </div>
                    <div style="padding: 15px; background: var(--sf-success-light, #ECFDF5); border-radius: 8px; text-align: center;">
                        <div style="font-size: 28px; font-weight: 700; color: var(--sf-success, #10B981);"><?php echo intval($cats_count); ?></div>
                        <div style="font-size: 12px; color: var(--sf-gray-500, #64748B); margin-top: 4px;"><?php esc_html_e('Categories', 'seo-fury'); ?></div>
                    </div>
                    <div style="padding: 15px; background: var(--sf-accent-light, #FEF3C7); border-radius: 8px; text-align: center;">
                        <div style="font-size: 28px; font-weight: 700; color: var(--sf-accent, #F59E0B);"><?php echo $auto_schema ? esc_html__('ON', 'seo-fury') : esc_html__('OFF', 'seo-fury'); ?></div>
                        <div style="font-size: 12px; color: var(--sf-gray-500, #64748B); margin-top: 4px;"><?php esc_html_e('Auto Schema', 'seo-fury'); ?></div>
                    </div>
                </div>
            </div>

            <!-- Product Schema Settings -->
            <div class="seo-content-box">
                <h3><?php esc_html_e('Product Schema (Structured Data)', 'seo-fury'); ?></h3>
                <p class="description" style="margin-bottom: 15px;"><?php esc_html_e('Automatically generate Product schema markup from WooCommerce product data.', 'seo-fury'); ?></p>

                <table class="form-table">
                    <tr>
                        <th scope="row"><?php esc_html_e('Auto-generate Product Schema', 'seo-fury'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="seo_fury_wc_auto_schema" value="1" <?php checked($auto_schema, 1); ?> />
                                <?php esc_html_e('Automatically create Product schema from WooCommerce data when saving a product', 'seo-fury'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Include Price', 'seo-fury'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="seo_fury_wc_schema_price" value="1" <?php checked($schema_price, 1); ?> />
                                <?php esc_html_e('Include product price and currency in schema', 'seo-fury'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Include Reviews', 'seo-fury'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="seo_fury_wc_schema_reviews" value="1" <?php checked($schema_reviews, 1); ?> />
                                <?php esc_html_e('Include average rating and review count in schema', 'seo-fury'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Include Brand', 'seo-fury'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="seo_fury_wc_schema_brand" value="1" <?php checked($schema_brand, 1); ?> />
                                <?php esc_html_e('Include brand from product attribute', 'seo-fury'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Brand Attribute', 'seo-fury'); ?></th>
                        <td>
                            <input type="text" name="seo_fury_wc_brand_attribute" value="<?php echo esc_attr($brand_attribute); ?>" style="max-width: 300px;" />
                            <p class="description"><?php
                                /* translators: %1$s and %2$s are code examples for attribute slugs */
                                printf(esc_html__('Product attribute slug for brand (e.g., %1$s or %2$s)', 'seo-fury'), '<code>pa_brand</code>', '<code>brand</code>');
                            ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Remove WC Default Schema', 'seo-fury'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="seo_fury_wc_remove_default_schema" value="1" <?php checked($remove_default, 1); ?> />
                                <?php esc_html_e('Remove WooCommerce\'s built-in structured data to prevent conflicts', 'seo-fury'); ?>
                            </label>
                            <p class="description" style="color: #d63638;"><?php esc_html_e('Warning: Only enable this if you are using SEO Fury to generate all product schema.', 'seo-fury'); ?></p>
                        </td>
                    </tr>
                </table>
            </div>

            <!-- SEO Templates -->
            <div class="seo-content-box">
                <h3><?php esc_html_e('SEO Title Templates', 'seo-fury'); ?></h3>
                <p class="description" style="margin-bottom: 15px;"><?php esc_html_e('Default SEO title/description templates for products and taxonomies. These are used when individual products don\'t have custom SEO titles set.', 'seo-fury'); ?></p>

                <table class="form-table">
                    <tr>
                        <th scope="row"><?php esc_html_e('Product Title Template', 'seo-fury'); ?></th>
                        <td>
                            <input type="text" name="seo_fury_wc_product_title_template" value="<?php echo esc_attr($product_title_tpl); ?>" style="width: 100%; max-width: 500px;" />
                            <p class="description"><?php
                                /* translators: %1$s, %2$s, %3$s, %4$s are template variable names */
                                printf(esc_html__('Variables: %1$s, %2$s, %3$s, %4$s', 'seo-fury'), '<code>%title%</code>', '<code>%sitename%</code>', '<code>%sep%</code>', '<code>%category%</code>');
                            ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Product Description Template', 'seo-fury'); ?></th>
                        <td>
                            <input type="text" name="seo_fury_wc_product_desc_template" value="<?php echo esc_attr($product_desc_tpl); ?>" style="width: 100%; max-width: 500px;" />
                            <p class="description"><?php
                                /* translators: %1$s, %2$s, %3$s are template variable names */
                                printf(esc_html__('Variables: %1$s, %2$s, %3$s', 'seo-fury'), '<code>%excerpt%</code>', '<code>%wcshortdesc%</code>', '<code>%title%</code>');
                            ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Product Category Title', 'seo-fury'); ?></th>
                        <td>
                            <input type="text" name="seo_fury_wc_cat_title_template" value="<?php echo esc_attr($cat_title_tpl); ?>" style="width: 100%; max-width: 500px;" />
                            <p class="description"><?php
                                /* translators: %1$s, %2$s, %3$s are template variable names */
                                printf(esc_html__('Variables: %1$s, %2$s, %3$s', 'seo-fury'), '<code>%term_title%</code>', '<code>%sitename%</code>', '<code>%sep%</code>');
                            ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><?php esc_html_e('Product Tag Title', 'seo-fury'); ?></th>
                        <td>
                            <input type="text" name="seo_fury_wc_tag_title_template" value="<?php echo esc_attr($tag_title_tpl); ?>" style="width: 100%; max-width: 500px;" />
                            <p class="description"><?php
                                /* translators: %1$s, %2$s, %3$s are template variable names */
                                printf(esc_html__('Variables: %1$s, %2$s, %3$s', 'seo-fury'), '<code>%term_title%</code>', '<code>%sitename%</code>', '<code>%sep%</code>');
                            ?></p>
                        </td>
                    </tr>
                </table>
            </div>

            <p class="submit">
                <input type="submit" name="seo_fury_wc_save" class="button button-primary" value="<?php echo esc_attr__('Save WooCommerce Settings', 'seo-fury'); ?>" />
            </p>
        </form>
        <?php
    }
}
