<?php if (!defined('ABSPATH')) {
    die('Direct access forbidden.');
}

/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package ethrik
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */

/** Echo Variable **/
function ethrik_return($s)
{
    return esc_html($s); // Escaping the variable to prevent XSS
}

/** Get Tag List **/
if (!function_exists('ethrik_post_tags')) {
    function ethrik_post_tags()
    {
        $terms = get_terms(array(
            'taxonomy' => 'post_tag',
            'hide_empty' => false,
            'posts_per_page' => -1,
        ));
        $cat_list = [];
        foreach ($terms as $post) {
            $cat_list[$post->term_id] = [$post->name];
        }
        return $cat_list;
    }
}

/** Post Read Time **/
function ethrik_reading_time()
{
    global $post;
    $content = get_post_field('post_content', $post->ID);
    $word_count = str_word_count(strip_tags($content));
    $readingtime = ceil($word_count / 200);
    $timer = " min read";
    $totalreadingtime = $readingtime . $timer;
    return $totalreadingtime;
}

/** Post View **/
function ethrik_get_post_view()
{
    $count = get_post_meta(get_the_ID(), 'post_views_count', true);
    return esc_html($count); // Escaping the output
}

function ethrik_set_post_view()
{
    $key = 'post_views_count';
    $post_id = get_the_ID();
    $count = (int) get_post_meta($post_id, $key, true);
    $count++;
    update_post_meta($post_id, $key, $count);
}

/** Return embed code for video URL **/
function ethrik_video_embed($url)
{
    $embed_url = '';
    if (strpos($url, 'facebook.com/') !== false) {
        $embed_url = esc_url('https://www.facebook.com/plugins/video.php?href=' . rawurlencode($url) . '&show_text=1&width=200');
    } elseif (strpos($url, 'vimeo.com/') !== false) {
        $video_id = explode("vimeo.com/", $url)[1];
        if (strpos($video_id, '&') !== false) {
            $video_id = explode("&", $video_id)[0];
        }
        $embed_url = esc_url('https://player.vimeo.com/video/' . $video_id);
    } elseif (strpos($url, 'youtube.com/') !== false) {
        $video_id = explode("v=", $url)[1];
        if (strpos($video_id, '&') !== false) {
            $video_id = explode("&", $video_id)[0];
        }
        $embed_url = esc_url('https://www.youtube.com/embed/' . $video_id);
    } elseif (strpos($url, 'youtu.be/') !== false) {
        $video_id = explode("youtu.be/", $url)[1];
        if (strpos($video_id, '&') !== false) {
            $video_id = explode("&", $video_id)[0];
        }
        $embed_url = esc_url('https://www.youtube.com/embed/' . $video_id);
    }
    return $embed_url;
}

/** Previous and Next Post Navigation **/
if (!function_exists('ethrik_theme_post_navigation')) {
    function ethrik_theme_post_navigation()
    {
        $previous_post = get_previous_post();
        $prev_thumbnail = (is_object($previous_post) && !empty($previous_post)) ? get_the_post_thumbnail($previous_post->ID) : '';
        $next_post = get_next_post();
        $next_post_thumbnail = (is_object($next_post) && !empty($next_post)) ? get_the_post_thumbnail($next_post->ID) : '';
        $col_class = ($previous_post && $next_post) ? 'col-sm-6' : 'col-sm-12';
        if ($previous_post || $next_post): ?>

            <div class="theme_blog_navigation__Wrap">
                <div class="row">
                    <?php if ($previous_post): ?>
                        <div class="<?php echo esc_attr($col_class); ?>">
                            <div class="theme_blog_Nav post_nav_Left <?php echo (empty($prev_thumbnail)) ? 'no-thumb' : ''; ?>">
                                <?php if (!empty($prev_thumbnail)): ?>
                                    <div class="theme_blog_nav_Img prev_nav_left_Img">
                                        <?php echo wp_kses_post($prev_thumbnail); ?>
                                    </div>
                                <?php endif;?>
                                <div class="theme_blog_nav_Inner">
                                    <div class="theme_blog_nav_Label">
                                        <?php $blog_prev_title = ethrik_get_option('blog_prev_title');?>
                                        <?php echo esc_html($blog_prev_title); ?>
                                    </div>
                                    <h3 class="theme_blog_nav_Title"><?php previous_post_link('%link', '%title');?></h3>
                                </div>
                            </div>
                        </div>
                    <?php endif;?>
                    <?php if ($next_post): ?>
                        <div class="<?php echo esc_attr($col_class); ?>">
                            <div class="theme_blog_Nav post_nav_Right <?php echo (empty($next_post_thumbnail)) ? 'no-thumb' : ''; ?>">
                                <?php if (!empty($next_post_thumbnail)): ?>
                                    <div class="theme_blog_nav_Img prev_nav_Right_Img">
                                        <?php echo wp_kses_post($next_post_thumbnail); ?>
                                    </div>
                                <?php endif;?>
                                <div class="theme_blog_Inner">
                                    <div class="theme_blog_nav_Label">
                                        <?php $blog_next_title = ethrik_get_option('blog_next_title');?>
                                        <?php echo esc_html($blog_next_title); ?>
                                    </div>
                                    <h3 class="theme_blog_nav_Title"><?php next_post_link('%link', '%title');?></h3>
                                </div>
                            </div>
                        </div>
                    <?php endif;?>
                </div>
            </div>

        <?php endif;
    }
}

/** Add Contact Methods in the User Profile **/
function ethrik_user_contact_methods($user_contact)
{
    $user_contact['facebook'] = esc_html__('Facebook Profile Link', 'ethrik');
    $user_contact['twitter'] = esc_html__('Twitter Profile', 'ethrik');
    $user_contact['instagram'] = esc_html__('Instagram', 'ethrik');
    $user_contact['pinterest'] = esc_html__('Pinterest', 'ethrik');
    $user_contact['youtube'] = esc_html__('Youtube Profile', 'ethrik');
    return $user_contact;
}
add_filter('user_contactmethods', 'ethrik_user_contact_methods');

/** Author Box **/
function ethrik_theme_author_box()
{
    global $post;

    $display_name = get_the_author_meta('display_name', $post->post_author) ?: get_the_author_meta('nickname', $post->post_author);
    $user_description = get_the_author_meta('user_description', $post->post_author);
    $user_facebook = get_the_author_meta('facebook', $post->post_author);
    $user_twitter = get_the_author_meta('twitter', $post->post_author);
    $user_instagram = get_the_author_meta('instagram', $post->post_author);
    $user_pinterest = get_the_author_meta('pinterest', $post->post_author);
    $user_youtube = get_the_author_meta('youtube', $post->post_author);

    $theme_author_markup = '<div class="author-thumb">' . get_avatar(get_the_author_meta('ID'), 200) . '</div>';
    $theme_author_markup .= '<div class="theme_author_Info">';
    $theme_author_markup .= '<h6 class="theme_author_Title">' . esc_html__('About Author', 'ethrik') . '</h6>';
    $theme_author_markup .= '<h4 class="theme_author__Name">' . esc_html($display_name) . '</h4>';
    $theme_author_markup .= '<p class="theme_author__Description">' . esc_html($user_description) . '</p>';
    $theme_author_markup .= '<div class="theme_author_Socials">';

    $socials = [
        'facebook' => $user_facebook,
        'twitter' => $user_twitter,
        'instagram' => $user_instagram,
        'pinterest' => $user_pinterest,
        'youtube' => $user_youtube,
    ];

    foreach ($socials as $key => $value) {
        if (!empty($value)) {
            $theme_author_markup .= ' <a href="' . esc_url($value) . '" target="_blank" rel="nofollow" title="' . ucfirst($key) . '"><i class="fa fa-' . $key . '"></i> </a>';
        }
    }

    $theme_author_markup .= '</div></div>';

    echo '<div class="author_bio__Wrapper">' . $theme_author_markup . '</div>';
}

/** Categories Count Custom Markup **/
function ethrik_categories_postcount_filter($variable)
{
    $variable = str_replace('(', '<span class="post_count"> ', $variable);
    $variable = str_replace(')', ' </span>', $variable);
    return $variable;
}
add_filter('wp_list_categories', 'ethrik_categories_postcount_filter');

/** Making an API request using PHP **/
// function ethrik_make_api_request(){
//     $client = new \GuzzleHttp\Client();
//     $response = $client->request('GET', 'https://api.opensea.io/api/v2/collections/matr1x-kuku', [
//         'headers' => [
//             'accept' => 'application/json',
//             'x-api-key' => 'a13be099f680490893b3ed54f9c1aaf4',
//         ],
//     ]);

//     echo esc_html($response->getBody());
// }

function ethrik_make_api_request() {
    $response = wp_remote_get('https://api.opensea.io/api/v2/collections/matr1x-kuku', [
        'headers' => [
            'accept' => 'application/json',
            'x-api-key' => 'a13be099f680490893b3ed54f9c1aaf4',
        ],
    ]);

    if (is_wp_error($response)) {
        return 'Error: ' . $response->get_error_message();
    }

    $body = wp_remote_retrieve_body($response);
    return esc_html($body);
}