<?php
/**
 * Theme functions
 *
 * @package xts
 */

use Elementor\Controls_Manager;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Direct access not allowed.
}

if ( ! function_exists( 'xts_antares_hooks' ) ) {
	/**
	 * Hooks.
	 *
	 * @since 1.0.0
	 */
	function xts_antares_hooks() {
		remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );
		remove_action( 'xts_shop_tools_left_area', 'xts_current_shop_breadcrumbs' );
	}

	add_action( 'wp', 'xts_antares_hooks', 500 );
}

if ( ! function_exists( 'xts_shop_tools_widgets' ) ) {
	/**
	 * Shop tools widgets area.
	 *
	 * @since 1.0.0
	 */
	function xts_shop_tools_widgets() {
		xts_enqueue_js_script( 'shop-tools-filters' );
		?>
		<div class="xts-shop-tools-widgetarea">
			<?php dynamic_sidebar( 'shop-tools-widget-sidebar' ); ?>
		</div>
		<?php
	}

	add_action( 'xts_shop_tools_left_area', 'xts_shop_tools_widgets', 10 );
}

if ( ! function_exists( 'xts_custom_content_after_page_title' ) ) {
	/**
	 * Add content after page title.
	 *
	 * @since 1.0.0
	 */
	function xts_custom_content_after_page_title() {
		if ( ! xts_is_shop_archive() ) {
			return;
		}

		?>
		<div class="container">
			<div class="xts-shop-head-nav row row-spacing-0">
				<div class="col xts-shop-tools">
					<?php xts_current_shop_breadcrumbs(); ?>
				</div>

				<div class="col-auto xts-shop-tools">
					<?php woocommerce_result_count(); ?>
				</div>
			</div>
		</div>
		<?php
	}

	add_action( 'xts_before_site_content_container', 'xts_custom_content_after_page_title', 20 );
}

if ( ! function_exists( 'xts_antares_register_sidebars' ) ) {
	/**
	 * Register widget area.
	 *
	 * @since 1.0.0
	 */
	function xts_antares_register_sidebars() {
		$title_tag = apply_filters( 'xts_widgets_title_tag', 'span' );

		register_sidebar(
			array(
				'name'          => esc_html__( 'Shop tools widget area', 'xts-theme' ),
				'id'            => 'shop-tools-widget-sidebar',
				'description'   => esc_html__( 'Add widgets here to appear in your shop tools widget area.', 'xts-theme' ),
				'before_widget' => '<div id="%1$s" class="widget xts-shop-tools-widget %2$s">',
				'after_widget'  => '</div>',
				'before_title'  => '<' . $title_tag . ' class="xts-tools-widget-title"><span>',
				'after_title'   => '</span></' . $title_tag . '>',
			)
		);
	}

	add_action( 'widgets_init', 'xts_antares_register_sidebars' );
}

if ( ! function_exists( 'xts_add_mega_menu_element_submenu_indicator_control' ) ) {
	/**
	 * Add submenu indicator control to mega menu element element.
	 *
	 * @since 1.0.0
	 *
	 * @param object $element Element object.
	 */
	function xts_add_mega_menu_element_submenu_indicator_control( $element ) {
		$element->add_control(
			'submenu_indicator_style',
			[
				'label'   => esc_html__( 'Submenu indicator', 'xts-theme' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [
					'chevron' => esc_html__( 'Chevron icon', 'xts-theme' ),
					'plus'    => esc_html__( 'Plus icon', 'xts-theme' ),
				],
				'default' => 'chevron',
			]
		);
	}

	add_action( 'xts_mega_menu_general_style_after_menu_style', 'xts_add_mega_menu_element_submenu_indicator_control' );
}

if ( ! function_exists( 'xts_remove_play_button_border_controls' ) ) {
	/**
	 * Remove border controls.
	 *
	 * @since 1.0.0
	 */
	function xts_remove_play_button_border_controls() {
		remove_action( 'elementor/element/xts_video/style_play_button_section/before_section_end', 'xts_add_video_play_button_border_controls', 10 ); // Does not remove core filters.
	}

	add_action( 'init', 'xts_remove_play_button_border_controls', 50 );
}



function video_popup_wrrapper() {
    ?>

    <div class="video_popup_wrrapper">
		<div class="video_popup_overlay"></div>
		<div class="video_popup_inner"></div>
	</div>

    <?php
}
add_action( 'wp_head', 'video_popup_wrrapper', 400 );






 /**
 * Adds WooCommerce profile picture functionality to the My Account page
 */
function gl_woocommerce_profile_picture_functionality() {
    // Add enctype attribute to account form
    add_action('woocommerce_edit_account_form_tag', function() {
        echo 'enctype="multipart/form-data"';
    });

    // Add profile picture upload field
    add_action('woocommerce_edit_account_form_start', function() {
        ?>
        <fieldset>
            <legend>تصویر پروفایل</legend>

            <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
                <label><?php _e('تصویر پروفایل', 'woocommerce'); ?></label>
                <?php echo get_avatar(get_current_user_id()); ?>
            </p>

            <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
                <label for="profile_picture"><?php _e('تصویر پروفایل خود را آپلود کنید.', 'woocommerce'); ?></label>
                <input type="file" name="profile_picture" id="profile_picture" accept=".jpg, .jpeg, .png">
            </p>
        </fieldset>
        <?php
    });

    // Handle profile picture upload
    add_action('woocommerce_save_account_details', function($user_id) {
        if (isset($_FILES['profile_picture']) && !empty($_FILES['profile_picture']['name'])) {
            $file = $_FILES['profile_picture'];
            
            $file_type = wp_check_filetype($file['name']);
            if (isset($file_type['type']) && str_contains($file_type['type'], 'image')) {
                $file_path = $file['tmp_name'];
                $new_width = 150;
                $new_height = 150;
                
                $unique_filename = md5($user_id);
                $wp_upload = wp_upload_dir();
                $upload_dir = $wp_upload['basedir'] . '/wc-profile-picture/';
                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir);
                }
                $image_path = $upload_dir . $unique_filename . '.jpg';
                $image_url = $wp_upload['baseurl'] . '/wc-profile-picture/' . $unique_filename . '.jpg';
                
                list($width, $height) = wp_getimagesize($file_path);
                if ($width > $new_width || $height > $new_height) {
                    $size = getimagesize($file_path);
                    $ratio = $size[0] / $size[1]; // width/height
                    
                    if ($ratio > 1) {
                        $width = $new_width;
                        $height = $new_height / $ratio;
                    } else {
                        $width = $new_width * $ratio;
                        $height = $new_height;
                    }
                    
                    $image_src = imagecreatefromstring(file_get_contents($file_path));
                    $new_image = imagecreatetruecolor($width, $height);
                    imagecopyresampled($new_image, $image_src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
                    imagejpeg($new_image, $image_path);
                } else {
                    $uploaded_file = move_uploaded_file($file_path, $image_path);
                    if (empty($uploaded_file)) {
                        wc_add_notice(__('خطا در آپلود تصویر. لطفا مجدد تلاش کنید!', 'woocommerce'), 'error');
                    }
                }
                
                update_user_meta($user_id, 'profile_picture', $image_url);
            } else {
                wc_add_notice(__('نوع فایل غیرمجاز. لطفا مجدد تلاش کنید.', 'woocommerce'), 'error');
            }
        }
    });

    // Override default avatar with custom profile picture
    add_filter('pre_get_avatar', function($avatar, $id_or_email, $args) {
        $user_id = null;
        if (is_object($id_or_email)) {
            if (!empty($id_or_email->comment_author_email)) {
                $user_id = $id_or_email->user_id;
            }
        } else {
            if (is_email($id_or_email)) {
                $user = get_user_by('email', $id_or_email);
                if ($user) {
                    $user_id = $user->ID;
                }
            } else {
                $user_id = $id_or_email;
            }
        }
        
        $avatar_url = get_user_meta($user_id, 'profile_picture', true);
        
        if (!empty($avatar_url)) {
            return '<img class="woo-profile-picture size-' . $args['size'] . '" src="' . $avatar_url . '" alt="تصویر پروفایل" style="object-fit: cover;width:' . $args['size'] . 'px; height:' . $args['size'] . 'px; border-radius: 108px;">';
        }
        
        return $avatar;
    }, 10, 3);
}

// Initialize the functionality
add_action('init', 'gl_woocommerce_profile_picture_functionality');



