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


/**
 * Get search bar title from settings
 *
 * @return string
 * @since 2.0.3
 */
function hvnly_get_search_bar_title() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_searchBarTitle']) && !empty($search_settings['hvnly_searchBarTitle'])) {
            return $search_settings['hvnly_searchBarTitle'];
        }
    }
    return '';
}

/**
 * Check if top search title should be hidden
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_top_search_title_hidden() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_hideTopSearchTitle'])) {
            $is_hidden = $search_settings['hvnly_hideTopSearchTitle'];
            // Convert to boolean properly
            return filter_var($is_hidden, FILTER_VALIDATE_BOOLEAN);
        }
    }
    return false;
}

/**
 * Check if AJAX Load More is enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_ajax_load_more_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_enableAjaxLoadMore'])) {
            return (bool) $search_settings['hvnly_enableAjaxLoadMore'];
        }
    }
    return true; // Default to enabled
}
/**
 * Check if breadcrumbs are enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_breadcrumb_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->is_breadcrumb_enabled();
    }
    return true;
}

/**
 * Check if back to top button is enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_back_to_top_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->is_back_to_top_enabled();
    }
    return true;
}

/**
 * Check if print button is enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_print_button_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->is_print_button_enabled();
    }
    return true;
}
/**
 * Check if save property button is enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_save_property_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->is_save_property_enabled();
    }
    return true;
}
/**
 * Check if share button is enabled from settings
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_is_share_button_enabled()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->is_share_button_enabled();
    }
    return true;
}


/**
 * Get design setting with backward compatibility
 *
 * @param string $key     Setting key (with or without hvnly_ prefix)
 * @param mixed  $default Default value
 * @return mixed
 */
function hvnly_get_design_setting($key, $default = null)
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_design_setting($key, $default);
    }
    return $default;
}

/**
 * Get all design settings
 *
 * @return array
 */
function hvnly_get_design_settings()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_design_settings();
    }
    return [];
}

/**
 * Get brand color
 *
 * @return string
 */
function hvnly_get_brand_color()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_brand_color();
    }
    return '#6C60FE';
}

/**
 * Get secondary color
 *
 * @return string
 */
function hvnly_get_secondary_color()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_secondary_color();
    }
    return '#764ba2';
}

/**
 * Get link color
 *
 * @return string
 */
function hvnly_get_link_color()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_link_color();
    }
    return '#1E1E2F';
}

/**
 * Get title color
 *
 * @return string
 */
function hvnly_get_title_color()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_title_color();
    }
    return '#1E1E2F';
}

/**
 * Get body font size
 *
 * @return int
 */
function hvnly_get_body_font_size()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_body_font_size();
    }
    return 16;
}

/**
 * Get body color
 *
 * @return string
 */
function hvnly_get_body_color()
{
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_body_color();
    }
    return '#ffffff';
}

/**
 * Get cached sidebar filter data
 *
 * @return array
 */
if (!function_exists('hvnly_get_cached_sidebar_filters')) {
    function hvnly_get_cached_sidebar_filters()
    {
        if (!class_exists('HvnlyNab\Frontend\ViewModels\SidebarSearchFilters')) {
            // Fallback to direct query if ViewModel not available
            return hvnly_get_current_filters();
        }

        $sidebar_filters = new HvnlyNab\Frontend\ViewModels\SidebarSearchFilters();
        return $sidebar_filters->get_sidebar_filter_data();
    }
}

/**
 * Clear sidebar cache
 *
 * @return void
 */
if (!function_exists('hvnly_clear_sidebar_cache')) {
    function hvnly_clear_sidebar_cache()
    {
        if (!class_exists('HvnlyNab\Frontend\ViewModels\SidebarSearchFilters')) {
            return;
        }

        $sidebar_filters = new HvnlyNab\Frontend\ViewModels\SidebarSearchFilters();
        $sidebar_filters->clear_all_sidebar_cache();

        do_action('hvnly_sidebar_cache_cleared');
    }
}





/**
 * Get cached taxonomy terms with fallback
 *
 * @param string $taxonomy Taxonomy name
 * @param array  $args     Get terms arguments
 * @return array
 */
if (!function_exists('hvnly_get_cached_terms')) {
    function hvnly_get_cached_terms($taxonomy, $args = [])
    {
        if (!class_exists('HvnlyNab\Frontend\ViewModels\SearchFilters')) {
            // Fallback to direct query if ViewModel not available
            return get_terms(wp_parse_args($args, [
                'taxonomy' => $taxonomy,
                'hide_empty' => true,
            ]));
        }

        $search_filters = new HvnlyNab\Frontend\ViewModels\SearchFilters();
        return $search_filters->get_cached_terms($taxonomy, $args);
    }
}

/**
 * Clear all Havenlytics cache
 *
 * @return void
 */
function hvnly_clear_all_cache()
{
    if (!class_exists('HvnlyNab\Frontend\ViewModels\SearchFilters')) {
        return;
    }

    $search_filters = new HvnlyNab\Frontend\ViewModels\SearchFilters();
    $search_filters->clear_all_search_cache();

    do_action('hvnly_cache_cleared');
}

/**
 * Check if transient caching is available
 *
 * @return bool
 */
if (!function_exists('hvnly_transients_available')) {
    function hvnly_transients_available()
    {
        return HVNLY_NAB()->transients_available();
    }
}

/**
 * Utility function to get cache statistics
 *
 * @since 2.0.0
 * @return array
 */
if (!function_exists('hvnly_get_cache_stats')) {
    function hvnly_get_cache_stats()
    {
        return HVNLY_NAB()->get_cache_stats();
    }
}
/**
 * Utility function to clear Havenlytics cache
 *
 * @since 2.0.0
 * @return void
 */
if (!function_exists('hvnly_clear_cache')) {
    function hvnly_clear_cache()
    {
        HVNLY_NAB()->clear_all_cache();
    }
}
/**
 * Check if it's a property archive
 */
if (!function_exists('hvnly_is_property_archive')) {
    function hvnly_is_property_archive()
    {
        $post_type = 'hvnly_property';

        // Get the queried object
        $queried_object = get_queried_object();

        // Check if it's a post type archive
        if (is_post_type_archive($post_type)) {
            return true;
        }

        // Check if it's a taxonomy archive (dynamically)
        if (is_tax() && isset($queried_object->taxonomy)) {
            $taxonomy = get_taxonomy($queried_object->taxonomy);
            $allowed_taxonomies = ['hvnly_prop_types', 'hvnly_prop_depts', 'hvnly_prop_locations'];

            // Allow for translated taxonomy slugs
            if (in_array($taxonomy->name, $allowed_taxonomies, true)) {
                return true;
            }
        }

        // Check if it's an author property archive
        if (function_exists('hvnly_is_author_property_archive') && hvnly_is_author_property_archive()) {
            return true;
        }

        return false;
    }
}

/**
 * Check if it's an author property archive
 */
if (!function_exists('hvnly_is_author_property_archive')) {
    function hvnly_is_author_property_archive()
    {
        $is_properties = $_GET['properties'] ?? '';

        if (is_author() && (($is_properties === 'yes') || (get_post_type() === 'hvnly_property'))) {
            return true;
        }
        return false;
    }
}

/**
 * Get common property meta
 */
if (!function_exists('hvnly_get_common_property_meta')) {
    function hvnly_get_common_property_meta($post_id, $metakey, $single = true)
    {
        return get_post_meta($post_id, $metakey, $single);
    }
}

/**
 * Get property type info
 */
if (!function_exists('hvnly_get_property_type_info')) {
    function hvnly_get_property_type_info($post_id, $entity)
    {
        $property_type = get_post_meta($post_id, 'hvnly_property_type', true);
        $property_type_name = get_term((int) $property_type)->name;

        if ($entity === 'name') {
            return $property_type_name;
        } else {
            $property_type_icon = get_term_meta((int) $property_type, 'hvnly_term_icon', true);
            return $property_type_icon;
        }
    }
}

/**
 * Render repeated taxonomy terms
 */
if (!function_exists('hvnly_render_repeated_tax')) {
    function hvnly_render_repeated_tax($post_id, $tax = 'hvnly_prop_locations', $display_item = 2)
    {
        $terms = get_the_terms($post_id, $tax) ? get_the_terms($post_id, $tax) : array();
        return array_slice($terms, 0, $display_item);
    }
}

/**
 * Get property feature image
 */
if (!function_exists('hvnly_get_property_feature')) {
    function hvnly_get_property_feature($post_id)
    {
        $feature_image = get_the_post_thumbnail_url($post_id);
        if ($feature_image) {
            return $feature_image;
        }
    }
}

/**
 * Get terms with arguments
 */
if (!function_exists('hvnly_get_terms')) {
    function hvnly_get_terms($taxonomy, $args = array())
    {
        return get_terms(
            array_merge(
                array(
                    'taxonomy'   => $taxonomy,
                    'hide_empty' => true,
                ),
                $args
            )
        );
    }
}

/**
 * Property type navigation URL
 */
if (!function_exists('hvnly_property_type_nav_url')) {
    function hvnly_property_type_nav_url($type = 'all', $base_url = null)
    {
        if (empty($base_url)) {
            $base_url = remove_query_arg(array('page', 'paged'));
            $base_url = preg_replace('~/page/(\d+)/?~', '', $base_url);
            $base_url = preg_replace('~/paged/(\d+)/?~', '', $base_url);
        }

        $url = add_query_arg(array('property_type' => $type), $base_url);

        return $url;
    }
}



/**
 * Get search page URL
 */
if (!function_exists('hvnly_get_search_page_url')) {
    function hvnly_get_search_page_url()
    {
        return get_post_type_archive_link('hvnly_property');
    }
}





/**
 * Get property author URL
 */
if (!function_exists('hvnly_property_author_url')) {
    function hvnly_property_author_url($author_id, $post_type = 'hvnly_property')
    {
        // You can customize this based on your URL structure
        return get_author_posts_url($author_id);
    }
}



/**
 * Get AJAX URL
 */
if (!function_exists('hvnly_get_ajax_url')) {
    function hvnly_get_ajax_url()
    {
        return admin_url('admin-ajax.php');
    }
}


/**
 * Check if top search bar should be displayed
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_should_show_top_search_bar() {
    // Only check on property archive
    if (!is_post_type_archive('hvnly_property') && !hvnly_page_has_property_shortcode()) {
        return true;
    }
    
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        // Check if hide top search bar is enabled (true means hide, so we return false)
        if (isset($search_settings['hvnly_hideTopSearchBar'])) {
            $is_hidden = $search_settings['hvnly_hideTopSearchBar'];
            // Convert to boolean properly
            $is_hidden = filter_var($is_hidden, FILTER_VALIDATE_BOOLEAN);
            return !$is_hidden;
        }
    }
    
    return true;
}

/**
 * Check if left filter sidebar should be displayed
 *
 * @return bool
 * @since 2.0.3
 */
function hvnly_should_show_filter_sidebar() {
    // Only check on property archive
    if (!is_post_type_archive('hvnly_property') && !hvnly_page_has_property_shortcode()) {
        return true;
    }
    
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        // Check if hide left search bar is enabled (true means hide, so we return false)
        if (isset($search_settings['hvnly_hideLeftSearchBar'])) {
            $is_hidden = $search_settings['hvnly_hideLeftSearchBar'];
            // Convert to boolean properly
            $is_hidden = filter_var($is_hidden, FILTER_VALIDATE_BOOLEAN);
            return !$is_hidden;
        }
    }
    
    return true;
}

/**
 * Get search button text from settings
 *
 * @return string
 * @since 2.0.3
 */
function hvnly_get_search_button_text() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_searchButtonText']) && !empty($search_settings['hvnly_searchButtonText'])) {
            return $search_settings['hvnly_searchButtonText'];
        }
    }
    return __('Filter', 'havenlytics');
}


/**
 * Get search filter fields from settings
 *
 * @return array
 * @since 2.0.3
 */
function hvnly_get_search_filter_fields() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        // Check both possible keys
        if (isset($search_settings['hvnly_search_fields']) && !empty($search_settings['hvnly_search_fields'])) {
            return $search_settings['hvnly_search_fields'];
        }
        if (isset($search_settings['search_fields']) && !empty($search_settings['search_fields'])) {
            return $search_settings['search_fields'];
        }
    }
    return hvnly_get_default_search_filter_fields();
}

/**
 * Get default search filter fields
 *
 * @return array
 * @since 2.0.3
 */
function hvnly_get_default_search_filter_fields() {
    return [
        ['id' => 'price', 'title' => __('Price', 'havenlytics'), 'type' => 'range', 'enabled' => true, 'order' => 1, 'is_default' => true],
        ['id' => 'status', 'title' => __('Status', 'havenlytics'), 'type' => 'dropdown', 'enabled' => true, 'order' => 2, 'is_default' => true],
        ['id' => 'bedrooms_bathrooms', 'title' => __('Bedrooms & Bathrooms', 'havenlytics'), 'type' => 'group', 'enabled' => true, 'order' => 3, 'is_default' => true],
        ['id' => 'reception_rooms', 'title' => __('Reception Rooms', 'havenlytics'), 'type' => 'number', 'enabled' => true, 'order' => 4, 'is_default' => true],
        ['id' => 'property_types', 'title' => __('Property Types', 'havenlytics'), 'type' => 'checkbox', 'enabled' => true, 'order' => 5, 'is_default' => true],
        ['id' => 'locations', 'title' => __('Locations', 'havenlytics'), 'type' => 'dropdown', 'enabled' => true, 'order' => 6, 'is_default' => true],
        ['id' => 'features', 'title' => __('Features', 'havenlytics'), 'type' => 'checkbox', 'enabled' => true, 'order' => 7, 'is_default' => true],
        ['id' => 'tags', 'title' => __('Tags', 'havenlytics'), 'type' => 'dropdown', 'enabled' => true, 'order' => 8, 'is_default' => true],
        ['id' => 'badges', 'title' => __('Badges', 'havenlytics'), 'type' => 'checkbox', 'enabled' => true, 'order' => 9, 'is_default' => true],
        ['id' => 'property_id', 'title' => __('Property ID', 'havenlytics'), 'type' => 'text', 'enabled' => true, 'order' => 10, 'is_default' => true]
    ];
}

/**
 * Get unique property IDs for filter
 *
 * @return array
 * @since 2.0.3
 */
function hvnly_get_unique_property_ids() {
    global $wpdb;
    
    $cache_key = 'hvnly_unique_property_ids';
    $property_ids = get_transient($cache_key);
    
    if (false === $property_ids) {
        $property_ids = $wpdb->get_col(
            "SELECT DISTINCT pm.meta_value 
             FROM {$wpdb->postmeta} pm
             INNER JOIN {$wpdb->posts} p ON pm.post_id = p.ID
             WHERE pm.meta_key = '_hvnly_unique_property_id'
             AND p.post_type = 'hvnly_property'
             AND p.post_status = 'publish'
             AND pm.meta_value IS NOT NULL
             AND pm.meta_value != ''
             ORDER BY CAST(pm.meta_value AS UNSIGNED)"
        );
        
        set_transient($cache_key, $property_ids, 12 * HOUR_IN_SECONDS);
    }
    
    return $property_ids;
}

/**
 * Get default sort option from settings
 *
 * @return string
 * @since 2.0.3
 */
function hvnly_get_default_sort_option() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_propertySortByType']) && !empty($search_settings['hvnly_propertySortByType'])) {
            return $search_settings['hvnly_propertySortByType'];
        }
    }
    return 'date'; // Default to Newest
}

/**
 * Get default view option from settings
 *
 * @return string
 * @since 2.0.3
 */
function hvnly_get_default_view_option() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_propertyViewType']) && !empty($search_settings['hvnly_propertyViewType'])) {
            $view = strtolower($search_settings['hvnly_propertyViewType']);
            // Map the values to match frontend
            if ($view === 'grid') return 'grid';
            if ($view === 'list') return 'list';
            if ($view === 'map') return 'map';
            return 'grid';
        }
    }
    return 'grid'; // Default to Grid View
}

/**
 * Get AJAX Load More button text from settings
 *
 * @return string
 * @since 2.0.3
 */
function hvnly_get_ajax_load_more_button_text() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $search_settings = $settings_manager->get_search_settings();
        
        if (isset($search_settings['hvnly_AjaxLoadMoreButtonText']) && !empty($search_settings['hvnly_AjaxLoadMoreButtonText'])) {
            return $search_settings['hvnly_AjaxLoadMoreButtonText'];
        }
    }
    return __('Load More Properties', 'havenlytics');
}

/**
 * Get number of properties to display per page from settings
 *
 * @return int
 * @since 2.0.3
 */
function hvnly_get_properties_per_page() {
    if (class_exists('HvnlyNab\Core\SettingsManager')) {
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        return $settings_manager->get_properties_per_page();
    }
    return 12;
}


/**
 * Modify main query to use custom properties per page setting
 *
 * @param WP_Query $query The WordPress query object.
 * @return void
 */
function hvnly_modify_property_archive_posts_per_page($query) {
    if (!is_admin() && $query->is_main_query() && function_exists('hvnly_is_property_archive')) {
        if (hvnly_is_property_archive()) {
            $properties_per_page = function_exists('hvnly_get_properties_per_page') 
                ? hvnly_get_properties_per_page() 
                : 12;
            
            $query->set('posts_per_page', $properties_per_page);
        }
    }
}
add_action('pre_get_posts', 'hvnly_modify_property_archive_posts_per_page', 20);