<?php
/**
 * Toronto Filter Integration for SearchingInToronto IDX - FIXED
 * File: Filters/searchingintoronto-toronto-filter.php
 * RESO Web API v4.0 Compliant Integration
 * Hook Integration: CORRECTED to match main plugin
 */

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

class SearchingInToronto_Toronto_Filter {
    
    /**
     * Initialize integration with main SearchingInToronto_IDX plugin - FIXED
     */
    public function __construct() {
        // FIXED: Hook into main plugin's correct hook structure
        add_action('trreb_render_search_form_content', array($this, 'render_toronto_search_form'), 15);
        add_filter('trreb_search_parameters', array($this, 'process_toronto_search_parameters'), 10, 1);
        add_filter('trreb_build_api_filter', array($this, 'build_toronto_reso_filter'), 15, 2);
        
        // Enqueue assets conditionally
        add_action('wp_enqueue_scripts', array($this, 'enqueue_toronto_assets'), 25);
    }
    
    /**
     * FIXED: Render Toronto filter using correct hook signature
     */
    public function render_toronto_search_form($args = array()) {
        // Check if Toronto filter is enabled
        if (get_option('toronto_filter_enabled', 'true') !== 'true') {
            return;
        }
        
        $toronto_areas = $this->get_toronto_neighborhoods_reso();
        ?>
        <div class="toronto-filter-wrapper filter-container-base" id="toronto-filter-wrapper" data-reso-filter="CityRegion">
            <div class="filter-header-base">
                <h4>Toronto Neighborhoods (STRING 1)</h4>
                <span class="filter-toggle">▼</span>
            </div>
            
            <div class="filter-content-base">
                <!-- RESO Field Info -->
                <div class="reso-integration-status">
                    <span class="reso-status-indicator">✅</span>
                    <span>RESO Fields: CityRegion, PostalCode, StateOrProvince</span>
                </div>
                
                <!-- Quick Search -->
                <div class="toronto-search-container">
                    <label for="toronto-search-input">Search Toronto Neighborhoods</label>
                    <input type="text" 
                           id="toronto-search-input" 
                           class="toronto-search-input"
                           placeholder="Search neighborhoods..."
                           data-reso-field="CityRegion">
                    <div id="toronto-suggestions" class="suggestions-dropdown" style="display: none;"></div>
                </div>
                
                <!-- Toronto Areas Grid -->
                <div class="toronto-areas-grid">
                    <?php foreach ($toronto_areas as $area_key => $area_data): ?>
                        <div class="area-group" data-area="<?php echo $area_key; ?>" data-reso-region="<?php echo esc_attr($area_data['reso_region']); ?>">
                            <div class="area-header">
                                <label class="area-label">
                                    <input type="checkbox" class="area-master-checkbox" data-area="<?php echo $area_key; ?>">
                                    <span>
                                        <strong><?php echo $area_data['name']; ?></strong>
                                        <small>(<?php echo count($area_data['neighborhoods']); ?> areas)</small>
                                    </span>
                                </label>
                                <button type="button" class="area-expand-btn" data-area="<?php echo $area_key; ?>">▼</button>
                            </div>
                            
                            <div class="area-neighborhoods" id="<?php echo $area_key; ?>-neighborhoods" style="display: none;">
                                <?php foreach ($area_data['neighborhoods'] as $neighborhood): ?>
                                    <label class="neighborhood-option">
                                        <input type="checkbox" 
                                               name="toronto_neighborhoods[]" 
                                               value="<?php echo esc_attr($neighborhood['name']); ?>"
                                               data-area="<?php echo $area_key; ?>"
                                               data-reso-value="<?php echo esc_attr($neighborhood['reso_name']); ?>"
                                               data-postal-codes="<?php echo esc_attr(implode(',', $neighborhood['postal_codes'])); ?>"
                                               class="neighborhood-checkbox">
                                        <span>
                                            <?php echo $neighborhood['name']; ?>
                                            <small><?php echo implode(', ', array_slice($neighborhood['postal_codes'], 0, 2)); ?><?php echo count($neighborhood['postal_codes']) > 2 ? '...' : ''; ?></small>
                                        </span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Actions -->
                <div class="toronto-actions">
                    <button type="button" id="clear-toronto" class="btn-secondary">Clear All</button>
                    <button type="button" id="apply-toronto" class="btn-primary">Apply Toronto Filter</button>
                </div>
                
                <!-- Selection Summary -->
                <div class="toronto-selection-summary">
                    <span id="toronto-selected-count">0 neighborhoods selected</span>
                </div>
            </div>
        </div>
        
        <!-- Hidden fields for form integration -->
        <input type="hidden" name="toronto_neighborhoods_selected" id="toronto-neighborhoods-hidden" value="">
        <input type="hidden" name="toronto_reso_filters" id="toronto-reso-hidden" value="">
        <input type="hidden" name="toronto_postal_codes" id="toronto-postal-hidden" value="">
        <?php
    }
    
    /**
     * FIXED: Process Toronto parameters using correct signature
     */
    public function process_toronto_search_parameters($params) {
        // Check for Toronto neighborhood selections
        if (isset($_POST['toronto_neighborhoods_selected']) && !empty($_POST['toronto_neighborhoods_selected'])) {
            $selected_neighborhoods = json_decode(sanitize_text_field($_POST['toronto_neighborhoods_selected']), true);
            
            if (!empty($selected_neighborhoods)) {
                $params['toronto_neighborhoods'] = $selected_neighborhoods;
                
                // Add RESO location data
                $reso_filters = $this->build_reso_location_filters($selected_neighborhoods);
                if (!empty($reso_filters)) {
                    $params['toronto_reso_filters'] = $reso_filters;
                }
            }
        }
        
        return $params;
    }
    
    /**
     * FIXED: Build Toronto RESO filter using correct signature
     */
    public function build_toronto_reso_filter($existing_filter, $search_params) {
        $toronto_filters = array();
        
        // Always include Ontario province for Toronto searches
        $toronto_filters[] = "StateOrProvince eq 'ON'";
        
        if (!empty($search_params['toronto_neighborhoods'])) {
            $reso_filters = $this->build_reso_location_filters($search_params['toronto_neighborhoods']);
            
            if (!empty($reso_filters['city_region'])) {
                $toronto_filters[] = $reso_filters['city_region'];
            }
            
            if (!empty($reso_filters['postal_code'])) {
                $toronto_filters[] = $reso_filters['postal_code'];
            }
        }
        
        // Combine with existing filters
        if (!empty($toronto_filters)) {
            if (!empty($existing_filter)) {
                return $existing_filter . ' and (' . implode(' and ', $toronto_filters) . ')';
            } else {
                return implode(' and ', $toronto_filters);
            }
        }
        
        return $existing_filter;
    }
    
    /**
     * Get Toronto neighborhoods data with RESO mapping
     */
    private function get_toronto_neighborhoods_reso() {
        return array(
            'downtown' => array(
                'name' => 'Downtown Toronto',
                'reso_region' => 'Toronto-Downtown',
                'neighborhoods' => array(
                    array(
                        'name' => 'Financial District',
                        'reso_name' => 'Toronto-Financial',
                        'postal_codes' => array('M5H', 'M5J', 'M5K')
                    ),
                    array(
                        'name' => 'Entertainment District',
                        'reso_name' => 'Toronto-Entertainment',
                        'postal_codes' => array('M5V', 'M6K')
                    ),
                    array(
                        'name' => 'St. Lawrence',
                        'reso_name' => 'Toronto-StLawrence',
                        'postal_codes' => array('M5E', 'M5A')
                    ),
                    array(
                        'name' => 'Distillery District',
                        'reso_name' => 'Toronto-Distillery',
                        'postal_codes' => array('M5A')
                    )
                )
            ),
            'midtown' => array(
                'name' => 'Midtown Toronto',
                'reso_region' => 'Toronto-Midtown',
                'neighborhoods' => array(
                    array(
                        'name' => 'Yorkville',
                        'reso_name' => 'Toronto-Yorkville',
                        'postal_codes' => array('M5R', 'M4W')
                    ),
                    array(
                        'name' => 'Rosedale',
                        'reso_name' => 'Toronto-Rosedale',
                        'postal_codes' => array('M4W', 'M5R')
                    ),
                    array(
                        'name' => 'Annex',
                        'reso_name' => 'Toronto-Annex',
                        'postal_codes' => array('M5S', 'M5R')
                    )
                )
            ),
            'east_end' => array(
                'name' => 'East End Toronto',
                'reso_region' => 'Toronto-East',
                'neighborhoods' => array(
                    array(
                        'name' => 'The Beaches',
                        'reso_name' => 'Toronto-Beaches',
                        'postal_codes' => array('M4E', 'M4L')
                    ),
                    array(
                        'name' => 'Leslieville',
                        'reso_name' => 'Toronto-Leslieville',
                        'postal_codes' => array('M4M', 'M4L')
                    ),
                    array(
                        'name' => 'Riverdale',
                        'reso_name' => 'Toronto-Riverdale',
                        'postal_codes' => array('M4M', 'M4K')
                    )
                )
            ),
            'west_end' => array(
                'name' => 'West End Toronto',
                'reso_region' => 'Toronto-West',
                'neighborhoods' => array(
                    array(
                        'name' => 'Liberty Village',
                        'reso_name' => 'Toronto-LibertyVillage',
                        'postal_codes' => array('M6K', 'M6H')
                    ),
                    array(
                        'name' => 'King West',
                        'reso_name' => 'Toronto-KingWest',
                        'postal_codes' => array('M5V', 'M6J')
                    ),
                    array(
                        'name' => 'Junction Triangle',
                        'reso_name' => 'Toronto-JunctionTriangle',
                        'postal_codes' => array('M6H', 'M6J')
                    )
                )
            ),
            'north_york' => array(
                'name' => 'North York',
                'reso_region' => 'Toronto-NorthYork',
                'neighborhoods' => array(
                    array(
                        'name' => 'Willowdale',
                        'reso_name' => 'Toronto-Willowdale',
                        'postal_codes' => array('M2N', 'M2M')
                    ),
                    array(
                        'name' => 'North York Centre',
                        'reso_name' => 'Toronto-NorthYorkCentre',
                        'postal_codes' => array('M2M', 'M2N')
                    )
                )
            )
        );
    }
    
    /**
     * Build RESO-compliant location filters
     */
    private function build_reso_location_filters($neighborhoods) {
        $filters = array();
        $postal_codes = array();
        
        // Get RESO data for selected neighborhoods
        $toronto_data = $this->get_toronto_neighborhoods_reso();
        
        foreach ($neighborhoods as $neighborhood_name) {
            // Find neighborhood in RESO data
            foreach ($toronto_data as $area_data) {
                foreach ($area_data['neighborhoods'] as $neighborhood) {
                    if ($neighborhood['name'] === $neighborhood_name) {
                        // Add RESO CityRegion filter
                        $reso_name = $neighborhood['reso_name'];
                        $filters['city_region'][] = "CityRegion eq '" . $this->escape_odata_string($reso_name) . "'";
                        
                        // Collect postal codes
                        $postal_codes = array_merge($postal_codes, $neighborhood['postal_codes']);
                        break 2;
                    }
                }
            }
        }
        
        // Build final RESO filters
        $result = array();
        
        if (!empty($filters['city_region'])) {
            $result['city_region'] = '(' . implode(' or ', $filters['city_region']) . ')';
        }
        
        if (!empty($postal_codes)) {
            $postal_filters = array();
            foreach (array_unique($postal_codes) as $postal) {
                $postal_filters[] = "PostalCode eq '" . $this->escape_odata_string($postal) . "'";
            }
            $result['postal_code'] = '(' . implode(' or ', $postal_filters) . ')';
        }
        
        return $result;
    }
    
    /**
     * Escape OData string values for RESO API
     */
    private function escape_odata_string($string) {
        return str_replace("'", "''", $string);
    }
    
    /**
     * Enqueue Toronto assets conditionally - FIXED
     */
    public function enqueue_toronto_assets() {
        global $post;
        if (is_a($post, 'WP_Post') && has_shortcode($post->post_content, 'searchingintoronto_idx')) {
            // No separate CSS needed - uses main plugin CSS classes
            
            // Add inline JavaScript that integrates with main plugin
            add_action('wp_footer', array($this, 'add_toronto_javascript'));
        }
    }
    
    /**
     * FIXED: Enqueue external JavaScript file
     */
    public function add_toronto_javascript() {
        // JavaScript is now in external file - no inline code needed
    }
}

// Initialize Toronto Filter component
new SearchingInToronto_Toronto_Filter();

?>