<?php
/**
 * WCMLIM SEO - Location SEO Optimization
 *
 * @link       http://www.techspawn.com
 * @since      1.0.0
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/includes
 */

/**
 * SEO functionality for multi-location stores
 *
 * Generates structured data (Schema.org), meta tags, and SEO-friendly content
 * for each location to improve local search visibility.
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/includes
 * @author     techspawn1 <contact@techspawn.com>
 */
class WCMLIM_SEO {

    /**
     * Plugin name
     */
    private $plugin_name;

    /**
     * Plugin version
     */
    private $version;

    /**
     * Current location term
     */
    private $current_location;

    /**
     * Constructor
     */
    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;

        // Hook into WordPress head for meta tags and schema
        add_action('wp_head', array($this, 'output_location_seo_tags'), 1);
        add_action('wp_head', array($this, 'output_location_schema'), 5);
    }

    /**
     * Check if SEO is enabled
     */
    public function is_seo_enabled() {
        return get_option('wcmlim_seo_enabled', 'on') === 'on';
    }

    /**
     * Check if structured data is enabled
     */
    public function is_structured_data_enabled() {
        return get_option('wcmlim_structured_data_enabled', 'on') === 'on';
    }

    /**
     * Get current location from cookie or query
     */
    private function get_current_location() {
        if ($this->current_location) {
            return $this->current_location;
        }

        // Check if we're on a location taxonomy page
        if (is_tax('locations')) {
            $this->current_location = get_queried_object();
            return $this->current_location;
        }

        // Check if we're on a custom location archive page (/locations/mumbai/)
        if (get_query_var('location_archive') && get_query_var('location_slug')) {
            $location_slug = get_query_var('location_slug');
            $location = get_term_by('slug', $location_slug, 'locations');
            if ($location && !is_wp_error($location)) {
                $this->current_location = $location;
                return $this->current_location;
            }
        }

        $location_id = 0;

        // 1. PRIORITY: Check URL parameter first (for SEO and Google crawling)
        //    This allows URLs like: /product/item/?location=mumbai
        if (isset($_GET['location'])) {
            $location_param = sanitize_text_field($_GET['location']);
            
            // Check if it's a numeric ID or a slug
            if (is_numeric($location_param)) {
                $location_id = intval($location_param);
            } else {
                // Try to find location by slug
                $term = get_term_by('slug', $location_param, 'locations');
                if ($term && !is_wp_error($term)) {
                    $location_id = $term->term_id;
                }
            }
        }

        // 2. FALLBACK: Check cookie for selected location (user preference)
        if ($location_id === 0 && isset($_COOKIE['wcmlim_selected_location_termid'])) {
            $location_id = intval($_COOKIE['wcmlim_selected_location_termid']);
        }

        // 3. DEFAULT: Check for site-wide default location setting
        if ($location_id === 0) {
            $default_location = get_option('wcmlim_default_location', 0);
            if ($default_location > 0) {
                $location_id = intval($default_location);
            }
        }
        
        // Get the location term
        if ($location_id > 0) {
            $term = get_term($location_id, 'locations');
            if ($term && !is_wp_error($term)) {
                $this->current_location = $term;
                return $this->current_location;
            }
        }

        return null;
    }

    /**
     * Output SEO meta tags for location pages
     */
    public function output_location_seo_tags() {
        if (!$this->is_seo_enabled()) {
            return;
        }

        $location = $this->get_current_location();
        if (!$location) {
            return;
        }

        // Get custom meta or generate from template
        $meta_title = $this->get_location_meta_title($location);
        $meta_description = $this->get_location_meta_description($location);
        $canonical_url = $this->get_location_canonical_url($location);

        // Output meta title
        if ($meta_title && !is_single() && !is_page()) {
            echo '<title>' . esc_html($meta_title) . '</title>' . "\n";
        }

        // Output meta description
        if ($meta_description) {
            echo '<meta name="description" content="' . esc_attr($meta_description) . '">' . "\n";
        }

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

        // Output OpenGraph tags
        $this->output_opengraph_tags($location);

        // Output Twitter Card tags
        $this->output_twitter_card_tags($location);
    }

    /**
     * Get location meta title
     */
    private function get_location_meta_title($location) {
        // Check for custom meta title
        $custom_title = get_term_meta($location->term_id, 'wcmlim_meta_title', true);
        if (!empty($custom_title)) {
            return $custom_title;
        }

        // Generate from template
        $template = get_option('wcmlim_meta_title_template', '%location_name% - %site_name%');
        return $this->parse_template($template, $location);
    }

    /**
     * Get location meta description
     */
    private function get_location_meta_description($location) {
        // Check for custom meta description
        $custom_description = get_term_meta($location->term_id, 'wcmlim_meta_description', true);
        if (!empty($custom_description)) {
            return $custom_description;
        }

        // Generate from template
        $template = get_option('wcmlim_meta_desc_template', 'Visit our %location_name% store. Find products near you with local inventory and pickup options.');
        return $this->parse_template($template, $location);
    }

    /**
     * Get canonical URL for location
     */
    private function get_location_canonical_url($location) {
        // Check for custom canonical
        $custom_canonical = get_term_meta($location->term_id, 'wcmlim_canonical_url', true);
        if (!empty($custom_canonical)) {
            return $custom_canonical;
        }

        // Generate default canonical
        return get_term_link($location);
    }

    /**
     * Parse template variables
     */
    private function parse_template($template, $location) {
        $replacements = array(
            '%location_name%' => $location->name,
            '%site_name%' => get_bloginfo('name'),
            '%site_description%' => get_bloginfo('description'),
            '%location_city%' => get_term_meta($location->term_id, 'location_city', true),
            '%location_state%' => get_term_meta($location->term_id, 'location_state', true),
            '%location_country%' => get_term_meta($location->term_id, 'location_country', true),
        );

        return str_replace(array_keys($replacements), array_values($replacements), $template);
    }

    /**
     * Output OpenGraph tags
     */
    private function output_opengraph_tags($location) {
        $og_title = $this->get_location_meta_title($location);
        $og_description = $this->get_location_meta_description($location);
        $og_url = get_term_link($location);
        $og_image = get_term_meta($location->term_id, 'location_image', true);

        echo '<meta property="og:title" content="' . esc_attr($og_title) . '">' . "\n";
        echo '<meta property="og:description" content="' . esc_attr($og_description) . '">' . "\n";
        echo '<meta property="og:type" content="business.business">' . "\n";
        echo '<meta property="og:url" content="' . esc_url($og_url) . '">' . "\n";
        
        if ($og_image) {
            echo '<meta property="og:image" content="' . esc_url($og_image) . '">' . "\n";
        }

        echo '<meta property="og:site_name" content="' . esc_attr(get_bloginfo('name')) . '">' . "\n";
    }

    /**
     * Output Twitter Card tags
     */
    private function output_twitter_card_tags($location) {
        $twitter_title = $this->get_location_meta_title($location);
        $twitter_description = $this->get_location_meta_description($location);
        $twitter_image = get_term_meta($location->term_id, 'location_image', true);

        echo '<meta name="twitter:card" content="summary_large_image">' . "\n";
        echo '<meta name="twitter:title" content="' . esc_attr($twitter_title) . '">' . "\n";
        echo '<meta name="twitter:description" content="' . esc_attr($twitter_description) . '">' . "\n";
        
        if ($twitter_image) {
            echo '<meta name="twitter:image" content="' . esc_url($twitter_image) . '">' . "\n";
        }
    }

    /**
     * Output Schema.org structured data
     */
    public function output_location_schema() {
        if (!$this->is_structured_data_enabled()) {
            return;
        }

        $location = $this->get_current_location();
        if (!$location) {
            return;
        }

        $schema = $this->generate_local_business_schema($location);
        
        if ($schema) {
            echo '<script type="application/ld+json">' . "\n";
            echo wp_json_encode($schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . "\n";
            echo '</script>' . "\n";
        }

        // Output breadcrumb schema if enabled
        if (get_option('wcmlim_breadcrumbs_enabled', 'on') === 'on') {
            $breadcrumb_schema = $this->generate_breadcrumb_schema($location);
            if ($breadcrumb_schema) {
                echo '<script type="application/ld+json">' . "\n";
                echo wp_json_encode($breadcrumb_schema, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . "\n";
                echo '</script>' . "\n";
            }
        }
    }

    /**
     * Generate LocalBusiness schema markup
     */
    public function generate_local_business_schema($location) {
        $schema_type = get_term_meta($location->term_id, 'wcmlim_schema_type', true);
        if (empty($schema_type)) {
            $schema_type = 'Store'; // Changed from LocalBusiness to Store
        }

        // Get location data with correct meta keys
        $address_line1 = get_term_meta($location->term_id, 'wcmlim_location', true);
        $street_number = get_term_meta($location->term_id, 'wcmlim_street_number', true);
        $route = get_term_meta($location->term_id, 'wcmlim_route', true);
        $city = get_term_meta($location->term_id, 'wcmlim_locality', true);
        $state = get_term_meta($location->term_id, 'wcmlim_administrative_area_level_1', true);
        $postcode = get_term_meta($location->term_id, 'wcmlim_postal_code', true);
        $country = get_term_meta($location->term_id, 'wcmlim_country', true);
        $latitude = get_term_meta($location->term_id, 'wcmlim_lat', true);
        $longitude = get_term_meta($location->term_id, 'wcmlim_lng', true);
        $phone = get_term_meta($location->term_id, 'wcmlim_phone', true);
        $email = get_term_meta($location->term_id, 'wcmlim_email', true);
        $start_time = get_term_meta($location->term_id, 'wcmlim_start_time', true);
        $end_time = get_term_meta($location->term_id, 'wcmlim_end_time', true);

        // Build street address
        $street_address = trim($street_number . ' ' . $route);
        if (empty($street_address)) {
            $street_address = $address_line1;
        }

        // Base schema
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => $schema_type,
            'name' => $location->name,
            'url' => get_term_link($location),
        );

        // Add address
        if ($city || $state || $postcode || $country) {
            $schema['address'] = array(
                '@type' => 'PostalAddress',
            );
            
            if ($street_address) {
                $schema['address']['streetAddress'] = $street_address;
            }
            if ($city) {
                $schema['address']['addressLocality'] = $city;
            }
            if ($state) {
                $schema['address']['addressRegion'] = $state;
            }
            if ($postcode) {
                $schema['address']['postalCode'] = $postcode;
            }
            if ($country) {
                $schema['address']['addressCountry'] = $country;
            }
        }

        // Add geo coordinates
        if ($latitude && $longitude) {
            $schema['geo'] = array(
                '@type' => 'GeoCoordinates',
                'latitude' => $latitude,
                'longitude' => $longitude,
            );
        }

        // Add contact info
        if ($phone) {
            $schema['telephone'] = $phone;
        }
        if ($email) {
            $schema['email'] = $email;
        }

        // Add opening hours
        if ($start_time && $end_time) {
            $schema['openingHoursSpecification'] = array(
                '@type' => 'OpeningHoursSpecification',
                'dayOfWeek' => array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'),
                'opens' => $start_time,
                'closes' => $end_time,
            );
        }

        // Add price range if specified
        $price_range = get_term_meta($location->term_id, 'wcmlim_schema_price_range', true);
        if ($price_range) {
            $schema['priceRange'] = $price_range;
        }

        // Add location image
        $location_image = get_term_meta($location->term_id, 'location_image', true);
        if ($location_image) {
            $schema['image'] = $location_image;
        }

        return $schema;
    }

    /**
     * Generate breadcrumb schema
     */
    public function generate_breadcrumb_schema($location) {
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => 'BreadcrumbList',
            'itemListElement' => array(),
        );

        // Home
        $schema['itemListElement'][] = array(
            '@type' => 'ListItem',
            'position' => 1,
            'name' => 'Home',
            'item' => home_url(),
        );

        // Locations archive
        $schema['itemListElement'][] = array(
            '@type' => 'ListItem',
            'position' => 2,
            'name' => 'Locations',
            'item' => home_url('/locations/'),
        );

        // Current location
        $schema['itemListElement'][] = array(
            '@type' => 'ListItem',
            'position' => 3,
            'name' => $location->name,
            'item' => get_term_link($location),
        );

        return $schema;
    }

    /**
     * Generate Organization schema for site
     */
    public function generate_organization_schema() {
        $schema = array(
            '@context' => 'https://schema.org',
            '@type' => 'Organization',
            'name' => get_bloginfo('name'),
            'url' => home_url(),
        );

        $logo = get_option('wcmlim_seo_organization_logo');
        if ($logo) {
            $schema['logo'] = $logo;
        }

        return $schema;
    }
}
