<?php
/**
 * WCMLIM Location Template Handler
 *
 * Handles custom URLs for location pages and integrates with WordPress templates
 *
 * @link       http://www.techspawn.com
 * @since      1.0.0
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/includes
 */

/**
 * Location template handler for custom URLs and template loading
 *
 * Creates custom URL structure for location pages like /locations/mumbai/
 * and handles template loading for location archives.
 *
 * @package    Wcmlim
 * @subpackage Wcmlim/includes
 * @author     techspawn1 <contact@techspawn.com>
 */
class WCMLIM_Location_Template_Handler {

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

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

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

        // Register rewrite rules
        add_action('init', array($this, 'register_rewrite_rules'));
        
        // Add query vars
        add_filter('query_vars', array($this, 'add_query_vars'));
        
        // Template loading
        add_filter('template_include', array($this, 'load_location_template'));
        
        // Modify page title
        add_filter('wp_title', array($this, 'modify_location_title'), 10, 2);
        add_filter('document_title_parts', array($this, 'modify_location_title_parts'));
        
        // Modify main query for location archives
        add_action('pre_get_posts', array($this, 'modify_location_query'));
    }

    /**
     * Register custom rewrite rules for location URLs
     */
    public function register_rewrite_rules() {
        // Single location page: /locations/mumbai/
        add_rewrite_rule(
            '^locations/([^/]+)/?$',
            'index.php?location_slug=$matches[1]&location_archive=1',
            'top'
        );
        
        // Location with pagination: /locations/mumbai/page/2/
        add_rewrite_rule(
            '^locations/([^/]+)/page/([0-9]+)/?$',
            'index.php?location_slug=$matches[1]&location_archive=1&paged=$matches[2]',
            'top'
        );
    }

    /**
     * Add custom query vars
     */
    public function add_query_vars($vars) {
        $vars[] = 'location_slug';
        $vars[] = 'location_archive';
        return $vars;
    }

    /**
     * Load location template
     */
    public function load_location_template($template) {
        // Check if this is a location archive page
        if (get_query_var('location_archive') && get_query_var('location_slug')) {
            $location_slug = get_query_var('location_slug');
            
            // Verify location exists
            $location = get_term_by('slug', $location_slug, 'locations');
            
            if ($location && !is_wp_error($location)) {
                // Look for template in theme first, then plugin
                $theme_template = locate_template(array(
                    'wcmlim-location-archive.php',
                    'archive-location.php',
                    'location-archive.php'
                ));
                
                if ($theme_template) {
                    return $theme_template;
                }
                
                // Use plugin template
                $plugin_template = plugin_dir_path(dirname(__FILE__)) . 'includes/templates/location-archive.php';
                
                if (file_exists($plugin_template)) {
                    return $plugin_template;
                }
            }
        }
        
        return $template;
    }

    /**
     * Modify page title for location archives
     */
    public function modify_location_title($title, $sep = '|') {
        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)) {
                $custom_title = get_term_meta($location->term_id, 'wcmlim_meta_title', true);
                
                if (!empty($custom_title)) {
                    return $custom_title;
                }
                
                return $location->name . ' ' . $sep . ' ' . get_bloginfo('name');
            }
        }
        
        return $title;
    }

    /**
     * Modify document title parts for location archives
     */
    public function modify_location_title_parts($title_parts) {
        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)) {
                $custom_title = get_term_meta($location->term_id, 'wcmlim_meta_title', true);
                
                if (!empty($custom_title)) {
                    $title_parts['title'] = $custom_title;
                } else {
                    $title_parts['title'] = $location->name;
                }
            }
        }
        
        return $title_parts;
    }

    /**
     * Modify main query for location archives
     */
    public function modify_location_query($query) {
        // Only modify main query on location archives
        if (!is_admin() && $query->is_main_query() && get_query_var('location_archive')) {
            $location_slug = get_query_var('location_slug');
            $location = get_term_by('slug', $location_slug, 'locations');
            
            if ($location && !is_wp_error($location)) {
                // Get products that have stock in this location
                $products_in_location = $this->get_products_in_location($location->term_id);
                
                if (!empty($products_in_location)) {
                    // Query products
                    $query->set('post_type', 'product');
                    $query->set('posts_per_page', 12);
                    $query->set('post__in', $products_in_location);
                    $query->set('orderby', 'post__in');
                } else {
                    // No products in this location
                    $query->set('post_type', 'product');
                    $query->set('post__in', array(0)); // Force empty result
                }
            }
        }
    }

    /**
     * Get products that have stock in a specific location
     */
    private function get_products_in_location($location_id) {
        global $wpdb;
        
        // Query products that have stock data for this location
        $meta_key = 'wcmlim_stock_at_' . $location_id;
        
        $query = $wpdb->prepare("
            SELECT DISTINCT post_id 
            FROM {$wpdb->postmeta} 
            WHERE meta_key = %s
            AND CAST(meta_value AS SIGNED) > 0
            ORDER BY post_id DESC
        ", $meta_key);
        
        $product_ids = $wpdb->get_col($query);
        
        return !empty($product_ids) ? $product_ids : array();
    }

    /**
     * Flush rewrite rules on activation
     */
    public static function flush_rewrite_rules() {
        flush_rewrite_rules();
    }
}
