<?php
if ( ! defined( 'ABSPATH' ) ) exit;

class IntegratePalace_Properties_Public {
    private $plugin_name;
    private $version;

    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        add_action( 'wp_ajax_nopriv_ajax_load_button', array( $this, 'ajax_load_button' ) );
        add_action( 'wp_ajax_ajax_load_button', array( $this, 'ajax_load_button' ) );
        add_action( 'wp_ajax_nopriv_ipp_filter_properties', array( $this, 'ajax_filter_properties' ) );
        add_action( 'wp_ajax_ipp_filter_properties', array( $this, 'ajax_filter_properties' ) );

        // Exclude hidden properties from frontend queries
        add_action( 'pre_get_posts', array( $this, 'exclude_hidden_properties' ) );
    }

    /**
     * Modify the main query for property archives — handle hidden, search, and filters.
     */
    public function exclude_hidden_properties( $query ) {
        if ( is_admin() || ! $query->is_main_query() ) {
            return;
        }

        if ( $query->get( 'post_type' ) !== 'palace-properties' && ! is_post_type_archive( 'palace-properties' ) ) {
            return;
        }

        $meta_query = $query->get( 'meta_query' ) ?: array( 'relation' => 'AND' );

        // Exclude hidden properties
        $meta_query[] = array(
            'relation' => 'OR',
            array( 'key' => 'ipp_hide_property', 'compare' => 'NOT EXISTS' ),
            array( 'key' => 'ipp_hide_property', 'value' => '1', 'compare' => '!=' ),
        );

        // Handle GET-based search from the filter form
        if ( isset( $_GET['filter'] ) ) {

            // Text search — search across title + meta fields
            if ( ! empty( $_GET['search_text'] ) ) {
                $search_term = sanitize_text_field( wp_unslash( $_GET['search_text'] ) );
                $this->add_meta_search_filter( $search_term );
                $query->set( 'ipp_meta_search', true );
            }

            // Price range
            if ( ! empty( $_GET['price_min'] ) ) {
                $meta_query[] = array( 'key' => 'ipp_rent_amount', 'value' => absint( $_GET['price_min'] ), 'type' => 'NUMERIC', 'compare' => '>=' );
            }
            if ( ! empty( $_GET['price_max'] ) ) {
                $meta_query[] = array( 'key' => 'ipp_rent_amount', 'value' => absint( $_GET['price_max'] ), 'type' => 'NUMERIC', 'compare' => '<=' );
            }

            // Bedrooms
            if ( ! empty( $_GET['bedroom'] ) ) {
                $beds = absint( $_GET['bedroom'] );
                $meta_query[] = array( 'key' => 'ipp_bedrooms', 'value' => $beds, 'compare' => $beds >= 5 ? '>=' : '>=', 'type' => 'NUMERIC' );
            }

            // Bathrooms
            if ( ! empty( $_GET['bathroom'] ) ) {
                $baths = absint( $_GET['bathroom'] );
                $meta_query[] = array( 'key' => 'ipp_bathrooms', 'value' => $baths, 'compare' => $baths >= 4 ? '>=' : '>=', 'type' => 'NUMERIC' );
            }

            // Taxonomy filters from GET params
            $tax_query = array( 'relation' => 'AND' );
            if ( ! empty( $_GET['region'] ) ) {
                $tax_query[] = array( 'taxonomy' => 'palace-property-region', 'field' => 'slug', 'terms' => sanitize_text_field( $_GET['region'] ) );
            }
            if ( ! empty( $_GET['property_type'] ) ) {
                $tax_query[] = array( 'taxonomy' => 'palace-property-type', 'field' => 'slug', 'terms' => sanitize_text_field( $_GET['property_type'] ) );
            }
            if ( ! empty( $_GET['property_status'] ) ) {
                $tax_query[] = array( 'taxonomy' => 'palace-property-status', 'field' => 'slug', 'terms' => sanitize_text_field( $_GET['property_status'] ) );
            }
            if ( count( $tax_query ) > 1 ) {
                $query->set( 'tax_query', $tax_query );
            }

            // Sort
            if ( ! empty( $_GET['sort_by'] ) ) {
                switch ( sanitize_text_field( $_GET['sort_by'] ) ) {
                    case 'price_asc':
                        $query->set( 'meta_key', 'ipp_rent_amount' );
                        $query->set( 'orderby', 'meta_value_num' );
                        $query->set( 'order', 'ASC' );
                        break;
                    case 'price_desc':
                        $query->set( 'meta_key', 'ipp_rent_amount' );
                        $query->set( 'orderby', 'meta_value_num' );
                        $query->set( 'order', 'DESC' );
                        break;
                    case 'bedrooms_desc':
                        $query->set( 'meta_key', 'ipp_bedrooms' );
                        $query->set( 'orderby', 'meta_value_num' );
                        $query->set( 'order', 'DESC' );
                        break;
                }
            }
        }

        $query->set( 'meta_query', $meta_query );
    }

    /**
     * Add search filter to extend WP search to include meta fields.
     */
    private function add_meta_search_filter( $search_term ) {
        add_filter( 'posts_where', function( $where, $query ) use ( $search_term ) {
            if ( ! $query->get( 'ipp_meta_search' ) ) return $where;
            global $wpdb;
            $like = '%' . $wpdb->esc_like( $search_term ) . '%';
            $where .= $wpdb->prepare(
                " AND ({$wpdb->posts}.post_title LIKE %s OR {$wpdb->posts}.post_content LIKE %s OR {$wpdb->posts}.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key IN ('ipp_address1','ipp_address2','ipp_address3','ipp_suburb','ipp_region','ipp_postcode','ipp_property_code','ipp_property_code_global','ipp_agent_full_name','ipp_class','ipp_management_type','information_address','information_suburb','information_region','ipp_header','ipp_name') AND meta_value LIKE %s))",
                $like, $like, $like
            );
            return $where;
        }, 10, 2 );
    }

    public function enqueue_styles() {
        // Base CSS — always loaded
        wp_enqueue_style(
            'ipp-base',
            INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/css/ipp-base.css',
            array(),
            $this->version
        );

        // Template-specific CSS (if exists)
        $template = $this->get_active_template();
        $template_css = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . $template . '/style.css';
        if ( file_exists( $template_css ) ) {
            wp_enqueue_style(
                'ipp-template-' . $template,
                INTEGRATE_PALACE_P_PLUGIN_URI . 'public/templates/' . $template . '/style.css',
                array( 'ipp-base' ),
                $this->version
            );
        }

        // Legacy CSS — only load if using old template system (no new card.php exists)
        $new_card = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . $template . '/card.php';
        if ( ! file_exists( $new_card ) ) {
            wp_enqueue_style( 'swiper-style', INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/css/swiper-bundle.min.css', array(), $this->version );
            wp_enqueue_style( $this->plugin_name, INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/css/ipp-main.css', array(), $this->version );
        }
    }

    public function enqueue_scripts() {
        // Gallery JS — lightweight, no jQuery dependency
        wp_enqueue_script(
            'ipp-gallery',
            INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/js/ipp-gallery.js',
            array(),
            $this->version,
            true
        );

        // Main script
        wp_enqueue_script(
            $this->plugin_name,
            INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/js/ipp-scripts.js',
            array( 'jquery' ),
            $this->version,
            true
        );

        wp_localize_script( $this->plugin_name, 'ipp_ajax', array(
            'ajax_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
            'nonce'    => wp_create_nonce( 'ipp_frontend_nonce' ),
        ) );

        // Legacy compat
        wp_localize_script( $this->plugin_name, 'ajax_params', array(
            'ajax_url' => esc_url( admin_url( 'admin-ajax.php' ) ),
        ) );

        // Filters JS — AJAX filtering, sorting, load more, URL state
        wp_enqueue_script(
            'ipp-filters',
            INTEGRATE_PALACE_P_PLUGIN_URI . 'public/assets/js/ipp-filters.js',
            array(),
            $this->version,
            true
        );
    }

    public function integrate_palace_enqueue_fonts() {
        $options = get_option( IPPR_SETTINGS, [] );
        $heading_font = $options['heading_font_family'] ?? 'Euclid Circular B';
        $body_font = $options['body_font_family'] ?? 'Euclid Circular B';
        $button_font = $options['btn_font_family'] ?? 'Euclid Circular B';

        if ( $heading_font === 'initial' && $body_font === 'initial' && $button_font === 'initial' ) {
            return;
        }

        $euclid_enqueued = false;
        $fonts = array(
            'ipp-heading-font' => $heading_font,
            'ipp-body-font'    => $body_font,
            'ipp-button-font'  => $button_font,
        );

        foreach ( $fonts as $handle => $font ) {
            if ( $font === 'initial' ) continue;
            if ( $font === 'Euclid Circular B' ) {
                if ( ! $euclid_enqueued ) {
                    wp_enqueue_style( $handle, plugin_dir_url( __FILE__ ) . 'assets/fonts/ipp-fonts.css', array(), null );
                    $euclid_enqueued = true;
                }
            } else {
                wp_enqueue_style( $handle, esc_url( 'https://fonts.googleapis.com/css?family=' . urlencode( $font ) ), array(), null );
            }
        }
    }

    /**
     * Get active template slug.
     */
    private function get_active_template() {
        return sanitize_text_field( get_option( 'ipp_select_template', 'palace-property' ) );
    }

    /**
     * Resolve template file path with theme override support.
     * Hierarchy: child theme → parent theme → plugin new templates → plugin legacy templates
     */
    private function resolve_template( $type ) {
        $template_slug = $this->get_active_template();

        // 1. Check child/parent theme: palace-properties/{type}-{template}.php
        $theme_file = locate_template( "palace-properties/{$type}-{$template_slug}.php" );
        if ( $theme_file ) return $theme_file;

        // 2. Check child/parent theme: palace-properties/{type}.php
        $theme_file = locate_template( "palace-properties/{$type}.php" );
        if ( $theme_file ) return $theme_file;

        // 3. New template system
        $new_template = INTEGRATE_PALACE_P_PLUGIN_DIR . "public/templates/{$template_slug}/{$type}.php";
        if ( file_exists( $new_template ) ) return $new_template;

        // 4. Legacy template fallback
        if ( $type === 'single' ) {
            return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/single-palace_property.php';
        }
        return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/archive-palace_property.php';
    }

    /**
     * Template routing for single and archive views.
     */
    public function use_palace_property_template( $template ) {
        $post_type = 'palace-properties';
        $template_slug = $this->get_active_template();

        if ( is_singular( $post_type ) ) {
            // 1. Theme override
            $theme_template = locate_template( array(
                "palace-properties/single-{$template_slug}.php",
                'palace-properties/single.php',
                'single-palace_property.php',
            ) );
            if ( $theme_template ) return $theme_template;

            // 2. New template single.php in template dir
            $new_single = INTEGRATE_PALACE_P_PLUGIN_DIR . "public/templates/{$template_slug}/single.php";
            if ( file_exists( $new_single ) ) {
                return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/single.php'; // wrapper
            }

            // 3. Legacy fallback
            return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/single-palace_property.php';
        }

        if ( is_post_type_archive( $post_type ) || is_tax( array( 'palace-property-type', 'palace-property-status', 'palace-property-region', 'palace-property-management' ) ) ) {
            // 1. Theme override
            $theme_template = locate_template( array(
                "palace-properties/archive-{$template_slug}.php",
                'palace-properties/archive.php',
                'archive-palace_property.php',
            ) );
            if ( $theme_template ) return $theme_template;

            // 2. New template card.php in template dir
            $new_card = INTEGRATE_PALACE_P_PLUGIN_DIR . "public/templates/{$template_slug}/card.php";
            if ( file_exists( $new_card ) ) {
                return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/archive.php'; // wrapper
            }

            // 3. Legacy fallback
            return INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/archive-palace_property.php';
        }

        return $template;
    }

    /**
     * Load More AJAX handler (legacy compat + new templates).
     */
    public function ajax_load_button() {
        $template_slug = $this->get_active_template();
        $paged = isset( $_POST['page'] ) ? intval( $_POST['page'] ) : 1;

        $options = get_option( 'ipp_settings', [] );
        $posts_per_page = absint( $options['property_per_page'] ?? 9 );

        $query_args = array(
            'post_type'      => 'palace-properties',
            'orderby'        => 'date',
            'order'          => 'DESC',
            'posts_per_page' => $posts_per_page,
            'paged'          => $paged,
            'post_status'    => 'publish',
        );

        $the_query = new WP_Query( $query_args );
        $response = '';

        if ( $the_query->have_posts() ) :
            while ( $the_query->have_posts() ) :
                $the_query->the_post();
                ob_start();
                $post_id = get_the_ID();

                // Try new template card first
                $card_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/card.php';
                if ( file_exists( $card_path ) ) {
                    include $card_path;
                } else {
                    // Legacy fallback
                    $legacy_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/content/archive/' . sanitize_file_name( $template_slug ) . '.php';
                    if ( file_exists( $legacy_path ) ) {
                        include $legacy_path;
                    }
                }
                $response .= ob_get_clean();
            endwhile;
        endif;

        wp_reset_postdata();

        wp_send_json_success( array(
            'content'   => $response,
            'max_pages' => $the_query->max_num_pages,
        ) );
    }

    /**
     * AJAX filter/sort handler for archive pages.
     */
    public function ajax_filter_properties() {
        check_ajax_referer( 'ipp_frontend_nonce', 'nonce' );

        $template_slug = $this->get_active_template();
        $page     = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
        $per_page = isset( $_POST['per_page'] ) ? absint( $_POST['per_page'] ) : 9;
        $sort_by  = isset( $_POST['sort_by'] ) ? sanitize_text_field( $_POST['sort_by'] ) : 'date_desc';

        // Build query
        $args = array(
            'post_type'      => 'palace-properties',
            'posts_per_page' => $per_page,
            'paged'          => $page,
            'post_status'    => 'publish',
        );

        // Sorting
        switch ( $sort_by ) {
            case 'price_asc':
                $args['meta_key'] = 'ipp_rent_amount';
                $args['orderby']  = 'meta_value_num';
                $args['order']    = 'ASC';
                break;
            case 'price_desc':
                $args['meta_key'] = 'ipp_rent_amount';
                $args['orderby']  = 'meta_value_num';
                $args['order']    = 'DESC';
                break;
            case 'bedrooms_desc':
                $args['meta_key'] = 'ipp_bedrooms';
                $args['orderby']  = 'meta_value_num';
                $args['order']    = 'DESC';
                break;
            default:
                $args['orderby'] = 'date';
                $args['order']   = 'DESC';
                break;
        }

        // Meta query for filters
        $meta_query = array( 'relation' => 'AND' );

        if ( ! empty( $_POST['search_text'] ) ) {
            $search = sanitize_text_field( $_POST['search_text'] );
            $args['ipp_meta_search'] = true;
            $this->add_meta_search_filter( $search );
        }

        if ( ! empty( $_POST['price_min'] ) ) {
            $meta_query[] = array(
                'key'     => 'ipp_rent_amount',
                'value'   => absint( $_POST['price_min'] ),
                'type'    => 'NUMERIC',
                'compare' => '>=',
            );
        }

        if ( ! empty( $_POST['price_max'] ) ) {
            $meta_query[] = array(
                'key'     => 'ipp_rent_amount',
                'value'   => absint( $_POST['price_max'] ),
                'type'    => 'NUMERIC',
                'compare' => '<=',
            );
        }

        if ( ! empty( $_POST['bedrooms'] ) && $_POST['bedrooms'] !== 'any' ) {
            $beds = absint( $_POST['bedrooms'] );
            $meta_query[] = array(
                'key'     => 'ipp_bedrooms',
                'value'   => $beds,
                'compare' => $beds >= 6 ? '>=' : '=',
                'type'    => 'NUMERIC',
            );
        }

        if ( ! empty( $_POST['bathrooms'] ) && $_POST['bathrooms'] !== 'any' ) {
            $baths = absint( $_POST['bathrooms'] );
            $meta_query[] = array(
                'key'     => 'ipp_bathrooms',
                'value'   => $baths,
                'compare' => $baths >= 4 ? '>=' : '=',
                'type'    => 'NUMERIC',
            );
        }

        // Exclude hidden properties
        $meta_query[] = array(
            'relation' => 'OR',
            array( 'key' => 'ipp_hide_property', 'compare' => 'NOT EXISTS' ),
            array( 'key' => 'ipp_hide_property', 'value' => '1', 'compare' => '!=' ),
        );

        if ( count( $meta_query ) > 1 ) {
            $args['meta_query'] = $meta_query;
        }

        // Taxonomy filters
        $tax_query = array( 'relation' => 'AND' );

        if ( ! empty( $_POST['property_type'] ) ) {
            $tax_query[] = array(
                'taxonomy' => 'palace-property-type',
                'field'    => 'slug',
                'terms'    => array_map( 'sanitize_text_field', (array) $_POST['property_type'] ),
            );
        }

        if ( ! empty( $_POST['property_status'] ) ) {
            $tax_query[] = array(
                'taxonomy' => 'palace-property-status',
                'field'    => 'slug',
                'terms'    => array_map( 'sanitize_text_field', (array) $_POST['property_status'] ),
            );
        }

        if ( ! empty( $_POST['region'] ) ) {
            $tax_query[] = array(
                'taxonomy' => 'palace-property-region',
                'field'    => 'slug',
                'terms'    => array_map( 'sanitize_text_field', (array) $_POST['region'] ),
            );
        }

        if ( count( $tax_query ) > 1 ) {
            $args['tax_query'] = $tax_query;
        }

        $the_query = new WP_Query( $args );
        $html = '';

        if ( $the_query->have_posts() ) :
            while ( $the_query->have_posts() ) :
                $the_query->the_post();
                ob_start();
                $post_id = get_the_ID();
                $card_path = INTEGRATE_PALACE_P_PLUGIN_DIR . 'public/templates/' . sanitize_file_name( $template_slug ) . '/card.php';
                if ( file_exists( $card_path ) ) {
                    include $card_path;
                }
                $html .= ob_get_clean();
            endwhile;
        endif;

        wp_reset_postdata();

        wp_send_json_success( array(
            'html'        => $html,
            'total_count' => $the_query->found_posts,
            'max_pages'   => $the_query->max_num_pages,
            'current_page' => $page,
        ) );
    }
}
