<?php
/**
 * Utility Functions
 *
 * @package Author_Website_Templates
 */

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

/**
 * Check if the current theme is allowed.
 */
function rswpthemes_awt_is_allowed_theme()
{
    $allowed_themes = ['author-portfolio', 'author-portfolio-pro', 'book-author-blog', 'book-review-blog', 'author-personal-blog', 'writers-portfolio', 'book-author-template'];
    $current_theme_slug = get_template(); // Get the current theme's directory name (slug)
    return in_array(strtolower($current_theme_slug), $allowed_themes);
}

/**
 * Check if Pro version is active.
 */
function rswpthemes_awt_is_pro_active()
{
    // Load the is_plugin_active() function if it doesn't exist
    if (!function_exists('is_plugin_active')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $active_theme = wp_get_theme(); // Get the currently active theme
    $is_theme_active = ($active_theme->get('Name') === 'Author Portfolio Pro');

    $is_plugin_active = is_plugin_active('rs-wp-books-showcase-pro/rs-wp-books-showcase-pro.php'); // Adjust path if needed

    return $is_theme_active || $is_plugin_active;
}

/**
 * Get Block ID by Slug
 *
 * @param string $slug The slug of the wp_block post.
 * @return int|false The post ID if found, false otherwise.
 */
function rswpthemes_awt_get_block_id_by_slug($slug)
{
    if (empty($slug)) {
        return false;
    }
    // Check for 'wp_block' post type by slug (post_name)
    $post = get_page_by_path($slug, OBJECT, 'wp_block');
    return ($post && $post->ID) ? $post->ID : false;
}

/**
 * Get page by title (Custom)
 */
function rswpthemes_awt_new_get_page_by_title($page_title, $output = OBJECT, $post_type = 'page')
{
    $args = array(
        'post_type' => $post_type,
        'post_status' => 'published',
        'posts_per_page' => 1,
        'update_post_term_cache' => false,
        'update_post_meta_cache' => false,
        'no_found_rows' => true,
        'orderby' => 'post_date ID',
        'order' => 'ASC',
        'title' => $page_title,
    );

    $query = new WP_Query($args);
    $pages = $query->posts;

    if (empty($pages)) {
        return null;
    }

    return get_post($pages[0], $output);
}

/**
 * Get Excerpt with limit
 */
function rswpthemes_awt_get_excerpt($limit, $source = null)
{
    if ($source == 'content' ? ($excerpt = get_the_content()) : ($excerpt = get_the_excerpt())) {
    }
    $excerpt = preg_replace(' (\[.*?\])', '', $excerpt);
    $excerpt = strip_shortcodes($excerpt);
    $excerpt = strip_tags($excerpt);
    $excerpt = substr($excerpt, 0, $limit);
    $excerpt = substr($excerpt, 0, strripos($excerpt, ' '));
    $excerpt = trim(preg_replace('/\s+/', ' ', $excerpt));
    return $excerpt;
}

/**
 * Display Categories
 */
function rswpthemes_awt_categories()
{
    if ('post' === get_post_type()) {
        /* translators: used between list items, there is a space after the comma */
        $categories_list = get_the_category_list(' ');
        if ($categories_list) {
            printf('<span class="cat-links">' . '%1$s' . '</span>', $categories_list); // WPCS: XSS OK.
        }
    }
    return;
}

if (!function_exists('rswpthemes_awt_posted_on')):
    /**
     * Prints HTML with meta information for the current post-date/time.
     */
    function rswpthemes_awt_posted_on()
    {
        $time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
        if (get_the_time('U') !== get_the_modified_time('U')) {
            $time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time>';
        }
        $time_string = sprintf(
            $time_string,
            esc_attr(get_the_date(DATE_W3C)),
            esc_html(get_the_date()),
            esc_attr(get_the_modified_date(DATE_W3C)),
            esc_html(get_the_modified_date())
        );
        $posted_on = sprintf(
            /* translators: %s: post date. */
            esc_html_x('posted on %s', 'post date', 'eafe'),
            '<a href="' . esc_url(get_permalink()) . '" rel="bookmark">' . $time_string . '</a>'
        );
        echo '<span class="posted-on">' . $posted_on . '</span>'; // WPCS: XSS OK.
    }
endif;

if (!function_exists('rswpthemes_awt_comment_popuplink')) {
    function rswpthemes_awt_comment_popuplink()
    {
        comments_popup_link(esc_html__('No Comment', 'eafe'), esc_html__('1 Comment', 'eafe'), esc_html__('% Comments', 'eafe'));
    }
}

if (!function_exists('rswpthemes_awt_posted_by')):
    /**
     * Prints HTML with meta information for the current author.
     */
    function rswpthemes_awt_posted_by()
    {
        $byline = sprintf(
            /* translators: %s: post author. */
            esc_html_x('by %s', 'post author', 'extra-addons-for-elementor'),
            '<span class="author vcard"><a class="url fn n" href="' . esc_url(get_author_posts_url(get_the_author_meta('ID'))) . '">' . esc_html(get_the_author()) . '</a></span>'
        );
        echo '<span class="byline"> ' . $byline . '</span>'; // WPCS: XSS OK.
    }
endif;

if (did_action('elementor/loaded')) {
    function rswpthemes_awt_enqueue_elementor_control_script()
    {
        $is_pro_active = rswpthemes_awt_is_pro_active();
        if (true !== $is_pro_active):
            wp_enqueue_script(
                'rsswpthemes_awt_elementor_control',
                RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/elementor-controls/elementor-control.js',
                ['jquery'],
                '1.0.0',
                true
            );
            wp_enqueue_style(
                'rsswpthemes_awt_elementor_control',
                RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/elementor-controls/control.css',
                array(),
                '1.0.0',
                'all'
            );
            wp_localize_script(
                'rsswpthemes_awt_elementor_control',
                'myWidgetSettings',
                [
                    'isProActive' => $is_pro_active,
                    'upgradeLink' => 'https://rswpthemes.com/author-portfolio-pro-wordpress-theme/',
                ]
            );
        endif;
    }
    add_action('elementor/editor/after_enqueue_scripts', 'rswpthemes_awt_enqueue_elementor_control_script');
}

/**
 * Register New Category For Author Website Templates Widgets
 */
if (did_action('elementor/loaded')) {
    add_action('elementor/elements/categories_registered', 'rswpthemes_awt_add_elementor_widget_categories');
    function rswpthemes_awt_add_elementor_widget_categories($elements_manager)
    {
        $elements_manager->add_category(
            'rswpthemes_awt_widgets',
            [
                'title' => __('Author Website Template Widgets', 'author-website-templates'),
            ]
        );
    }
}

if (did_action('elementor/loaded')) {
    add_filter('elementor/icons_manager/additional_tabs', 'rswpthemes_awt_register_custom_icon_library');
    function rswpthemes_awt_register_custom_icon_library($tabs)
    {
        // Define the custom icon set
        $tabs['rswpthemes_icon'] = [
            'name' => 'rswpthemes_icon',
            'label' => __('Rswpthemes Icons', 'author-website-templates'),
            'labelIcon' => 'eicon-star',
            'prefix' => 'rswpthemes-icon ',
            'displayPrefix' => '',
            'url' => RSWPTHEMES_AWT_PLUGIN_URL . 'includes/icons/icons.css',
            'fetchJson' => RSWPTHEMES_AWT_PLUGIN_URL . 'includes/icons/icons.json',
            'ver' => '1.0',
            'native' => false,
        ];
        return $tabs;
    }
}
