<?php

class agile_tix_post_type
{

    private $agile_tix;
    private $version;

    public function __construct($agile_tix, $version)
    {
        $this->agile_tix = $agile_tix;
        $this->version = $version;
    }


    function register_agile_custom_post_type()
    {
        register_post_type(
            'agile_post',
            array(
                'labels' => array(
                    'name' => __('AgileTix Shows', 'textdomain'),
                    'singular_name' => __('AgileTix Show', 'textdomain'),
                    'add_new' => 'Add New',
                ),
                'public' => true,
                'has_archive' => true,
                'menu_icon' => 'dashicons-tickets-alt',
                'rewrite' => array('slug' => 'custom-posts'),
                'supports' => array(
                    'title',
                    'editor',
                    'custom-fields',
                    //'author',
                    'thumbnail',
                    //'excerpt',
                    //'trackbacks',
                    //'comments',
                    //'revisions',
                    'page-attributes',
                    'post-formats',
                ),
                //'taxonomies' => array( 'post_tag', 'Genre'),
                'template' => array(array('agile-post-template')),
                'template_lock' => true,
                //'rewrite'     => array( 'slug' => 'AgileTix' ), // my custom slug
            )
        );

        register_taxonomy('genre', 'agile_post', array(
            'label' => 'Genre',
            'hierarchical' => true,
            'capabilities' => array(
                'manage_terms' => 'manage_genre',
                'edit_terms' => 'edit_genre',
                'delete_terms' => 'delete_genre',
                'assign_terms' => 'assign_genre'
            )
        ));
        
        // Register coming soon feed
        add_feed('coming-soon', array($this, 'ats_coming_soon_feed'));
        
        // Add admin columns and filters for coming soon posts
        // Use admin_init to ensure post type is configured
        add_action('admin_init', array($this, 'ats_register_coming_soon_admin_features'));
    }
    
    /**
     * Register admin columns and filters for coming soon posts
     * Called on admin_init to ensure post type is configured
     */
    function ats_register_coming_soon_admin_features()
    {
        $postType = self::get_configured_post_type();
        if (empty($postType)) {
            return;
        }
        
        add_filter('manage_' . $postType . '_posts_columns', array($this, 'ats_add_coming_soon_column'));
        add_action('manage_' . $postType . '_posts_custom_column', array($this, 'ats_render_coming_soon_column'), 10, 2);
        add_filter('manage_edit-' . $postType . '_sortable_columns', array($this, 'ats_coming_soon_column_sortable'));
        add_action('restrict_manage_posts', array($this, 'ats_add_coming_soon_filter'));
        add_action('pre_get_posts', array($this, 'ats_filter_coming_soon_posts'));
        add_filter('posts_clauses', array($this, 'ats_modify_query_for_coming_soon_ordering'), 10, 2);
        
        // Add visual indicator in post edit screen
        add_action('edit_form_after_title', array($this, 'ats_show_coming_soon_indicator'));
    }

    function ats_add_custom_post_type_to_rss_feed($query)
    {
        if (($query->is_feed() || $query->is_home()) && $query->is_main_query()  ) {
            $post_types = $query->get('post_type');

            if (empty($post_types)) {
                $post_types = ['post'];
            }

            if (is_array($post_types)) {
                $post_types[] = 'agile_post';
            } else {
                $post_types = ['post', 'agile_post'];
            }

            $query->set('post_type', $post_types);
        }
    }


    function ats_add_metaboxes()
    {
        add_meta_box(
            'ats_eventID_meta',
            'Agile Event ID',
            'agile_tix_post_type::ats_meta_eventID_callback',
            "agile_post",
            "normal",
            "default",
            null
        );

        add_meta_box(
            'ats_CorpOrgName_meta',
            'Agile CorpOrgName',
            'agile_tix_post_type::ats_meta_CorpOrgName_callback',
            "agile_post",
            "normal",
            "default",
            null
        );
        add_meta_box(
            'ats_Name_meta',
            'Agile Name',
            'agile_tix_post_type::ats_meta_Name_callback',
            "agile_post",
            "normal",
            "default",
            null
        );
        add_meta_box(
            'ats_StartDate_meta',
            'Agile Start Date',
            'agile_tix_post_type::ats_meta_StartDate_callback',
            "agile_post",
            "normal",
            "default",
            null
        );
        add_meta_box(
            'ats_EndDate_meta',
            'Agile End Date',
            'agile_tix_post_type::ats_meta_EndDate_callback',
            "agile_post",
            "normal",
            "default",
            null
        );
        add_meta_box(
            'ats_Distributor_meta',
            'Agile Distributor',
            'agile_tix_post_type::ats_meta_Distributor_callback',
            "agile_post",
            "normal",
            "default",
            null
        );
    }


    static function ats_meta_eventID_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['EventID'];
        echo '<textarea style="width:100%" id="ats_eventID_meta_text" name="ats_eventID_meta_text">' . esc_attr($value) . '</textarea>';
    }
    static function ats_meta_CorpOrgName_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['CorpOrgName'];
        echo '<textarea style="width:100%" id="ats_CorpOrgName_meta_text" name="ats_CorpOrgName_meta_text">' . esc_attr($value) . '</textarea>';
    }
    static function ats_meta_Name_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['Name'];
        echo '<textarea style="width:100%" id="ats_Name_meta_text" name="ats_Name_meta_text">' . esc_attr($value) . '</textarea>';
    }
    static function ats_meta_StartDate_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['StartDate'];
        echo '<textarea style="width:100%" id="ats_StartDate_meta_text" name="ats_StartDate_meta_text">' . esc_attr($value) . '</textarea>';
    }
    static function ats_meta_EndDate_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['EndDate'];
        echo '<textarea style="width:100%" id="ats_EndDate_meta_text" name="ats_EndDate_meta_text">' . esc_attr($value) . '</textarea>';
    }
    static function ats_meta_Distributor_callback($post)
    {
        $event = get_post_meta($post->ID, 'ATS_Event', true);
        $value = $event['Distributor'];
        echo '<textarea style="width:100%" id="ats_Distributor_meta_text" name="ats_Distributor_meta_text">' . esc_attr($value) . '</textarea>';
    }

    static function agile_post_adjust_queries($query)
    {
        if (!is_admin() && is_post_type_archive('agile_post') && $query->is_main_query()) {
            $query->set('meta_key', 'event_date');
            $query->set('orderby', 'meta_value_num');
            $query->set('order', 'ASC');
            $query->set('meta_query', array(
                array(
                    'key' => 'event_date',
                    'compare' => '>=',
                    'value' => date('Ymd'),
                    'type' => 'numeric',
                )
            ));
        }
    }
    
    /**
     * Get the configured post type based on theme integration settings
     * 
     * @return string The post type to use
     */
    static function get_configured_post_type()
    {
        $themeType = get_option('agile_field_config_integration_type') ?? 'none';
        
        switch ($themeType) {
            case 'none':
                return 'agile_post';
                
            case 'event_champ':
                return 'event';
                
            case 'custom':
                $customPostType = get_option('agile_field_theme_custom_map_post_type');
                return !empty($customPostType) ? $customPostType : 'agile_post';
                
            case 'amy_movie':
                return 'amy_movie';
                
            default:
                return 'agile_post';
        }
    }
    
    /**
     * Handle the coming soon feed query
     * Filters posts to only show those with ATS_ComingSoonDate meta
     */
    function ats_coming_soon_feed_query($query)
    {
        if ($query->is_feed('coming-soon') && $query->is_main_query()) {
            // Get the configured post type from theme settings
            $postType = self::get_configured_post_type();
            $query->set('post_type', $postType);
            
            $meta_query = array(
                'relation' => 'AND',
                array(
                    'key' => 'ATS_ComingSoonDate',
                    'compare' => 'EXISTS',
                ),
            );
            
            $query->set('meta_query', $meta_query);
        }
    }
    
    /**
     * Render the coming soon feed
     */
    function ats_coming_soon_feed()
    {
        // Load the default WordPress RSS template
        load_template(ABSPATH . WPINC . '/feed-rss2.php');
    }
    
    /**
     * Add Coming Soon column to post list
     */
    function ats_add_coming_soon_column($columns)
    {
        $new_columns = array();
        foreach ($columns as $key => $value) {
            if ($key === 'date') {
                $new_columns['coming_soon'] = __('Coming Soon', 'agile');
            }
            $new_columns[$key] = $value;
        }
        // If date column doesn't exist, add it at the end
        if (!isset($new_columns['coming_soon'])) {
            $new_columns['coming_soon'] = __('Coming Soon', 'agile');
        }
        return $new_columns;
    }
    
    /**
     * Render Coming Soon column content
     */
    function ats_render_coming_soon_column($column, $post_id)
    {
        if ($column === 'coming_soon') {
            $comingSoonDate = get_post_meta($post_id, 'ATS_ComingSoonDate', true);
            if (!empty($comingSoonDate)) {
                echo '<span style="color: #2271b1; font-weight: bold;">Coming Soon</span>';
                echo '<br><small style="color: #666;">' . esc_html($comingSoonDate) . '</small>';
            } else {
                echo '<span style="color: #00a32a; font-weight: bold;">Now Showing</span>';
            }
        }
    }
    
    /**
     * Make Coming Soon column sortable
     */
    function ats_coming_soon_column_sortable($columns)
    {
        $columns['coming_soon'] = 'coming_soon';
        return $columns;
    }
    
    /**
     * Add Coming Soon filter dropdown
     */
    function ats_add_coming_soon_filter()
    {
        global $typenow;
        $postType = self::get_configured_post_type();
        
        if ($typenow === $postType) {
            $filter_value = isset($_GET['coming_soon_filter']) ? $_GET['coming_soon_filter'] : '';
            ?>
            <select name="coming_soon_filter" id="coming_soon_filter">
                <option value=""><?php _e('All Posts', 'agile'); ?></option>
                <option value="yes" <?php selected($filter_value, 'yes'); ?>><?php _e('Coming Soon Only', 'agile'); ?></option>
                <option value="no" <?php selected($filter_value, 'no'); ?>><?php _e('Now Showing', 'agile'); ?></option>
            </select>
            <?php
        }
    }
    
    /**
     * Filter posts by Coming Soon status
     */
    function ats_filter_coming_soon_posts($query)
    {
        global $pagenow, $typenow;
        $postType = self::get_configured_post_type();
        
        if (is_admin() && $pagenow === 'edit.php' && $typenow === $postType) {
            if (isset($_GET['coming_soon_filter']) && $_GET['coming_soon_filter'] !== '') {
                if ($_GET['coming_soon_filter'] === 'yes') {
                } elseif ($_GET['coming_soon_filter'] === 'no') {
                    $meta_query = $query->get('meta_query');
                    if (!is_array($meta_query)) {
                        $meta_query = array();
                    }
                    $meta_query[] = array(
                        'key' => 'ATS_ComingSoonDate',
                        'compare' => 'NOT EXISTS',
                    );
                    $query->set('meta_query', $meta_query);
                }
            }
            
           
            // Don't set meta_key/orderby here, let the posts_clauses filter handle it
        }
    }
    

    function ats_modify_query_for_coming_soon_ordering($clauses, $query)
    {
        global $pagenow, $typenow, $wpdb;
        $postType = self::get_configured_post_type();
        
        if (is_admin() && $pagenow === 'edit.php' && $typenow === $postType) {
            $is_filter_active = isset($_GET['coming_soon_filter']) && $_GET['coming_soon_filter'] === 'yes';
            $is_sorting_by_coming_soon = isset($_GET['orderby']) && $_GET['orderby'] === 'coming_soon';
            
            // Check if we should order coming soon first (either filter or sort)
            if ($is_filter_active || $is_sorting_by_coming_soon) {
                // Add LEFT JOIN for ComingSoonDate meta
                $join_alias = 'ats_coming_soon_meta';
                $meta_key = 'ATS_ComingSoonDate';
                
                // Check if join already exists
                if (strpos($clauses['join'], $join_alias) === false) {
                    $clauses['join'] .= " LEFT JOIN {$wpdb->postmeta} AS {$join_alias} ON ({$wpdb->posts}.ID = {$join_alias}.post_id AND {$join_alias}.meta_key = '{$meta_key}')";
                }
                
                if ($is_sorting_by_coming_soon) {
                    // Get the sort order (ASC or DESC)
                    $order = isset($_GET['order']) && strtoupper($_GET['order']) === 'DESC' ? 'DESC' : 'ASC';
                    
                    if ($order === 'ASC') {
                        // ASC: Coming soon posts first (sorted by date ASC), then now showing posts
                        $clauses['orderby'] = "CASE WHEN {$join_alias}.meta_value IS NOT NULL THEN 0 ELSE 1 END ASC, CASE WHEN {$join_alias}.meta_value IS NOT NULL THEN {$join_alias}.meta_value END ASC, " . $clauses['orderby'];
                    } else {
                        // DESC: Coming soon posts first (sorted by date DESC), then now showing posts
                        $clauses['orderby'] = "CASE WHEN {$join_alias}.meta_value IS NOT NULL THEN 0 ELSE 1 END ASC, CASE WHEN {$join_alias}.meta_value IS NOT NULL THEN {$join_alias}.meta_value END DESC, " . $clauses['orderby'];
                    }
                } else {
                    // When filtering: just put coming soon posts first
                    $clauses['orderby'] = "CASE WHEN {$join_alias}.meta_value IS NOT NULL THEN 0 ELSE 1 END ASC, " . $clauses['orderby'];
                }
            }
        }
        
        return $clauses;
    }
    
    /**
     * Show Coming Soon indicator in post edit screen
     */
    function ats_show_coming_soon_indicator($post)
    {
        $postType = self::get_configured_post_type();
        if ($post->post_type !== $postType) {
            return;
        }
        
        $comingSoonDate = get_post_meta($post->ID, 'ATS_ComingSoonDate', true);
        if (!empty($comingSoonDate)) {
            ?>
            <div class="notice notice-info inline" style="margin: 10px 0; padding: 10px;">
                <p style="margin: 0;">
                    <strong style="color: #2271b1;">Coming Soon Event</strong>
                    <br>
                    <small>Coming Soon Date: <?php echo esc_html($comingSoonDate); ?></small>
                </p>
            </div>
            <?php
        }
    }

}