<?php
defined('WPINC') or die;

class ATMCEVNTS_Event_Query_Service {
    
    public function __construct() {
        // Initialize service
    }
    
    /**
     * Get events based on query parameters
     * 
     * @param array $query_params Query parameters
     * @return array Array of ATMCEVNTS_Event_Model objects
     */
    public function get_events($query_params = []) {
        // Default parameters
        $defaults = array(
            'filter' => 'future',
            'max' => 20,
            'featured' => null,
            'skip_first_x' => 0,
            'skip_first_x_featured' => 0,
            'order' => 'ASC',
            'paged' => 1,
            'posts_per_page' => 20
        );
        
        $params = wp_parse_args($query_params, $defaults);
        
        // Generate cache key
        $cache_key = 'atomic_events_query_' . md5(serialize($params));
        
        // Check cache first
        $cached_result = get_transient($cache_key);
        if ($cached_result !== false) {
            return $cached_result;
        }
        
        // Build query arguments
        $args = $this->build_query_args($params);
        
        // Execute query
        $events_query = new WP_Query($args);
        
        // Process results
        $events = $this->process_query_results($events_query, $params);
        
        /**
         * Filter the final event results before caching and returning
         * 
         * @param array $events Array of ATMCEVNTS_Event_Model objects
         * @param array $params The query parameters used
         */
        $events = apply_filters('atomic_events_query_results', $events, $params);
        
        // Prepare pagination data
        $pagination = $this->get_pagination_data($events_query, $params);
        
        // Prepare result array
        $result = array(
            'events' => $events,
            'pagination' => $pagination
        );
        
        // Cache results for 1 hour
        set_transient($cache_key, $result, HOUR_IN_SECONDS);
        
        // Track this transient key for cache clearing
        $this->track_transient_key($cache_key);
        
        return $result;
    }
    
    /**
     * Build WP_Query arguments from parameters
     * 
     * @param array $params Query parameters
     * @return array WP_Query arguments
     */
    private function build_query_args($params) {
        // Validate and sanitize the order attribute
        $order = strtoupper($params['order']);
        if ($order !== 'ASC' && $order !== 'DESC') {
            $order = 'ASC';
        }
        
        $args = array(
            'post_type' => 'atomic-event',
            'post_status' => 'publish',
            'posts_per_page' => $params['posts_per_page'],
            'meta_query' => array(
                'relation' => 'AND',
                array(
                    'key' => 'event_start_date',
                    'value' => gmdate('Y-m-d'),
                    'compare' => ($params['filter'] === 'future') ? '>=' : '<',
                    'type' => 'DATE'
                ),
                array(
                    'relation' => 'OR',
                    array(
                        'key' => 'event_hide_from_listings',
                        'compare' => 'NOT EXISTS'
                    ),
                    array(
                        'key' => 'event_hide_from_listings',
                        'value' => '1',
                        'compare' => '!='
                    )
                )
            ),
            'orderby' => 'meta_value',
            'meta_key' => 'event_start_date',
            'order' => $order
        );
        
        // Add featured filter if specified
        if ($params['featured'] !== null) {
            $featured_value = filter_var($params['featured'], FILTER_VALIDATE_BOOLEAN);
            $args['meta_query'][] = array(
                'key' => 'event_featured',
                'value' => $featured_value ? '1' : '0',
                'compare' => '=',
            );
        }
        
        // Add pagination support
        $paged = intval($params['paged']);
        if ($paged > 1) {
            $args['paged'] = $paged;
        }
        
        // Add offset for skip_first_x (only if not using pagination)
        $skip_first_x = intval($params['skip_first_x']);
        if ($skip_first_x > 0 && $paged <= 1) {
            $args['offset'] = $skip_first_x;
        }
        
        return $args;
    }
    
    /**
     * Process query results and apply filters
     * 
     * @param WP_Query $events_query Query object
     * @param array $params Original query parameters
     * @return array Array of ATMCEVNTS_Event_Model objects
     */
    private function process_query_results($events_query, $params) {
        $events = array();
        $featured_counter = 0;
        
        if ($events_query->have_posts()) {
            while ($events_query->have_posts()) {
                $events_query->the_post();
                $event_model = new ATMCEVNTS_Event_Model(get_the_ID());
                

                
                // Skip if members only and condition not met
                if (empty(ATMCEVNTS_Member_Utils::should_show_in_list($event_model))) {
                    continue;
                }
                
                // Handle skip_first_x_featured
                if ($event_model->is_featured()) {
                    $featured_counter++;
                }
                
                $skip_first_x_featured = intval($params['skip_first_x_featured']);
                if (!empty($skip_first_x_featured) && $event_model->is_featured()) {
                    if ($featured_counter <= $skip_first_x_featured) {
                        continue;
                    }
                }
                
                $events[] = $event_model;
            }
            
            wp_reset_postdata();
        }
        
        return $events;
    }
    
    /**
     * Get pagination data from WP_Query
     * 
     * @param WP_Query $events_query Query object
     * @param array $params Original query parameters
     * @return array Pagination data
     */
    private function get_pagination_data($events_query, $params) {
        $current_page = intval($params['paged']);
        $posts_per_page = intval($params['posts_per_page']);
        $total_posts = $events_query->found_posts;
        $total_pages = ceil($total_posts / $posts_per_page);
        
        return array(
            'current_page' => $current_page,
            'posts_per_page' => $posts_per_page,
            'total_posts' => $total_posts,
            'total_pages' => $total_pages,
            'has_next_page' => $current_page < $total_pages,
            'has_prev_page' => $current_page > 1,
            'next_page' => $current_page < $total_pages ? $current_page + 1 : null,
            'prev_page' => $current_page > 1 ? $current_page - 1 : null
        );
    }
    
    /**
     * Get featured events
     * 
     * @param array $params Additional parameters
     * @return array Array of featured events
     */
    public function get_featured_events($params = []) {
        $params['featured'] = true;
        $result = $this->get_events($params);
        return $result['events'];
    }
    
    /**
     * Get future events
     * 
     * @param array $params Additional parameters
     * @return array Array of future events
     */
    public function get_future_events($params = []) {
        $params['filter'] = 'future';
        $result = $this->get_events($params);
        return $result['events'];
    }
    
    /**
     * Get past events
     * 
     * @param array $params Additional parameters
     * @return array Array of past events
     */
    public function get_past_events($params = []) {
        $params['filter'] = 'past';
        $result = $this->get_events($params);
        return $result['events'];
    }
    
    /**
     * Get events with pagination data
     * 
     * @param array $params Query parameters
     * @return array Array with 'events' and 'pagination' keys
     */
    public function get_events_with_pagination($params = []) {
        return $this->get_events($params);
    }
    
    /**
     * Clear all event query cache
     */
    public function clear_cache() {
        // Get all transients that start with 'atomic_events_query_'
        $transients = wp_cache_get('atomic_events_query_transients', 'atomic_events');
        
        if ($transients === false) {
            // If not cached, get them from options
            $transients = get_option('atomic_events_query_transients', array());
        }
        
        // Delete each transient
        foreach ($transients as $transient_key) {
            delete_transient($transient_key);
        }
        
        // Clear the transient list
        delete_option('atomic_events_query_transients');
        wp_cache_delete('atomic_events_query_transients', 'atomic_events');
    }
    
    /**
     * Track a transient key for cache clearing
     * 
     * @param string $transient_key The transient key to track
     */
    private function track_transient_key($transient_key) {
        $transients = get_option('atomic_events_query_transients', array());
        
        if (!in_array($transient_key, $transients)) {
            $transients[] = $transient_key;
            update_option('atomic_events_query_transients', $transients);
        }
        
        // Also cache it for faster access
        wp_cache_set('atomic_events_query_transients', $transients, 'atomic_events');
    }
    
}
