<?php
/**
 * Actions Hook for the theme
 *
 * @package Bravisthemes
 */
add_action('after_setup_theme', 'kaitex_setup');
function kaitex_setup(){

    //Set the content width in pixels, based on the theme's design and stylesheet.
    $GLOBALS['content_width'] = apply_filters( 'kaitex_content_width', 1200 );

    // Make theme available for translation.
    load_theme_textdomain( 'kaitex', get_template_directory() . '/languages' );

    // Custom Header
    add_theme_support( 'custom-header' );

    // Add default posts and comments RSS feed links to head.
    add_theme_support( 'automatic-feed-links' );

    // Let WordPress manage the document title.
    add_theme_support( 'title-tag' );

    // Enable support for Post Thumbnails on posts and pages.
    add_theme_support( 'post-thumbnails' );

    set_post_thumbnail_size( 1170, 710 );

    // This theme uses wp_nav_menu() in one location.
    register_nav_menus( array(
        'primary' => esc_html__( 'Primary', 'kaitex' ),
    ) );

    // Add theme support for selective refresh for widgets.
    add_theme_support( 'customize-selective-refresh-widgets' );

    // Add support for core custom logo.
    add_theme_support( 'custom-logo', array(
        'height'      => 250,
        'width'       => 250,
        'flex-width'  => true,
        'flex-height' => true,
    ) );

    // Post formats
    add_theme_support( 'post-formats', array (
        'video',
    ) );

    // Enable support for Post Thumbnails on posts and pages.
    add_theme_support('post-thumbnails');
    add_image_size( 'kaitex-thumb-small', 500, 340, true );
    add_image_size( 'kaitex-thumb-medium', 1000, 584, true );
    add_image_size( 'kaitex-thumb-large', 856, 600, true );
    add_image_size( 'kaitex-thumb-wg-products', 255, 315, true );

    add_theme_support( 'woocommerce' );
    add_theme_support( 'wc-product-gallery-zoom' );
    add_theme_support( 'wc-product-gallery-lightbox' );
    add_theme_support( 'wc-product-gallery-slider' );
    remove_theme_support('widgets-block-editor');

}

/**
 * Register Widgets Position.
 */
add_action( 'widgets_init', 'kaitex_widgets_position' );
function kaitex_widgets_position() {
	register_sidebar( array(
		'name'          => esc_html__( 'Blog Sidebar', 'kaitex' ),
		'id'            => 'sidebar-blog',
		'before_widget' => '<section id="%1$s" class="widget %2$s"><div class="widget-content">',
		'after_widget'  => '</div></section>',
		'before_title'  => '<h2 class="widget-title"><span>',
		'after_title'   => '</span></h2>',
	) );

	if (class_exists('ReduxFramework')) {
		register_sidebar( array(
			'name'          => esc_html__( 'Page Sidebar', 'kaitex' ),
			'id'            => 'sidebar-page',
			'before_widget' => '<section id="%1$s" class="widget %2$s"><div class="widget-content">',
			'after_widget'  => '</div></section>',
			'before_title'  => '<h2 class="widget-title"><span>',
			'after_title'   => '</span></h2>',
		) );
	}

	if ( class_exists( 'Woocommerce' ) ) {
		register_sidebar( array(
			'name'          => esc_html__( 'Shop Sidebar', 'kaitex' ),
			'id'            => 'sidebar-shop',
			'before_widget' => '<section id="%1$s" class="widget %2$s"><div class="widget-content">',
			'after_widget'  => '</div></section>',
			'before_title'  => '<h2 class="widget-title"><span>',
			'after_title'   => '</span></h2>',
		) );
	}
}

/**
 * Enqueue Styles Scripts : Front-End
 */
add_action( 'wp_enqueue_scripts', 'kaitex_scripts' );
function kaitex_scripts() {

    /* Popup Libs */
    wp_enqueue_style( 'jquery-ui', get_template_directory_uri() . '/assets/css/jquery-ui.css', array(), '1.0.0' );
    wp_enqueue_style('magnific-popup', get_template_directory_uri() . '/assets/css/libs/magnific-popup.min.css', array(), '1.1.0');
    wp_enqueue_script( 'magnific-popup', get_template_directory_uri() . '/assets/js/libs/magnific-popup.min.js', array( 'jquery' ), '1.1.0', true );
    wp_enqueue_style('wow-animate', get_template_directory_uri() . '/assets/css/libs/animate.min.css', array(), '1.1.0');
    wp_enqueue_script( 'wow-animate', get_template_directory_uri() . '/assets/js/libs/wow.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'nice-select', get_template_directory_uri() . '/assets/js/libs/nice-select.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'progressbar', get_template_directory_uri() . '/assets/js/libs/progressbar.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style('overlayscrollbars-style', get_template_directory_uri() . '/assets/css/libs/overlayscrollbars.min.css', array(), '1.1.0');
    wp_enqueue_script( 'overlayscrollbars', get_template_directory_uri() . '/assets/js/libs/overlayscrollbars.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'tween-max', get_template_directory_uri() . '/assets/js/libs/tweenmax.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'scroll-magic', get_template_directory_uri() . '/assets/js/libs/scrollmagic.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'animation-gsap', get_template_directory_uri() . '/assets/js/libs/animation-gsap.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'parallax-scroll', get_template_directory_uri() . '/assets/js/libs/parallax-scroll.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'gsap-lib', get_template_directory_uri() . '/assets/js/libs/gsap.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'scroll-trigger-lib', get_template_directory_uri() . '/assets/js/libs/scroll-trigger.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'anime-lib', get_template_directory_uri() . '/assets/js/libs/anime.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'split-text-lib', get_template_directory_uri() . '/assets/js/libs/split-text.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'scroll-smoother-lib', get_template_directory_uri() . '/assets/js/libs/scroll-smoother.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'curtains-lib', get_template_directory_uri() . '/assets/js/libs/curtains.umd.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'three-lib', get_template_directory_uri() . '/assets/js/libs/three.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'drawsvgplugin3-lib', get_template_directory_uri() . '/assets/js/libs/drawsvgplugin3.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_style('splitting-style', get_template_directory_uri() . '/assets/css/libs/splitting.css', array(), '1.1.0');
    wp_enqueue_script( 'splitting-lib', get_template_directory_uri() . '/assets/js/libs/splitting.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'scrollout-lib', get_template_directory_uri() . '/assets/js/libs/scroll-out.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'hammer-lib', get_template_directory_uri() . '/assets/js/libs/hammer.min.js', array( 'jquery' ), '1.0.0', true );
    wp_enqueue_script( 'jquery-ui-slider' );

    /* Parallax Libs */
    wp_enqueue_script( 'vanilla-tilt', get_template_directory_uri() . '/assets/js/libs/vanilla-tilt.min.js', array( 'jquery' ), '1.0.0', true );

    /* Icons Lib - CSS */
    wp_enqueue_style('bootstrap-icons', get_template_directory_uri() . '/assets/fonts/bootstrap-icons/css/bootstrap-icons.css');
    wp_enqueue_style('ionicons', get_template_directory_uri() . '/assets/fonts/ionicons/css/ionicons.css');

    /* Cookie */
    wp_register_script( 'pxl-cookie', get_template_directory_uri() . '/assets/js/libs/cookie.js', array( 'jquery' ), '1.4.1', true );

    // Image Before After
    wp_register_script( 'event-move', get_template_directory_uri() . '/assets/js/libs/eventmove.min.js', array( 'jquery' ), '1.0.0', true );

	$kaitex_version = wp_get_theme( get_template() );
	wp_enqueue_style( 'pxl-caseicon', get_template_directory_uri() . '/assets/css/caseicon.css', array(), $kaitex_version->get( 'Version' ) );
    wp_enqueue_style( 'pxl-grid', get_template_directory_uri() . '/assets/css/grid.css', array(), $kaitex_version->get( 'Version' ) );
	wp_enqueue_style( 'pxl-style', get_template_directory_uri() . '/assets/css/style.css', array(), $kaitex_version->get( 'Version' ) );
	wp_add_inline_style( 'pxl-style', kaitex_inline_styles() );
    wp_enqueue_style( 'pxl-base', get_template_directory_uri() . '/style.css', array(), $kaitex_version->get( 'Version' ) );
    wp_enqueue_style( 'pxl-google-fonts', kaitex_fonts_url(), array(), null );
	wp_enqueue_script( 'pxl-main', get_template_directory_uri() . '/assets/js/theme.js', array( 'jquery' ), $kaitex_version->get( 'Version' ), true );
    wp_enqueue_script( 'pxl-woocommerce', get_template_directory_uri() . '/woocommerce/woocommerce.js', array( 'jquery' ), $kaitex_version->get( 'Version' ), true );
    wp_localize_script( 'pxl-main', 'main_data', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
    do_action( 'kaitex_scripts');
}

/**
 * Enqueue Styles Scripts : Back-End
 */
add_action('admin_enqueue_scripts', 'kaitex_admin_style');
function kaitex_admin_style() {
    $theme = wp_get_theme( get_template() );
    wp_enqueue_style( 'kaitex-admin-style', get_template_directory_uri() . '/assets/css/admin.css', array(), $theme->get( 'Version' ) );
    wp_enqueue_style('bootstrap-icons', get_template_directory_uri() . '/assets/fonts/bootstrap-icons/css/bootstrap-icons.css');
    wp_enqueue_style('ionicons', get_template_directory_uri() . '/assets/fonts/ionicons/css/ionicons.css');
}

add_action( 'elementor/editor/before_enqueue_scripts', function() {
    wp_enqueue_style('admin-bootstrap-icons', get_template_directory_uri() . '/assets/fonts/bootstrap-icons/css/bootstrap-icons.css');
    wp_enqueue_style('admin-ionicons', get_template_directory_uri() . '/assets/fonts/ionicons/css/ionicons.css');
    wp_enqueue_style( 'kaitex-admin-style', get_template_directory_uri() . '/assets/css/admin.css');
} );

/* Favicon */
add_action('wp_head', 'kaitex_site_favicon');
function kaitex_site_favicon(){
    $favicon = kaitex()->get_theme_opt( 'favicon' );
    if(!empty($favicon['url']))
        echo '<link rel="icon" type="image/png" href="'.esc_url($favicon['url']).'"/>';
}

/**
 * Add a pingback url auto-discovery header for singularly identifiable articles.
 */
add_action( 'wp_head', 'kaitex_pingback_header' );
function kaitex_pingback_header() {
    if ( is_singular() && pings_open() )
    {
        echo '<link rel="pingback" href="', esc_url( get_bloginfo( 'pingback_url' ) ), '">';
    }
}

add_action( 'elementor/preview/enqueue_styles', 'kaitex_add_editor_preview_style' );
function kaitex_add_editor_preview_style() {
    wp_add_inline_style( 'editor-preview', kaitex_editor_preview_inline_styles() );
}
function kaitex_editor_preview_inline_styles(){
    $theme_colors = kaitex_configs('theme_colors');
    ob_start();
        echo '.elementor-edit-area-active{';
            foreach ($theme_colors as $color => $value) {
                printf('--%1$s-color: %2$s;', str_replace('#', '',$color),  $value['value']);
            }
        echo '}';
    return ob_get_clean();
}

add_action( 'pxl_anchor_target', 'kaitex_hook_anchor_templates_hidden_panel');
function kaitex_hook_anchor_templates_hidden_panel(){

    $hidden_templates = kaitex_get_templates_slug('hidden-panel');
    if(empty($hidden_templates)) return;

    foreach ($hidden_templates as $slug => $values){
        $args = [
            'slug' => $slug,
            'post_id' => $values['post_id'],
            'position' => !empty($values['position']) ? $values['position'] : 'custom-pos'
        ];
        if( did_action('pxl_anchor_target_hidden_panel_'.$values['post_id']) <= 0){
            //can be assign from here: do_action( 'pxl_anchor_target_hidden_panel_'.$slug);
            do_action( 'pxl_anchor_target_hidden_panel_'.$values['post_id'], $args );
        }
    }
}

function kaitex_hook_anchor_hidden_panel($args){
    ?>
    <div class="pxl-hidden-template pxl-hidden-template-<?php echo esc_attr($args['post_id'])?> pos-<?php echo esc_attr($args['position']) ?>">
        <div class="pxl-hidden-template-wrap">
            <div class="pxl-panel-header">
                <div class="panel-header-inner">
                    <span class="pxl-close pxl-close-drop" title="<?php echo esc_attr__( 'Close', 'kaitex' ) ?>"></span>
                </div>
            </div>
            <div class="pxl-panel-content" data-lenis-prevent>
               <?php echo Elementor\Plugin::$instance->frontend->get_builder_content_for_display( (int)$args['post_id']); ?>
            </div>
        </div>
    </div>
    <div class="pxl-overlay-drop"></div>
    <?php
}

/* Elementor Popup */
add_action( 'pxl_anchor_target', 'kaitex_hook_anchor_templates_popup');
function kaitex_hook_anchor_templates_popup(){

    $popup_templates = kaitex_get_templates_slug('popup');
    if(empty($popup_templates)) return;

    foreach ($popup_templates as $slug => $values){
        $args = [
            'slug' => $slug,
            'post_id' => $values['post_id']
        ];
        if( did_action('pxl_anchor_target_popup_'.$values['post_id']) <= 0){
            do_action( 'pxl_anchor_target_popup_'.$values['post_id'], $args );
        }
    }
}
if(!function_exists('kaitex_hook_anchor_popup')){
    function kaitex_hook_anchor_popup($args){ ?>
        <div id="pxl-popup-elementor" class="pxl-popup-elementor-wrap">
            <div class="pxl-item--overlay pxl-cursor--cta">
                <div class="pxl-item--flip pxl-item--flip1"></div>
                <div class="pxl-item--flip pxl-item--flip2"></div>
                <div class="pxl-item--flip pxl-item--flip3"></div>
                <div class="pxl-item--flip pxl-item--flip4"></div>
                <div class="pxl-item--flip pxl-item--flip5"></div>
            </div>
            <div class="pxl-item--close pxl-close pxl-cursor--cta"></div>
            <div class="pxl-item--conent">
                <div class="pxl-conent-elementor">
                    <?php echo Elementor\Plugin::$instance->frontend->get_builder_content_for_display( (int)$args['post_id']); ?>
                </div>
            </div>
        </div>
    <?php }
}

/* Page Popup */
add_action( 'pxl_anchor_target', 'kaitex_hook_anchor_templates_page_popup');
function kaitex_hook_anchor_templates_page_popup(){

    $page_templates = kaitex_get_templates_slug('page');
    if(empty($page_templates)) return;

    foreach ($page_templates as $slug => $values){
        $args = [
            'slug' => $slug,
            'post_id' => $values['post_id']
        ];
        if( did_action('pxl_anchor_target_page_popup_'.$values['post_id']) <= 0){
            do_action( 'pxl_anchor_target_page_popup_'.$values['post_id'], $args );
        }
    }
}
if(!function_exists('kaitex_hook_anchor_page_popup')){
    function kaitex_hook_anchor_page_popup($args){ ?>
        <div class="pxl-page-popup pxl-page-popup-template-<?php echo esc_attr($args['post_id'])?>">
            <div class="pxl-popup--close"><i class="pxl-icon-close"></i></div>
            <div class="pxl-popup--conent">
                <div class="pxl-conent-elementor">
                    <?php
                        $content_page = \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( (int)$args['post_id'] );
                        pxl_print_html($content_page);
                    ?>
                </div>
            </div>
        </div>
    <?php }
}

/* Search Popup */
if(!function_exists('kaitex_hook_anchor_search')){
    function kaitex_hook_anchor_search(){ ?>
        <div id="pxl-search-popup">
            <div class="pxl-item--overlay"></div>
            <div class="pxl-item--conent">
                <div class="pxl-item--close pxl-close"></div>
                <form role="search" method="get" action="<?php echo esc_url(home_url( '/' )); ?>">
                    <input type="text" required placeholder="<?php esc_attr_e('Type Your Search Words...', 'kaitex'); ?>" name="s" class="search-field" />
                    <button type="submit" class="search-submit rm-style-default"><i class="caseicon-search"></i></button>
                    <div class="pxl--search-divider"></div>
                </form>
            </div>
        </div>
    <?php }
}
/* Cart Sidebar */
if(!function_exists('kaitex_hook_anchor_cart')){
    function kaitex_hook_anchor_cart(){ ?>
        <div class="pxl-overlay-drop"></div>
        <div class="pxl-hidden-template pxl-side-cart pos-right">
            <div class="pxl-hidden-template-wrap">
                <div class="pxl-panel-header">
                    <div class="panel-header-inner">
                        <span class="pxl-title h3"><?php echo esc_html__( 'Cart', 'kaitex' ) ?><span class="widget_cart_counter">(<?php echo sprintf (_n( '%d item', '%d items', WC()->cart->cart_contents_count, 'kaitex' ), WC()->cart->cart_contents_count ); ?>)</span></span>
                        <span class="pxl-close pxl-close-drop" title="<?php echo esc_attr__( 'Close', 'kaitex' ) ?>"></span>
                    </div>
                </div>
                <div class="pxl-panel-content widget_shopping_cart" data-lenis-prevent>
                    <div class="widget_shopping_cart_content">
                        <?php woocommerce_mini_cart(); ?>
                    </div>
                </div>
            </div>
        </div>
    <?php }
}

/**
 * Custom Post Field
 */
// Post format "Video"
function add_video_url_meta_box() {
    add_meta_box(
        'video-url-box',
        'Video Details',
        'display_video_url_meta_box',
        'post',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_video_url_meta_box');

function display_video_url_meta_box($post) {
    $video_url = get_post_meta($post->ID, 'video_url', true);
    $video_thumbnail = get_post_meta($post->ID, 'video_thumbnail', true);
    ?>
    <div class="custom-meta-box">
        <label for="video_url">Video URL:</label>
        <input type="text" id="video_url" name="video_url" value="<?php echo esc_attr($video_url); ?>" style="width: 100%;" />
    </div>
    <div class="custom-meta-box">
        <label for="video_thumbnail">Video Thumbnail:</label>
        <input type="text" id="video_thumbnail" name="video_thumbnail" value="<?php echo esc_attr($video_thumbnail); ?>" style="width: 100%;" />
        <button id="upload_video_thumbnail" class="button" style="margin: 10px 0;">Upload Image</button>
    </div>
    <div class="video-thumbnail-preview">
        <?php if (!empty($video_thumbnail)) : ?>
            <img src="<?php echo esc_url($video_thumbnail); ?>" alt="Video Thumbnail" style="max-width: 300px; height: auto;" />
        <?php endif; ?>
    </div>
    <script>
        jQuery(document).ready(function($) {
            $('#upload_video_thumbnail').click(function(e) {
                e.preventDefault();
                var image = wp.media({
                    title: 'Select Video Thumbnail',
                    multiple: false
                }).open().on('select', function(e) {
                    var uploadedImage = image.state().get('selection').first().toJSON();
                    $('#video_thumbnail').val(uploadedImage.url);
                    $('.video-thumbnail-preview img').attr('src', uploadedImage.url);
                });
            });
        });
    </script>
    <?php if (class_exists('Classic_Editor')) { ?>
        <script>
            jQuery(document).ready(function($) {
                var formatElements = {
                    '0': '#postimagediv',
                    'gallery': '#gallery-image-box',
                    'link': '#link-url-box',
                    'quote': '#quote-box',
                    'audio': '#audio-url-box',
                    'video': '#video-url-box'
                };

                function toggleFormatElements(selectedFormat) {
                    for (var format in formatElements) {
                        $(formatElements[format]).hide();
                    }
                    $(formatElements[selectedFormat]).show();
                }

                $('input[name="post_format"]').change(function() {
                    var selectedFormat = $(this).val();
                    toggleFormatElements(selectedFormat);
                });

                var initialFormat = $('input[name="post_format"]:checked').val();
                toggleFormatElements(initialFormat);
            });
        </script>
    <?php } ?>

    <?php
}

function save_video_url_meta_box($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['video_url'])) {
        $video_url = esc_url($_POST['video_url']);
        update_post_meta($post_id, 'video_url', $video_url);
    }

    if (isset($_POST['video_thumbnail'])) {
        $video_thumbnail = esc_url($_POST['video_thumbnail']);
        update_post_meta($post_id, 'video_thumbnail', $video_thumbnail);
    }
}
add_action('save_post', 'save_video_url_meta_box');

function pxl_upload_external_image($image_url) {
    $upload_dir = wp_upload_dir();
    $image_data = file_get_contents($image_url);
    $filename   = basename($image_url);

    if (wp_mkdir_p($upload_dir['path'])) {
        $file = $upload_dir['path'] . '/' . $filename;
    } else {
        $file = $upload_dir['basedir'] . '/' . $filename;
    }

    file_put_contents($file, $image_data);

    $wp_filetype = wp_check_filetype($filename, null);
    $attachment  = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit',
    );

    $attach_id = wp_insert_attachment($attachment, $file);
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata($attach_id, $file);
    wp_update_attachment_metadata($attach_id, $attach_data);

    return $attach_id;
}
