HEX
Server: nginx/1.18.0
System: Linux vcwordpress 5.15.0-174-generic #184-Ubuntu SMP Fri Mar 13 18:41:50 UTC 2026 x86_64
User: root (0)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/stg-everycred.com/wp-content/themes/everycred/inc/custom-functions.php
<?php

/**
 * Theme custom functions and hooks
 */


/**
 * Acf option page
 */
if (function_exists('acf_add_options_page')) {

    acf_add_options_page(
        array(
            'page_title'    => 'Theme Option',
            'menu_title'    => 'Theme Option',
            'menu_slug'     => 'theme-general-settings',
            'capability'    => 'edit_posts',
            'redirect'      => false
        )
    );
    acf_add_options_page(array(
        'page_title' => 'Global CTA Settings',
        'menu_title' => 'Global CTA',
        'menu_slug'  => 'global-cta-settings',
        'capability' => 'edit_posts',
        'redirect'   => false
    ));
}
/**
 * ACF Local JSON — save path + direct registration from JSON files.
 * Direct registration via acf_add_local_field_group() is the most reliable
 * approach and guarantees the group appears under ACF > Field Groups > Sync Available.
 */
add_filter('acf/settings/save_json', function ($path) {
    return get_stylesheet_directory() . '/acf-json';
});
add_filter('acf/settings/load_json', function ($paths) {
    $paths[] = get_stylesheet_directory() . '/acf-json';
    return $paths;
});
add_action('acf/init', function () {
    if (!function_exists('acf_add_local_field_group')) {
        return;
    }
    $dir = get_stylesheet_directory() . '/acf-json';
    foreach (glob($dir . '/*.json') as $file) {
        $data = json_decode(file_get_contents($file), true);
        if (!empty($data['key'])) {
            acf_add_local_field_group($data);
        }
    }
});

/**
 * Allow SVG upload by adding SVG MIME type to the allowed list.
 */
function Allow_Svg_upload($mimes)
{
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'Allow_Svg_upload');

/**  
 * Menu Registration 
 */
function customNewMenu()
{
    register_nav_menus(
        array(
            'primary' => esc_html__('Primary menu', 'twentytwentyone'),
            'solution' => esc_html__('Solution menu', 'twentytwentyone'),
            'applications' => esc_html__('Applications menu', 'twentytwentyone'),
            'products' => esc_html__('Products menu', 'twentytwentyone'),
            'resources-support' => esc_html__('Resources & Support menu', 'twentytwentyone'),
            'footer-menu' => esc_html__('Footer menu', 'twentytwentyone'),
        )
    );
}
add_action('init', 'customNewMenu');


/**
 * Li custom class for wp menu
 */
function customNavMenuClasses($classes)
{
    // Add your custom class here
    $classes[] = 'nav-item dropdown pe-5 position-relative';
    return $classes;
}
add_filter('nav_menu_css_class', 'customNavMenuClasses', 10, 4);

/**
 * Anchor tag custom class
 */
function addLinkAtts($atts)
{
    $atts['class'] = "nav-link dropdown-toggle font-18 text-semi text-white p-0";
    $atts['id'] = "navbarDarkDropdownMenuLink";
    return $atts;
}
add_filter('nav_menu_link_attributes', 'addLinkAtts');

// Add feature image in default blog 
add_theme_support('post-thumbnails');

/**
 * Anchor tag custom class
 */
function commonInnerPageBanner()
{

    $common_banner_image    =   get_field('common_banner_image');
    $banner_sub_text        =   get_field('banner_sub_text');
    $banner_heading         =   get_field('banner_heading');
    $banner_description     =   get_field('banner_description');
    $output = '';
    if ($common_banner_image  || $banner_sub_text  || $banner_heading  || $banner_description) {
        // $output .= '<section class="contact-banner py-120 pb-5 pb-lg-0 bg-black position-relative">';
        // $output .= '<div class="container">';
        // $output .= '<div class="row">';
        // $output .= '<div class="col-12 col-lg-6 text-start text-lg-center position-relative">';
        // $output .= '<div class="banner-left-img d-none d-lg-block position-absolute start-0 top-0">';
        // $output .= '<img src="' . get_template_directory_uri() . '/assets/images/contact-img-left.svg" alt="banner-img">';
        // $output .= '</div>';
        // if ($common_banner_image) {
        //     $output .= '<img src="' . $common_banner_image['url'] . '" title    ="' . $common_banner_image['title'] . '" alt="' . $common_banner_image['alt'] . '" class="banner-img">';
        // }
        // $output .= '<div class="banner-right-img d-none d-lg-block position-absolute top-0 end-0">';
        // $output .= '<img src="' . get_template_directory_uri() . '/assets/images/contact-img-right.svg" alt="banner-img">';
        // $output .= '</div>';
        // $output .= '</div>';
        // $output .= '<div class="col-12 col-lg-1"></div>';
        // $output .= '<div class="col-12 col-lg-5 mt-4 mt-lg-0">';
        // if ($banner_sub_text) {
        //     $output .= '<div class="font-16 text-uppercase text-bold"> ' . $banner_sub_text . ' </div>';
        // }
        // if ($banner_heading) {
        //     $output .= '<div class="font-52 text-bold my-4">' . $banner_heading . '</div>';
        // }
        // if ($banner_description) {
        //     $output .= '<div class="font-20">' . $banner_description . '</div>'; 
        // }
        // $output .= '</div>';
        // $output .= '</div>';
        // $output .= '</div>'; 
        // $output .= '<div class="position-absolute start-0 w-100 bottom-white-pattern">';
        // $output .= '<img src="' . get_template_directory_uri() . '/assets/images/round-pattern-white.svg" alt="banner-img" width="100%">';
        // $output .= '</div>';
        // $output .= '</section>';
    }
    return $output;
}
add_shortcode('inner_page_banner', 'commonInnerPageBanner');


/**
 * Css and js call 

 */
function addThemeScripts()
{
    // ── Core CSS (loaded async to eliminate render-blocking) ──────────────
    wp_enqueue_style('bootstrap.min',    get_template_directory_uri() . '/assets/css/bootstrap.min.css',    array(), '1.1', 'all');
    wp_enqueue_style('styles',           get_template_directory_uri() . '/assets/css/style.css',            array(), '1.1', 'all');
    wp_enqueue_style('brand-identity',   get_template_directory_uri() . '/assets/css/brand-identity.css',   array(), '1.1', 'all');
    wp_enqueue_style('theme-style',      get_template_directory_uri() . '/style.css',                       array(), '1.1', 'all');

    // ── Utility CSS (async) ───────────────────────────────────────────────
    wp_enqueue_style('owl.carousel',     get_template_directory_uri() . '/assets/css/owl.carousel.css',     array(), '1.1', 'all');
    wp_enqueue_style('owl.theme.default', get_template_directory_uri() . '/assets/css/owl.theme.default.css', array(), '1.1', 'all');
    // datepicker.min.css is scoped to contact/support pages only (see below)

    // ── Page-specific CSS ─────────────────────────────────────────────────
    if (is_front_page()) {
        wp_enqueue_style('home', get_template_directory_uri() . '/assets/css/home.css', array(), '1.1', 'all');
    }
    if (is_single()) {
        wp_enqueue_style('blog-detail', get_template_directory_uri() . '/assets/css/blog-detail.css', array(), '1.1', 'all');
    }
    if (is_page('blog')) {
        wp_enqueue_style('blog-listing', get_template_directory_uri() . '/assets/css/blog-listing.css', array(), '1.1', 'all');
    }
    if (is_page('contact-us') || is_page('support')) {
        wp_enqueue_style('contact-us', get_template_directory_uri() . '/assets/css/contact-us.css', array(), '1.1', 'all');
    }
    if (is_page(array('issuer', 'holder', 'verifier'))) {
        wp_enqueue_style('product-pages', get_template_directory_uri() . '/assets/css/product-pages.css', array(), '1.1', 'all');
    }
    // Pricing CSS — only on actual pricing pages (was incorrectly loaded everywhere)
    if (is_page(array('everycred-pricing', 'pricing'))) {
        wp_enqueue_style('pricing', get_template_directory_uri() . '/assets/css/pricing.css', array(), '1.1', 'all');
    }
    if (is_page(array('trust-credentials', 'trust-method', 'trust-supply-chain'))) {
        wp_enqueue_style('trust-credentials', get_template_directory_uri() . '/assets/css/trust-credentials.css', array(), '1.1', 'all');
    }
    if (is_singular('industries')) {
        wp_enqueue_style('application', get_template_directory_uri() . '/assets/css/application.css', array(), '1.1', 'all');
    }
    if (is_page('insights') || is_post_type_archive('case_studies') || is_post_type_archive('white_papers')) {
        wp_enqueue_style('insights', get_template_directory_uri() . '/assets/css/insights.css', array(), '1.1', 'all');
    }
    if (is_page('industries')) {
        wp_enqueue_style('industry-list', get_template_directory_uri() . '/assets/css/industry-list.css', array(), '1.1', 'all');
    }
    if (is_page('developers')) {
        wp_enqueue_style('developers', get_template_directory_uri() . '/assets/css/developers.css', array(), '1.1', 'all');
    }
    if (is_page('faq')) {
        wp_enqueue_style('faq', get_template_directory_uri() . '/assets/css/faq.css', array(), '1.1', 'all');
    }
    if (is_page_template('templates/page-home-v2.php')) {
        wp_enqueue_style('home-v2', get_template_directory_uri() . '/assets/css/home-v2.css', array(), '1.1', 'all');
    }

    // ── JavaScript ───────────────────────────────────────────────────────
    // NOTE: Do NOT enqueue a custom jQuery — WordPress already provides it.
    wp_enqueue_script('bootstrap.bundle.min', get_template_directory_uri() . '/assets/js/bootstrap.bundle.min.js', array('jquery'), '1.1', true);

    // Owl Carousel — only load on pages that actually use the carousel
    if (is_front_page() || is_page('blog') || is_singular('post')) {
        wp_enqueue_script('owl.carousel.min', get_template_directory_uri() . '/assets/js/owl.carousel.min.js', array('jquery'), '1.1', true);
        wp_enqueue_script('carousel-slider', get_template_directory_uri() . '/assets/js/carousel-slider.js', array('jquery', 'owl.carousel.min'), '1.1', true);
    }

    // Lottie — used for animations
    wp_enqueue_script('lottie.min', get_template_directory_uri() . '/assets/js/lottie.min.js', array(), '1.1', true);

    // AOS — used for scroll animations
    wp_enqueue_script('aos', get_template_directory_uri() . '/assets/js/aos.js', array(), '1.1', true);

    // Main Custom JS
    wp_enqueue_script('custom', get_template_directory_uri() . '/assets/js/custom.js', array('jquery'), '1.1', true);
    wp_enqueue_script('seo-tracking-scripts', get_template_directory_uri() . '/assets/js/seo-tracking-scripts.js', array('jquery'), '1.1', true);

    // Datepicker CSS + JS — only load on contact/form pages
    if (is_page('contact-us') || is_page('support')) {
        wp_enqueue_style('datepicker.min', get_template_directory_uri() . '/assets/css/datepicker.min.css', array(), '1.1', 'all');
        wp_enqueue_script('bootstrap.datepicker.min', get_template_directory_uri() . '/assets/js/datepicker.min.js', array('jquery'), '1.1', true);
    }
}
add_action('wp_enqueue_scripts', 'addThemeScripts');

/**
 * 1. Enqueue Cookie Consent Assets
 */
function vc_enqueue_cookie_consent_assets()
{
    $theme_uri = get_stylesheet_directory_uri();
    $version = '1.1.1';

    wp_enqueue_style('c15t-style', $theme_uri . '/cookie-consent/cookie-consent.css', [], $version);
    wp_enqueue_script('c15t-core', $theme_uri . '/cookie-consent/cookie-consent.js', [], $version, true);
    wp_script_add_data('c15t-core', 'strategy', 'defer');

    wp_enqueue_script('c15t-init', $theme_uri . '/cookie-consent/cookie-init.js', ['c15t-core'], $version, true);
    wp_script_add_data('c15t-init', 'strategy', 'defer');
}
add_action('wp_enqueue_scripts', 'vc_enqueue_cookie_consent_assets');

/** 
 * Show filtered blogs after click on tags 
 */

function tagFilteredData()
{
    // Set your taxonomy and terms
    global $post;
    if (!empty($_POST['tags_id']) || $_POST['tags_id'] !== "") {
        $terms = $_POST['tags_id'];
    }
    $output = '';
    $args = array(
        'post_type' => 'post',  // Set the post type you want to query
        'post_status' => 'publish',
        'posts_per_page' => 3,
        'order' => 'DESC',
        'tax_query' => array(
            array(
                'taxonomy' => 'post_tag',
                'field'    => 'term_id',  // Use 'term_id', 'slug', or 'name'
                'terms'    => $terms,
            ),
        ),
    );
    $blog_query = new WP_Query($args);
    $i = 1;
    if ($blog_query->have_posts()) {
        while ($blog_query->have_posts()) {
            $blog_query->the_post();
            $title      = get_the_title();
            $content    = get_the_excerpt();
            $trimmed_content = wp_trim_words($content, 12);
            $blog_img   = get_the_post_thumbnail_url($post->ID);
            $date       = get_the_date('d M, Y', $post->ID);
            // $author     = get_the_author();
            $blog_read_time  = get_field('blog_read_time', $post->ID);
            if ($i == 1) {
                $output .= '<div class="col-12 col-lg-6">';
                $output .= '<div class="refine-blog-img-left overflow-hidden">';
                $output .= '<img src="' . $blog_img . '" alt="img" width="100%" />';
                $output .= '</div>';
            }
            if ($i == 2) {
                $output .= '<div class="col-12 col-lg-6 mt-3 mt-lg-0 d-block d-md-flex d-lg-block gap-3 gap-lg-0">';
            }
            if ($i == 2) {
                $output .= '<div class="blog-box d-flex gap-4 mt-4 mt-md-0">';
            }
            if ($i == 3) {
                add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php

                add_action('template_redirect', 'add_ajax');
                $output .= '<div class="blog-box d-flex gap-4 mt-4 mt-md-0 mt-lg-4">';
            }
            if ($i == 2 || $i == 3) {
                $output .= '<div class="img-box overflow-hidden">';
                $output .= '<a href="' . get_permalink() . '"><img src="' . $blog_img . '" alt="img" width="100%" />';
                $output .= '</div>';
            }
            if ($i == 2 || $i == 3) {
                $output .= '<div class="blog-img-content">';
            }
            $output .= '<div class="font-14 text-blue my-2">' . $date . '</div>';
            $output .= '<div class="font-20 text-black text-semi d-flex">' . $title . ' <img
            src="' . get_template_directory_uri() . '/assets/images/upper-right-arrow.svg" alt="arrow" class="ms-auto" />';
            $output .= '</div>';
            if ($i == 1) {
                $output .= '<div class="font-16 text-black mt-2 mb-3">' . $trimmed_content . '</div>';
            }
            if ($i == 2 || $i == 3) {
                $output .= '<div class="font-16 text-black mt-2 mb-3 blog-box-content"> ' . $trimmed_content . '</div>';
            }
            $post_tags = get_the_tags();

            if ($post_tags) {
                $output .= '<div class="d-flex align-items-center gap-3 flex-wrap">';
                $s = 1;
                foreach ($post_tags as $tag) {
                    $tag_id = $tag->term_id;
                    $is_selected = get_term_meta($tag_id, 'post_tag', true);
                    if ($s == 1) {
                        $output .= '<div class="purple-badge d-flex align-items-center justify-content-center font-16 px-3">' . $tag->name . '</div>';
                    } elseif ($s == 2) {
                        $output .= '<div class="blue-badge d-flex align-items-center justify-content-center font-16 px-3">' . $tag->name . '</div>';
                    } elseif ($s == 3) {
                        $output .= '<div class="red-badge d-flex align-items-center justify-content-center font-16 px-3">' . $tag->name . '</div>';
                    }
                    if ($s == 3) {
                        $s = 1;
                    } else {
                        $s++;
                    }
                }
                wp_reset_postdata();
                $output .= '</div>';
            }
            if ($i == 2 || $i == 3) {
                $output .= '</div>';
            }
            if ($i == 3) {
                $output .= '</div>';
            }
            if ($i == 2) {
                $output .= '</div>';
            }
            if ($i == 3) {
                $output .= '</div>';
            }
            if ($i == 1) {
                $output .= '</div>';
            }
            $i++;
        }
        wp_reset_postdata();
        wp_reset_query();
    } else {
        $output .= '
        <iframe src="https://lottie.host/embed/39eb5f48-24ad-4118-a5a3-d24dd9758426/UvglMS7NCb.json">
            <iframe src="' . get_template_directory_uri() . '/assets/images/no-data.html"></iframe>
<div class="font-16 text-bold text-black text-uppercase no-data-found text-center pt-4">No blog found!</div>';
    }
    echo $output;
    die();
}
add_action('wp_ajax_tagFilteredData', 'tagFilteredData');
add_action('wp_ajax_nopriv_tagFilteredData', 'tagFilteredData');


function add_ids_to_headings($content)
{
    // Add IDs to all h2 headings
    $content = preg_replace_callback(
        '/<(h2|h2 class="wp-block-heading")>(.*?)<\/(h2|h2)>/',
        function ($match) {
            $heading = $match[2];
            $anchor = sanitize_title($heading);
            return '<h2 id="' . $anchor . '">' . $heading . '</h2>';
        },
        $content
    );
    return $content;
}

add_filter('the_content', 'add_ids_to_headings');

// add_filter('use_block_editor_for_post', '__return_false', 10);

function mailtrap($phpmailer)
{
    if (defined('SMTP_HOST')) {
        $phpmailer->isSMTP();
        $phpmailer->Host = SMTP_HOST;
        $phpmailer->SMTPAuth = true;

        if (defined('SMTP_PORT')) {
            $phpmailer->Port = SMTP_PORT;
        }
        if (defined('SMTP_USER')) {
            $phpmailer->Username = SMTP_USER;
        }
        if (defined('SMTP_PASS')) {
            $phpmailer->Password = SMTP_PASS;
        }
        if (defined('SMTP_SECURE')) {
            $phpmailer->SMTPSecure = SMTP_SECURE;
        }
        if (defined('SMTP_FROM')) {
            $phpmailer->From = SMTP_FROM;
        }
    }
}

add_action('phpmailer_init', 'mailtrap');


// Reading time function for the post page
function calculate_reading_time($content)
{
    $word_count = str_word_count(strip_tags($content));
    $words_per_minute = 200;
    $reading_time = ceil($word_count / $words_per_minute);
    return $reading_time;
}
function display_reading_time()
{
    $content = get_post_field('post_content', get_the_ID());
    $reading_time = calculate_reading_time($content);
    echo '<span class="reading-time">' . sprintf(_n('%d min', '%d min', $reading_time), $reading_time) . ' read</span>';
}

/**
 * Get child category
 */

function get_child_categories()
{
    $parent_id = $_POST['parent_id'];
    $child_categories = get_categories(array(
        'parent' => $parent_id,
        'hide_empty' => false
    ));

    $categories = array();
    foreach ($child_categories as $category) {
        $categories[] = array(
            'name' => $category->name,
            'cat_id' => $category->term_id
        );
    }

    wp_send_json_success($categories);
}
add_action('wp_ajax_get_child_categories', 'get_child_categories');
add_action('wp_ajax_nopriv_get_child_categories', 'get_child_categories');

add_action('wp_ajax_get_filtered_blogs', 'get_filtered_blogs');
add_action('wp_ajax_nopriv_get_filtered_blogs', 'get_filtered_blogs');

function get_filtered_blogs()
{
    $search_keyword = isset($_POST['searchKeyword']) ? sanitize_text_field($_POST['searchKeyword']) : '';
    $content_type   = isset($_POST['contentType'])   ? sanitize_text_field($_POST['contentType'])   : '';
    $page           = isset($_POST['page'])          ? max(1, intval($_POST['page']))               : 1;
    $posts_per_page = 12;

    if (!empty($content_type)) {
        $post_types = array($content_type);
    } else {
        $post_types = array('post', 'case_studies', 'white_papers');
    }

    $args = array(
        'post_type'      => $post_types,
        'post_status'    => 'publish',
        'posts_per_page' => $posts_per_page,
        'paged'          => $page,
        'orderby'        => 'date',
        'order'          => 'DESC',
    );

    if (!empty($search_keyword)) {
        $args['s'] = $search_keyword;
    }

    $query = new WP_Query($args);

    $total_posts    = (int) $query->found_posts;
    $posts_returned = (int) $query->post_count;
    $html           = '';

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $post_type = get_post_type();

            if ($post_type === 'case_studies') {
                $type_label = 'Case Study';
            } elseif ($post_type === 'white_papers') {
                $type_label = 'White Paper';
            } else {
                $subCats        = get_the_category(get_the_ID());
                $contentTypeCat = [];
                foreach ($subCats as $key => $subCat) {
                    $parentCategory = get_category($subCat->category_parent);
                    if ($parentCategory && $parentCategory->slug == 'content-type') {
                        $contentTypeCat[$key] = $subCat->name;
                    }
                }
                if (!empty($contentTypeCat)) {
                    $lowestKey  = min(array_keys($contentTypeCat));
                    $type_label = $contentTypeCat[$lowestKey];
                } else {
                    $type_label = 'Blog';
                }
            }

            $thumbnail_url = get_the_post_thumbnail_url() ? get_the_post_thumbnail_url() : '';
            $title         = get_the_title();
            $permalink     = get_permalink();
            $date          = get_the_date('d M Y');
            $post_id       = get_the_ID();

            if ($post_type === 'white_papers') {
                $pdf_field = get_field('attach_whitepaper_pdf', $post_id);
                $pdf_id    = is_array($pdf_field) ? $pdf_field['ID'] : $pdf_field;

                $html .= '
        <div class="col-12 col-md-6 col-lg-4">
            <div class="list-box h-100" style="cursor:pointer;">
                <div class="image-box">
                    <img class="w-100" src="' . esc_url($thumbnail_url) . '" alt="' . esc_attr($title) . '" />
                </div>
                <div class="desc-box bg-white">
                    <div class="title-txt font-18 d-flex justify-content-between align-items-center">
                        <span>White Paper | ' . esc_html($date) . '</span>
                        ' . ($pdf_id ? '<span class="download-pdf-btn" data-pdf-id="' . esc_attr($pdf_id) . '" data-post-id="' . esc_attr($post_id) . '" data-title="' . esc_attr($title) . '">Download PDF</span>' : '') . '
                    </div>
                    <div class="desc-txt font-20 text-semi font-light-black mt-2 mt-md-3">' . esc_html($title) . '</div>
                </div>
            </div>
        </div>';
            } else {

                $html .= '
        <div class="col-12 col-md-6 col-lg-4">
            <a href="' . esc_url($permalink) . '">
                <div class="list-box h-100">
                    <div class="image-box">
                        <img class="w-100" src="' . esc_url($thumbnail_url) . '" alt="' . esc_attr($title) . '" />
                    </div>
                    <div class="desc-box bg-white">
                        <div class="title-txt font-18">' . esc_html($type_label) . ' | ' . esc_html($date) . '</div>
                        <div class="desc-txt font-20 text-semi font-light-black mt-2 mt-md-3">' . esc_html($title) . '</div>
                    </div>
                </div>
            </a>
        </div>';
            }
        }
        wp_reset_postdata();
    } else {
        $html .= '<div class="col-12 text-center py-4">';
        $html .= '<p style="color:#000; font-size:16px; font-weight:500;">No results found.</p>';
        $html .= '</div>';
    }

    wp_send_json(array(
        'html'          => $html,
        'totalPosts'    => $total_posts,
        'postsReturned' => $posts_returned,
    ));
}


/**
 * Add prefix in blog post permalink
 */

function add_blog_prefix_to_post_link($permalink, $post)
{
    if ($post->post_type == 'post') {
        $permalink = home_url('/blog/' . $post->post_name . '/');
    }
    return $permalink;
}
add_filter('post_link', 'add_blog_prefix_to_post_link', 10, 2);

function add_custom_post_rewrite_rules()
{
    add_rewrite_rule('^blog/([^/]+)/?', 'index.php?post_type=post&name=$matches[1]', 'top');
}
add_action('init', 'add_custom_post_rewrite_rules');

function flush_rewrite_rules_on_activation()
{
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'flush_rewrite_rules_on_activation');


/**
 * Zoho CRM integration
 */

add_action('init', 'handle_zoho_oauth_callback');

function handle_zoho_oauth_callback()
{

    if (isset($_GET['code'])) {

        $code = sanitize_text_field($_GET['code']);
        $token_url = 'https://accounts.zoho.in/oauth/v2/token';
        $client_id = '1000.YOE63FD6VGVYG9FCIY23Z6IQ3M41FO';
        $client_secret = 'bc2b1996daf2addd1d11fcc64810e91fbe1aeadfea';
        $redirect_uri = 'https://everycred.com/zoho-callback';
        $response = wp_remote_post($token_url, array(
            'body' => array(
                'grant_type' => 'authorization_code',
                'client_id' => $client_id,
                'client_secret' => $client_secret,
                'redirect_uri' => $redirect_uri,
                'code' => $code,
            )
        ));

        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            echo 'Something went wrong: ' . esc_html($error_message);
            return;
        }
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($body['access_token'])) {
            update_option('zoho_access_token', sanitize_text_field($body['access_token']));
        }

        if (isset($body['refresh_token'])) {
            update_option('zoho_refresh_token', sanitize_text_field($body['refresh_token']));
        }
    }
}

function get_zoho_access_token()
{
    $access_token = get_option('zoho_access_token');
    $refresh_token = get_option('zoho_refresh_token');
    $token_url = 'https://accounts.zoho.in/oauth/v2/token';
    $client_id = '1000.YOE63FD6VGVYG9FCIY23Z6IQ3M41FO';
    $client_secret = 'bc2b1996daf2addd1d11fcc64810e91fbe1aeadfea';
    $response = wp_remote_post($token_url, array(
        'body' => array(
            'grant_type' => 'refresh_token',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'refresh_token' => $refresh_token,
        )
    ));

    $body = json_decode(wp_remote_retrieve_body($response), true);
    if (isset($body['access_token'])) {
        update_option('zoho_access_token', $body['access_token']);
    } else {
        error_log('Failed to refresh access token: ' . $body['error']);
    }

    return $access_token;
}

add_action('wpcf7_before_send_mail', 'send_data_to_bigin');

function send_data_to_bigin($contact_form)
{
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $data = $submission->get_posted_data();
        $zoho_data = [
            'data' => [
                [
                    'Subject' => 'Connect with EveryCRED',
                    'Account_Name' => $data['company-name'] ?? '',
                    'First_Name' => $data['first-name'] ?? '',
                    'Last_Name' => $data['last-name'] ?? '',
                    'Email' => $data['email'] ?? '',
                    'Mobile' => $data['contact-number'] ?? '',
                    'Designation' => $data['designation'] ?? '',
                    'Description' => $data['description'] ?? '',
                    'Tag' => [
                        ['name' => 'EveryCRED']
                    ]
                ]
            ]
        ];

        $url = 'https://www.zohoapis.in/bigin/v2/Contacts';
        $access_token = get_zoho_access_token();

        $headers = array(
            'Authorization' => 'Zoho-oauthtoken ' . $access_token,
            'Content-Type' => 'application/json'
        );

        $response = wp_remote_post($url, array(
            'method'    => 'POST',
            'headers'   => $headers,
            'body'      => json_encode($zoho_data)
        ));

        if (is_wp_error($response)) {
            error_log('Zoho API error: ' . $response->get_error_message());
        } else {
            $response_body = json_decode(wp_remote_retrieve_body($response), true);
            if (isset($response_body['data']) && !empty($response_body['data'])) {
                error_log('Contact created successfully!');
            }
        }
    }
}

/**
 * Add defer attribute to specific heavy front-end enqueued scripts
 */
function everycred_defer_frontend_scripts($tag, $handle, $src)
{
    if (is_admin() || strpos($tag, 'defer') !== false) {
        return $tag;
    }

    $defer_handles = array(
        'bootstrap.bundle.min',
        'owl.carousel.min',
        'carousel-slider',
        'bootstrap.datepicker.min',
        'c15t-core',
        'c15t-init',
        'lottie.min',
        'aos',
        'custom',
        'jquery-migrate', // No theme code uses deprecated jQuery APIs
    );

    if (in_array($handle, $defer_handles)) {
        return str_replace(' src', ' defer="defer" src', $tag);
    }

    return $tag;
}
add_filter('script_loader_tag', 'everycred_defer_frontend_scripts', 10, 3);

/**
 * Defer non-critical CSS by loading it asynchronously
 */
function everycred_async_css($html, $handle, $href, $media)
{
    if (is_admin()) {
        return $html;
    }

    /**
     * These CSS files are loaded asynchronously (non-render-blocking).
     * Critical CSS for above-the-fold content is already inlined in header.php,
     * so there is NO FOUC or CLS risk from deferring these stylesheets.
     *
     * The media="print" + onload trick is the recommended pattern for async CSS:
     * https://web.dev/defer-non-critical-css/
     */
    $async_css = array(
        // Core CSS — safely async due to critical CSS already inlined in header.php
        'bootstrap.min',   // 189 KiB — render-blocking → async (Bootstrap grid/nav inlined)
        'styles',
        'theme-style',
        // Secondary framework CSS — safe to async
        'brand-identity',
        'home',
        // Utility / plugin CSS
        'owl.carousel',
        'owl.theme.default',
        'datepicker.min',
        'c15t-style',
        // WordPress / plugin CSS
        'wp-block-library',
        'dashicons',
        'rank-math',
        'contact-form-7',
        'admin-bar',
        // Page-specific CSS
        'blog-detail',
        'blog-listing',
        'contact-us',
        'product-pages',
        'pricing',
        'trust-credentials',
        'application',
        'insights',
        'industry-list',
        'developers',
        'faq',
        'home-v2',
        'aos',
    );

    if (in_array($handle, $async_css)) {
        $noscript = '<noscript><link rel="stylesheet" href="' . esc_url($href) . '" /></noscript>';
        $html     = '<link rel="stylesheet" id="' . esc_attr($handle) . '-css" href="' . esc_url($href) . '" media="print" onload="this.media=\'all\'" />' . $noscript;
    }

    return $html;
}
add_filter('style_loader_tag', 'everycred_async_css', 10, 4);


function get_user_ip()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    }
    return $_SERVER['REMOTE_ADDR'];
}

function get_ip_location()
{
    $ip = get_user_ip();

    $response = wp_remote_get("https://ipapi.co/{$ip}/json/");

    if (is_wp_error($response)) {
        return false;
    }

    $data = json_decode(wp_remote_retrieve_body($response), true);

    return [
        'ip'      => $ip,
        'country' => $data['country_name'] ?? '',
        'state'   => $data['region'] ?? '',
        'city'    => $data['city'] ?? '',
    ];
}
add_filter('wpcf7_special_mail_tags', function ($output, $name) {

    if (!in_array($name, [
        'server-ip',
        'server-country',
        'server-state',
        'server-city'
    ])) {
        return $output;
    }

    $location = get_ip_location();
    if (!$location) return '';

    switch ($name) {
        case 'server-ip':
            return esc_html($location['ip']);
        case 'server-country':
            return esc_html($location['country']);
        case 'server-state':
            return esc_html($location['state']);
        case 'server-city':
            return esc_html($location['city']);
    }

    return $output;
}, 10, 2);