<?php
/**
 * کلاس SEO پیشرفته Dima Shop
 */
if (!defined('ABSPATH')) exit;

class Dima_SEO {
    
    private static $instance = null;
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('wp_head', array($this, 'output_meta_tags'), 1);
        add_action('wp_head', array($this, 'output_open_graph'), 5);
        add_action('wp_head', array($this, 'output_twitter_cards'), 5);
        add_action('wp_head', array($this, 'output_schema_markup'), 10);
        add_action('wp_head', array($this, 'output_canonical'), 2);
        
        add_filter('wp_robots', array($this, 'custom_robots'));
        add_filter('pre_get_document_title', array($this, 'optimize_title'), 20);
        add_filter('document_title_parts', array($this, 'title_parts'), 20);
        add_filter('document_title_separator', array($this, 'title_separator'));
        add_filter('wp_get_attachment_image_attributes', array($this, 'optimize_image_alt'), 10, 2);
    }
    
    /**
     * بهینه‌سازی عنوان صفحه
     */
    public function optimize_title($title) {
        if (is_singular('dima_product')) {
            $product_name = get_the_title();
            $price = Dima_Product::get_price(get_the_ID());
            $currency = get_option('dima_currency', 'تومان');
            
            if ($price) {
                return "{$product_name} - قیمت " . number_format($price) . " {$currency}";
            }
            return $product_name;
        }
        
        if (is_tax('dima_product_cat')) {
            $term = get_queried_object();
            return "خرید " . $term->name . " - بهترین قیمت";
        }
        
        $shop_page_id = get_option('dima_shop_page');
        if ($shop_page_id && is_page($shop_page_id)) {
            return "فروشگاه آنلاین - خرید اینترنتی";
        }
        
        return $title;
    }
    
    public function title_parts($parts) {
        if (is_singular('dima_product') || is_tax('dima_product_cat')) {
            $parts['site'] = get_bloginfo('name');
        }
        return $parts;
    }
    
    public function title_separator($sep) {
        return '|';
    }
    
    /**
     * Meta tags بهینه
     */
    public function output_meta_tags() {
        if (is_singular('dima_product')) {
            $product_id = get_the_ID();
            $price = Dima_Product::get_price($product_id);
            $description = $this->get_product_description($product_id);
            
            echo "\n<!-- Dima Shop SEO Meta Tags -->\n";
            echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
            echo '<meta name="keywords" content="' . esc_attr($this->get_product_keywords($product_id)) . '">' . "\n";
            
            if ($price) {
                echo '<meta name="price" content="' . esc_attr($price) . '">' . "\n";
                echo '<meta name="currency" content="' . esc_attr(get_option('dima_currency', 'IRR')) . '">' . "\n";
            }
            
            echo '<meta name="robots" content="index, follow, max-image-preview:large">' . "\n";
        } elseif (is_tax('dima_product_cat')) {
            $term = get_queried_object();
            $description = $term->description ?: "خرید آنلاین " . $term->name . " با بهترین قیمت و کیفیت";
            
            echo "\n<!-- Dima Shop Category Meta Tags -->\n";
            echo '<meta name="description" content="' . esc_attr($description) . '">' . "\n";
            echo '<meta name="robots" content="index, follow">' . "\n";
        }
    }
    
    /**
     * Open Graph Tags
     */
    public function output_open_graph() {
        if (!is_singular('dima_product') && !is_tax('dima_product_cat')) return;
        
        echo "\n<!-- Open Graph Tags -->\n";
        
        if (is_singular('dima_product')) {
            $product_id = get_the_ID();
            $title = get_the_title();
            $description = $this->get_product_description($product_id);
            $image = get_the_post_thumbnail_url($product_id, 'large');
            $url = get_permalink();
            $price = Dima_Product::get_price($product_id);
            
            echo '<meta property="og:type" content="product">' . "\n";
            echo '<meta property="og:title" content="' . esc_attr($title) . '">' . "\n";
            echo '<meta property="og:description" content="' . esc_attr($description) . '">' . "\n";
            echo '<meta property="og:url" content="' . esc_url($url) . '">' . "\n";
            echo '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
            echo '<meta property="og:locale" content="fa_IR">' . "\n";
            
            if ($image) {
                echo '<meta property="og:image" content="' . esc_url($image) . '">' . "\n";
                echo '<meta property="og:image:width" content="1200">' . "\n";
                echo '<meta property="og:image:height" content="630">' . "\n";
            }
            
            if ($price) {
                echo '<meta property="product:price:amount" content="' . esc_attr($price) . '">' . "\n";
                echo '<meta property="product:price:currency" content="IRR">' . "\n";
                echo '<meta property="product:availability" content="in stock">' . "\n";
            }
        }
    }
    
    /**
     * Twitter Cards
     */
    public function output_twitter_cards() {
        if (!is_singular('dima_product')) return;
        
        $product_id = get_the_ID();
        $image = get_the_post_thumbnail_url($product_id, 'large');
        
        echo "\n<!-- Twitter Cards -->\n";
        echo '<meta name="twitter:card" content="' . ($image ? 'summary_large_image' : 'summary') . '">' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr(get_the_title()) . '">' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr($this->get_product_description($product_id)) . '">' . "\n";
        
        if ($image) {
            echo '<meta name="twitter:image" content="' . esc_url($image) . '">' . "\n";
        }
    }
    
    /**
     * Schema.org JSON-LD Markup
     */
    public function output_schema_markup() {
        if (!get_option('dima_schema_markup')) return;
        
        if (is_singular('dima_product')) {
            $this->output_product_schema();
        } elseif (is_tax('dima_product_cat')) {
            $this->output_category_schema();
        } elseif (is_front_page()) {
            $this->output_organization_schema();
            $this->output_website_schema();
        }
    }
    
    private function output_product_schema() {
        $product_id = get_the_ID();
        $price = Dima_Product::get_price($product_id);
        $stock = Dima_Product::get_stock($product_id);
        $image = get_the_post_thumbnail_url($product_id, 'large');
        $description = $this->get_product_description($product_id);
        $categories = wp_get_post_terms($product_id, 'dima_product_cat', array('fields' => 'names'));
        
        $schema = array(
            '@context' => 'https://schema.org/',
            '@type' => 'Product',
            'name' => get_the_title(),
            'description' => $description,
            'sku' => 'DIMA-' . $product_id,
            'productID' => $product_id,
            'url' => get_permalink(),
            'itemCondition' => 'https://schema.org/NewCondition',
            'availability' => ($stock === '' || intval($stock) > 0) 
                ? 'https://schema.org/InStock' 
                : 'https://schema.org/OutOfStock',
            'datePublished' => get_the_date('c'),
            'dateModified' => get_the_modified_date('c'),
        );
        
        if ($image) $schema['image'] = $image;
        
        if ($price) {
            $schema['offers'] = array(
                '@type' => 'Offer',
                'priceCurrency' => 'IRR',
                'price' => $price,
                'priceValidUntil' => date('Y-12-31'),
                'availability' => $schema['availability'],
                'url' => get_permalink(),
                'seller' => array(
                    '@type' => 'Organization',
                    'name' => get_option('dima_schema_org_name', get_bloginfo('name'))
                )
            );
        }
        
        if (!empty($categories)) {
            $schema['category'] = implode(' > ', $categories);
        }
        
        $rating = get_post_meta($product_id, '_dima_avg_rating', true);
        $review_count = get_post_meta($product_id, '_dima_review_count', true);
        
        if ($rating && $review_count) {
            $schema['aggregateRating'] = array(
                '@type' => 'AggregateRating',
                'ratingValue' => $rating,
                'reviewCount' => $review_count,
                'bestRating' => 5,
                'worstRating' => 1
            );
        }
        
        echo "\n<!-- Product Schema.org JSON-LD -->\n";
        echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . '</script>' . "\n";
    }
    
    private function output_category_schema() {
        $term = get_queried_object();
        $image_id = get_term_meta($term->term_id, 'category_image_id', true);
        $image = $image_id ? wp_get_attachment_image_url($image_id, 'large') : '';
        
        $schema = array(
            '@context' => 'https://schema.org/',
            '@type' => 'CollectionPage',
            'name' => $term->name,
            'description' => $term->description ?: 'دسته‌بندی ' . $term->name,
            'url' => get_term_link($term),
            'numberOfItems' => $term->count
        );
        
        if ($image) $schema['image'] = $image;
        
        echo "\n<!-- Category Schema.org JSON-LD -->\n";
        echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
    }
    
      private function output_organization_schema() {
          $org_name = get_option('dima_schema_org_name', get_option('dima_store_name', get_bloginfo('name')));
          $logo_id = get_option('dima_schema_org_logo');
          $logo = $logo_id ? wp_get_attachment_image_url($logo_id, 'full') : '';
    
          $schema = array(
              '@context' => 'https://schema.org/',
              '@type' => 'Organization',
              'name' => $org_name,
              'url' => home_url('/'),
              'description' => get_option('dima_store_description', get_bloginfo('description'))
          );
    
          if ($logo) {
              $schema['logo'] = array('@type' => 'ImageObject', 'url' => $logo);
          }
    
          // اطلاعات تماس از تنظیمات فروشگاه
          $phone = get_option('dima_store_phone');
          $email = get_option('dima_store_email');
          $address = get_option('dima_store_address');
          $city = get_option('dima_store_city');
    
          if ($phone || $email) {
              $schema['contactPoint'] = array(
                  '@type' => 'ContactPoint',
                  'contactType' => 'customer service',
                  'availableLanguage' => array('Persian', 'English')
              );
        
              if ($phone) $schema['contactPoint']['telephone'] = $phone;
              if ($email) $schema['contactPoint']['email'] = $email;
          }
    
          if ($address || $city) {
              $schema['address'] = array(
                  '@type' => 'PostalAddress',
                  'addressLocality' => $city,
                  'streetAddress' => $address,
                  'addressCountry' => 'IR'
              );
          }
    
          // شبکه‌های اجتماعی
          $same_as = array_filter(array(
              get_option('dima_store_instagram'),
              get_option('dima_store_telegram'),
              get_option('dima_store_whatsapp'),
              get_option('dima_store_twitter'),
              get_option('dima_store_linkedin')
          ));
    
          if (!empty($same_as)) {
              $schema['sameAs'] = array_values($same_as);
          }
    
          echo "\n<!-- Organization Schema.org JSON-LD -->\n";
          echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
      }
    
    private function output_website_schema() {
        $schema = array(
            '@context' => 'https://schema.org/',
            '@type' => 'WebSite',
            'name' => get_bloginfo('name'),
            'url' => home_url('/'),
            'potentialAction' => array(
                '@type' => 'SearchAction',
                'target' => home_url('/?s={search_term_string}&post_type=dima_product'),
                'query-input' => 'required name=search_term_string'
            )
        );
        
        echo "\n<!-- Website Schema.org JSON-LD -->\n";
        echo '<script type="application/ld+json">' . wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</script>' . "\n";
    }
    
    /**
     * Canonical URL
     */
    public function output_canonical() {
        if (is_singular('dima_product') || is_tax('dima_product_cat')) {
            $url = is_singular() ? get_permalink() : get_term_link(get_queried_object());
            echo '<link rel="canonical" href="' . esc_url($url) . '">' . "\n";
        }
    }
    
    public function custom_robots($robots) {
        if (is_singular('dima_product') || is_tax('dima_product_cat')) {
            $robots['max-image-preview'] = 'large';
        }
        return $robots;
    }
    
    public function optimize_image_alt($attr, $attachment) {
        if (empty($attr['alt']) && is_singular('dima_product')) {
            $attr['alt'] = get_the_title() . ' - ' . get_bloginfo('name');
        }
        $attr['loading'] = 'lazy';
        return $attr;
    }
    
    private function get_product_description($product_id) {
        $excerpt = get_post_field('post_excerpt', $product_id);
        
        if (empty($excerpt)) {
            $content = get_post_field('post_content', $product_id);
            $excerpt = wp_trim_words(wp_strip_all_tags($content), 30, '...');
        }
        
        $price = Dima_Product::get_price($product_id);
        $currency = get_option('dima_currency', 'تومان');
        
        if ($price) {
            $excerpt .= " قیمت: " . number_format($price) . " {$currency}.";
        }
        
        return $excerpt;
    }
    
    private function get_product_keywords($product_id) {
        $keywords = array();
        
        $title = get_the_title($product_id);
        $keywords[] = $title;
        
        $categories = wp_get_post_terms($product_id, 'dima_product_cat', array('fields' => 'names'));
        if (!is_wp_error($categories)) {
            $keywords = array_merge($keywords, $categories);
        }
        
        $attributes = wp_get_post_terms($product_id, 'dima_attribute', array('fields' => 'names'));
        if (!is_wp_error($attributes)) {
            $keywords = array_merge($keywords, $attributes);
        }
        
        $keywords[] = 'خرید ' . $title;
        $keywords[] = 'قیمت ' . $title;
        
        return implode(', ', array_unique($keywords));
    }
}