<?php
namespace Prk\Admin;


use Prk\traits\Singleton;
use Prk\mw_tools;

class Studio_Importer extends Studio_Demo {
    private $result;
    private $processed_terms = [];
    private $processed_posts = [];

    use Singleton;

    public function __construct(){
        add_action('ahura_after_import_demo', [$this, 'handle_after_import_demo'], 10, 2);
    }

    /**
     *
     * Get home page names
     *
     * @return array|object
     */
    public function get_home_names($hash = false){
        $names = [
            'Home',
            'home',
            'خانه',
            'خانه اصلی',
            'صفحه اصلی',
            'صفحه خانه',
            'صفحه نخست'
        ];
        $names = apply_filters('ahura_get_home_names', $names);
        if($hash === true){
            $names = mw_tools::array_hash_values($names);
        }
        return $names;
    }

    /**
     *
     * Get header page names
     *
     * @return array|object
     */
    public function get_header_names($hash = false){
        $names = [
            'Header',
            'header',
            'هدر',
            'سربرگ',
            'هدر اصلی',
            'سربرگ اصلی'
        ];
        $names = apply_filters('ahura_get_header_names', $names);
        if($hash === true){
            $names = mw_tools::array_hash_values($names);
        }
        return $names;
    }

    /**
     *
     * Get footer page names
     *
     * @return array|object
     */
    public function get_footer_names($hash = false){
        $names = [
            'Footer',
            'footer',
            'فوتر',
            'پاورقی',
            'فوتر اصلی',
            'پاورقی اصلی'
        ];
        $names = apply_filters('ahura_get_footer_names', $names);
        if($hash === true){
            $names = mw_tools::array_hash_values($names);
        }
        return $names;
    }

    private function set_result($key, $value){
        if(is_array($key) && count($key) == 2){
            $this->result[$key[0]][$key[1]] = $value;
        } else {
            $this->result[$key] = $value;
        }
    }

    private function get_result(){
        return $this->result;
    }

    /**
     *
     * Import demo content
     *
     * @return false|void
     */
    public function import_demo($params = null) {
        @ini_set('memory_limit', '256M');
    
        if (!isset($params['demo']) || $params['demo'] < 0) {
            return ['complete' => true]; // همیشه آرایه بده، نه false
        }
    
        $step = $params['step'];
        $selected_items = isset($_POST['selected_items']) ? $_POST['selected_items'] : [];
        $is_first = $params['is_first'] == 'true';
        $is_last = $params['is_last'] == 'true';
    
        if ($is_first) {
            $this->set_demo_id($params['demo']);
            $this->set_result('start', true);
        }
    
        $demo_content = $this->get_demo_content();
        if (!$demo_content) {
            $this->set_result('empty', true);
        } else {
            $attachments = isset($demo_content['posts']['attachment']) ? $demo_content['posts']['attachment'] : false;
            if ($attachments) {
                unset($demo_content['posts']['attachment']);
            }
    
            do_action('ahura_before_import_demo', $demo_content);
    
            wp_suspend_cache_invalidation(true);
    
            if ($step === 'reset' && in_array('reset', $selected_items)) {
                $this->clear_site_content();
            } elseif (in_array($step, ['customizer', 'options']) && in_array('options', $selected_items)) {
                $this->import_customizer($demo_content);
            } elseif ($step === 'terms') {
                $this->import_product_categories($demo_content); // دسته‌بندی‌ها و برندها
                $this->import_terms($demo_content); // دسته‌بندی‌ها و برندها
                $this->import_brands($demo_content); // دسته‌بندی‌ها و برندها
            } elseif ($step === 'menus') {
            
              
            } elseif (in_array($step, ['posts', 'content']) && in_array('content', $selected_items)) {

            $this->import_posts($demo_content); // محصولات و برگه‌ها
            $this->import_comments($demo_content); // نظرات و ریویوها
            $this->import_menus($demo_content); // منوها
            flush_rewrite_rules(); // فقط یکبار در پایان

            } elseif ($step === 'media' && in_array('media', $selected_items)) {
                if (isset($attachments[$params['start_media']])) {
                    $this->import_media($attachments[$params['start_media']], $attachments);
                    $this->set_result('continue', true); // اگه فایل هنوز وجود داشت بگو ادامه داره
                } else {
                    $this->set_result('complete', true); // اگه دیگه فایلی نبود بگو کامل شد
                }
            } elseif ($step === 'widgets' && in_array('widgets', $selected_items)) {
                $this->import_widgets($demo_content);
            }
    
            wp_suspend_cache_invalidation(false);
    
            if ($is_last) {
                
                do_action('ahura_after_import_demo', $this->get_result(), $demo_content);
                $this->remove_demo_file();
                $this->set_result('complete', true);
            }
        }
    
        // ✨ حالا برگشت نتیجه
        $result = $this->get_result();
        if (empty($result)) {
            $result = ['complete' => true];
        }
    
        return $result;
    }
    


    /**
     *
     * Import demo media
     *
     * @param $attachment
     * @return false|int
     */
    public function import_media($attachment, $attachments = []){
        if (!is_array($attachment) || empty($attachment))
            return false;

        $import_count = 0;
        $attachment = (array) $attachment;
        $attachment_url = isset($attachment['guid']) && !empty($attachment['guid']) ? $attachment['guid'] : false;
        if($attachment_url){
            $sideload = @self::sideload_attachment($attachment_url, $attachment);
            if(is_object($sideload) && isset($sideload->url)){
                $this->set_result(['imported', 'url'], $sideload->url);
                $import_count++;
            }
        }

        $this->set_result(['imported', 'success'], $import_count);
        $this->set_result(['imported', 'all'], count($attachments));
        $this->set_result(['imported', 'attachment'], $attachment);
        return $import_count;
    }

    public static function sideload_attachment($file, $params = []){
        $data = new \stdClass();

        if ( ! function_exists( 'media_handle_sideload' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/media.php' );
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
        }

        if ( ! empty( $file ) ) {
            // Set variables for storage, fix file filename for query strings.
            preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png|svg|mp3|mp4|webm|webp)\b/i', $file, $matches );
            $file_array = array();
            $file_array['name'] = basename( $matches[0] );

            // Download file to temp location.
            $file_array['tmp_name'] = download_url( $file );

            // If error storing temporarily, return the error.
            if ( is_wp_error( $file_array['tmp_name'] ) ) {
                return $file_array['tmp_name'];
            }
            $params['import_id'] = $params['ID'];
            // Do the validation and storage stuff.
            $id = media_handle_sideload($file_array, $params['ID'], null, $params);

            // If error storing permanently, unlink.
            if ( is_wp_error( $id ) ) {
                unlink( $file_array['tmp_name'] );
                return $id;
            }

            // Build the object to return.
            $meta                = wp_get_attachment_metadata( $id );
            $data->attachment_id = $id;
            $data->url           = wp_get_attachment_url( $id );
            $data->thumbnail_url = wp_get_attachment_thumb_url( $id );
            $data->height        = $meta['height'];
            $data->width         = $meta['width'];
        }

        return $data;
    }

    /**
     *
     * Import demo posts
     *
     * @param $demo_content
     * @return void
     */
    private function import_posts($demo_content){
        $i = 0;
        $this->set_result(['imported', 'content'], $i);

        if(isset($demo_content['posts'])){
            $posts = $demo_content['posts'];
            if(is_array($posts) && count($posts) > 0){
                foreach ($posts as $post_type => $post_type_posts) {
                    foreach ($post_type_posts as $post) {
                        if(!$post) continue;
                        
                        $post_id = wp_insert_post(array(
                            'import_id ' => $post['ID'],
                            'post_type' => $post_type,
                            'post_title' => $post['post_title'],
                            'post_name'    => isset($post['post_name']) ? sanitize_title($post['post_name']) : '', // این خط اضافه شد
                            'post_content' => is_array($post['post_content']) ? json_encode($post['post_content']) : $post['post_content'],
                            'post_date' => $post['post_date'],
                            'post_date_gmt' => $post['post_date_gmt'],
                            'post_status' => 'publish', // ✨ این خط جدید اضافه شده
                        ));

                        if (isset($post['ID'])) {
                            $this->processed_posts[(int)$post['ID']] = (int)$post_id;
                        }
                        
                        if(!$post_id) continue;



                        $categories = [];
                        $taxonomy = '';
                    
                        if (isset($post['categories']) && !empty($post['categories'])) {
                            foreach ($post['categories'] as $category) {
                                if (isset($category['slug']) && isset($category['taxonomy'])) {
                                    $real_slug = urldecode($category['slug']);
                                    $term = get_term_by('slug', $real_slug, $category['taxonomy']);
                                    if ($term && !is_wp_error($term)) {
                                        $categories[] = (int) $term->term_id;
                                        $taxonomy = $category['taxonomy'];
                                    }
                                }
                            }
                        }
                        
                        if (!empty($categories) && $taxonomy) {
                            wp_set_object_terms($post_id, $categories, $taxonomy, false);
                        
                            foreach ($categories as $cat_id) {
                                wp_update_term_count_now([$cat_id], $taxonomy);
                            }
                        }

                        self::set_cache_option($post['ID'], 'before_id', $post_id);

               
                        if (in_array(md5($post['post_title']), self::get_home_names(true))){
                            update_option('ahura_demo_home_id', $post_id);
                        }
                   
                        if (isset($post['meta'])) {
                            foreach ($post['meta'] as $meta_key => $meta_value) {
                                if (is_string($meta_key)) {
                                    $value = maybe_unserialize($meta_value[0]);
                                    add_post_meta($post_id, wp_unslash($meta_key), $value);
                                }
                            }
                        }

                        $i++;
                    }
                }
                $this->set_result(['imported', 'content'], $i);
            }
        }
    }
    

    /**
     *
     * Import demo brands
     *
     * @param $attachment
     * @return false|int
     */
    public function import_brands($demo_content) {
        if (!isset($demo_content['brands']) || !is_array($demo_content['brands'])) return;

        foreach ($demo_content['brands'] as $term) {
            if (empty($term['slug']) || empty($term['taxonomy'])) continue;

            $slug = urldecode($term['slug']);
            $taxonomy = $term['taxonomy'];

            $term_exists = term_exists($slug, $taxonomy);

            if ($term_exists) {
                $term_id = is_array($term_exists) ? $term_exists['term_id'] : $term_exists;
            } else {
                $new_term = wp_insert_term(
                    $term['name'],
                    $taxonomy,
                    [
                        'slug' => $slug,
                        'description' => $term['description'] ?? '',
                    ]
                );

                $term_id = is_wp_error($new_term) ? 0 : $new_term['term_id'];
            }

            if ($term_id && isset($term['term_id'])) {
                $this->processed_terms[(int)$term['term_id']] = (int)$term_id;
            }

            if (!empty($term['meta'])) {
                foreach ($term['meta'] as $meta_key => $meta_value) {
                    update_term_meta($term_id, $meta_key, maybe_unserialize($meta_value));
                }
            }
        }
    }

    /**
     *
     * Import demo terms
     *
     * @param $attachment
     * @return false|int
     */
    public function import_terms($demo_content) {
        if (!isset($demo_content['terms']) || !is_array($demo_content['terms'])) return;
    
        foreach ($demo_content['terms'] as $term) {
            if (empty($term['slug']) || empty($term['taxonomy'])) continue;
    
            // 🚫 اگر taxonomy مربوط به دسته‌بندی محصولات بود، بیخیالش شو
            if ($term['taxonomy'] === 'product_cat' || $term['taxonomy'] === 'brands' ) continue;
    
            $slug = urldecode($term['slug']);
            $taxonomy = $term['taxonomy'];
    
            $term_exists = term_exists($slug, $taxonomy);
    
            if ($term_exists) {
                $term_id = is_array($term_exists) ? $term_exists['term_id'] : $term_exists;
            } else {
                $new_term = wp_insert_term(
                    $term['name'],
                    $taxonomy,
                    [
                        'slug' => $slug,
                        'description' => $term['description'] ?? '',
                        'parent' => isset($term['parent']) ? (int)$term['parent'] : 0,
                    ]
                );
    
                $term_id = is_wp_error($new_term) ? 0 : $new_term['term_id'];
            }
    
            // مپ کردن term_id قدیمی به جدید
            if ($term_id && isset($term['term_id'])) {
                $this->processed_terms[(int)$term['term_id']] = (int)$term_id;
            }
    
            // متاهای ترم رو ذخیره کن
            if (!empty($term['meta'])) {
                foreach ($term['meta'] as $meta_key => $meta_value) {
                    update_term_meta($term_id, $meta_key, maybe_unserialize($meta_value));
                }
            }
        }
    }

    
    /**
     *
     * Import demo product categories
     *
     * @param $attachment
     * @return false|int
     */
    private function import_product_categories($demo_content)
    {
        global $wpdb;
    
        $this->category_mapping = []; // خالی کردن مپینگ قبل شروع
    
        if (!isset($demo_content['product_categories']) || !is_array($demo_content['product_categories'])) {
            return;
        }
    
        foreach ($demo_content['product_categories'] as $category) {
            if (!$category || !isset($category['name']) || !isset($category['slug']) || !isset($category['taxonomy'])) {
                continue;
            }
    
            $real_slug = urldecode($category['slug']);
    
            // آیا این دسته قبلاً وجود داره؟
            $existing_term = get_term_by('slug', $real_slug, $category['taxonomy']);
            if ($existing_term && !is_wp_error($existing_term)) {
                $new_term_id = $existing_term->term_id;
            } else {
                // ✨ قبل از اضافه کردن، parent رو چک کنیم
                $parent = 0;
                if (!empty($category['parent'])) {
                    $parent_term = $wpdb->get_var(
                        $wpdb->prepare(
                            "SELECT term_id FROM {$wpdb->terms} WHERE term_id = %d",
                            (int)$category['parent']
                        )
                    );
    
                    if ($parent_term) {
                        $parent = (int)$category['parent'];
                    }
                }
    
                // اضافه کردن مستقیم به wp_terms
                $wpdb->insert(
                    $wpdb->terms,
                    [
                        'term_id' => (int)$category['term_id'],
                        'name' => $category['name'],
                        'slug' => $real_slug,
                        'term_group' => (int)$category['term_group'],
                    ]
                );
    
                // اضافه کردن مستقیم به wp_term_taxonomy
                $wpdb->insert(
                    $wpdb->term_taxonomy,
                    [
                        'term_id' => (int)$category['term_id'],
                        'taxonomy' => $category['taxonomy'],
                        'description' => $category['description'],
                        'parent' => $parent, // ✨ اینجا parent درست ست شد
                        'count' => 0, // حتماً صفر تا بعداً شمارش بشه
                    ]
                );
    
                $new_term_id = $category['term_id'];
            }
    
            // مپینگ term_id قدیمی به جدید
            $this->category_mapping[(int)$category['term_id']] = (int)$new_term_id;
    
            // متا دیتاها
            if (isset($category['meta']) && is_array($category['meta'])) {
                foreach ($category['meta'] as $meta_key => $meta_value) {
                    update_term_meta($new_term_id, $meta_key, maybe_unserialize($meta_value));
                }
            }
        }
    
        // پاکسازی کش ترم‌ها
        delete_option('category_children');
        wp_cache_flush();
    }


    
    /**
     *
     * Import demo product tcomments
     *
     * @param $attachment
     * @return false|int
     */
    public function import_comments($demo_content) {
        if (!isset($demo_content['comments'])) return;

        foreach ($demo_content['comments'] as $comment) {
            if (!isset($comment['comment_post_ID'])) continue;

            $old_post_id = (int)$comment['comment_post_ID'];

            if (!isset($this->processed_posts[$old_post_id])) continue;

            $new_post_id = $this->processed_posts[$old_post_id];

            $comment_data = [
                'comment_post_ID' => $new_post_id,
                'comment_author' => $comment['comment_author'],
                'comment_author_email' => $comment['comment_author_email'],
                'comment_author_url' => $comment['comment_author_url'],
                'comment_author_IP' => $comment['comment_author_IP'],
                'comment_date' => $comment['comment_date'],
                'comment_date_gmt' => $comment['comment_date_gmt'],
                'comment_content' => $comment['comment_content'],
                'comment_karma' => $comment['comment_karma'],
                'comment_approved' => $comment['comment_approved'],
                'comment_agent' => $comment['comment_agent'],
                'comment_type' => $comment['comment_type'],
                'comment_parent' => $comment['comment_parent'],
                'user_id' => $comment['user_id'],
            ];

            $comment_id = wp_insert_comment(wp_slash($comment_data));

            if (!is_wp_error($comment_id) && !empty($comment['meta'])) {
                foreach ($comment['meta'] as $meta) {
                    if (isset($meta['meta_key']) && isset($meta['meta_value'])) {
                        add_comment_meta($comment_id, $meta['meta_key'], maybe_unserialize($meta['meta_value']));
                    }
                }
            }
        }
    }

    
    /**
     *
     * Import demo customizer settings
     *
     * @param $demo_content
     * @return void
     */
    private function import_customizer($demo_content){

        update_option( 'prk_option', $demo_content['theme_options'] );
        
        global $wp_customize;
        $i = 0;
        if(isset($demo_content['customizer']) && !empty($demo_content['customizer'])){
            $mods = get_theme_mods();
            if($mods){
                $save_mods = update_option('ahura_before_theme_mods', json_encode($mods));
                set_theme_mod('theme_dark', false);
            }

            $customizer_settings = $demo_content['customizer'];
            do_action('customize_save', $wp_customize);

            foreach ( $customizer_settings as $key => $val ) {
                do_action('customize_save_' . $key, $wp_customize);

                set_theme_mod( $key, $val );
                $i++;
            }
        }
        $this->set_result(['imported', 'customizer'], $i);
    }

    /**
     *
     * Import demo menu items
     *
     * @param $demo_content
     * @return void
     */
    private function import_menus($demo_content)
    {
        self::session_start();
    
        $i = 0;
        $this->set_result(['imported', 'menus'], $i);
    
        if (isset($demo_content['menus'])) {
            $menus = $demo_content['menus'];
            if (!empty($menus)) {
                $locations = get_nav_menu_locations();
    
                foreach ($menus as $location => $menu_data) {
    
                    $menu = $menu_data['menu'];
                    $menu['menu-name'] = $menu['name'];
                    $menu_id = wp_update_nav_menu_object($menu['term_id'], $menu);
    
                    if (is_wp_error($menu_id)) {
                        $nav = wp_get_nav_menu_object($menu['name']);
                        if (!is_wp_error($nav)) {
                            if (is_object($nav) && isset($nav->term_id)) {
                                $menu_id = $nav->term_id;
                            }
                        }
                    }
    
                    if ($menu_id && isset($menu_data['menu_items'])) {
                        $menu_items = $menu_data['menu_items'];
    
                        foreach ($menu_items as $menu_item) {
                            if (isset($menu_item['object_id'])) {
    
                                $object_id = 0;
                                $menu_item_object = '';
    
                                if ($menu_item['type'] == 'taxonomy' && isset($menu_item['object_data']['taxonomy'])) {
                                    $taxonomy = $menu_item['object_data']['taxonomy'];
    
                                    if (isset($menu_item['object_data']['slug']) && !empty($menu_item['object_data']['slug'])) {
                                        $found_term = get_term_by('slug', $menu_item['object_data']['slug'], $taxonomy);
                                        if ($found_term && !is_wp_error($found_term)) {
                                            $object_id = $found_term->term_id;
                                            $menu_item_object = $taxonomy;
                                        }
                                    }
                                }
    
                                // اگه object_id پیدا نکردیم (مثلا آیتم custom یا post_type بود)
                                if (!$object_id) {
                                    if ('taxonomy' == $menu_item['type'] && !empty(self::get_cache_option($menu_item['object_id'], 'before_id', 'meta'))) {
                                        $object_id = self::get_cache_option($menu_item['object_id'], 'before_id', 'meta');
                                    } elseif ('post_type' == $menu_item['type'] && !empty(self::get_cache_option($menu_item['object_id'], 'before_id'))) {
                                        $object_id = self::get_cache_option($menu_item['object_id'], 'before_id');
                                    } elseif ('custom' == $menu_item['type']) {
                                        $object_id = 0;
                                    } else {
                                        $object_id = $menu_item['object_id'];
                                    }
                                }
    
                                if (empty($object_id) || is_wp_error($object_id)) {
                                    $object_id = 0;
                                }
    
                                $menu_item_data = [
                                    'menu-item-object-id'   => $object_id,
                                    'menu-item-type'        => $menu_item['type'],
                                    'menu-item-status'      => $menu_item['post_status'],
                                    'menu-item-title'       => $menu_item['title'],
                                    'menu-item-description' => $menu_item['description'],
                                    'menu-item-url'         => $menu_item['url'],
                                ];
    
                                // اضافه کن object به منو آیتم
                                if (!empty($menu_item_object)) {
                                    $menu_item_data['menu-item-object'] = $menu_item_object;
                                } elseif (isset($menu_item['object']) && !empty($menu_item['object'])) {
                                    $menu_item_data['menu-item-object'] = $menu_item['object'];
                                }
    
                                // مدیریت منوی والد
                                if (isset($menu_item['menu_item_parent']) && !empty($menu_item['menu_item_parent']) && $menu_item['menu_item_parent'] != $menu_item['ID']) {
                                    $parent_id = self::get_cache_item($menu_item['menu_item_parent']);
                                    if ($parent_id !== $menu_item['ID']) {
                                        $menu_item_data['menu-item-parent-id'] = $parent_id;
                                    }
                                }
    
                                $menu_item_id = wp_update_nav_menu_item($menu_id, 0, $menu_item_data);
    
                                if (!is_object($menu_item_id) && !is_wp_error($menu_item_id)) {
                                    self::cache_item($menu_item['ID'], $menu_item_id);
    
                                    if (isset($menu_item['meta']) && !empty($menu_item['meta'])) {
                                        foreach ($menu_item['meta'] as $key1 => $meta_item) {
                                            if (in_array($key1, ['_menu_item_type', '_menu_item_menu_item_parent', '_menu_item_object_id'])) continue;
                                            $meta_value = self::sanitize_meta_value($meta_item[0]);
                                            update_post_meta($menu_item_id, $key1, $meta_value);
                                        }
                                    }
    
                                    $i++;
                                }
                            }
                        }
                    }
    
                    $locations[$location] = $menu_id;
                }
    
                if (!empty($locations)) {
                    set_theme_mod('nav_menu_locations', $locations);
                }
    
                $this->set_result(['imported', 'menus'], $i);
            }
        }
    
        session_destroy();
    }
    
    
    

    /**
     *
     * Import demo widgets
     *
     * @param $demo_content
     * @return void
     */
    private function import_widgets($demo_content){

        $i = 0;
        if(isset($demo_content['widgets'])){
            $widgets = $demo_content['widgets'];
            
            if(!empty($widgets)){
                foreach ($widgets as $widget_id => $widget) {

	                if ($widget_id === 'widget_nav_menu') {
		                foreach ($widget as $key => $widget_item) {
			                if (isset($widget_item['nav_menu'])) {
				                foreach ($demo_content['menus'] as $menu) {
					                if (isset($menu['menu']['slug'])) {
						                if ($menu['menu']['term_id'] == $widget_item['nav_menu']) {
							                $menu_slug = $menu['menu']['slug'];
							                $menu_object = wp_get_nav_menu_object( $menu_slug );
							                if ($menu_object) {
								                $widget[$key]['nav_menu'] = $menu_object->term_id;
							                }
							                break;
						                }
					                }
				                }
			                }
		                }
	                }

                    $demo_widget_content = $widget;
                    update_option($widget_id, $demo_widget_content);
                    $i++;
                }
            }
        }

        if(isset($demo_content['sidebar_widgets'])){
            $demo_sidebar = $demo_content['sidebar_widgets'];
            update_option('sidebars_widgets', $demo_sidebar);
            $i++;
        }
        if(isset($demo_content['sidebar_blocks'])){
            $demo_widgets_block = $demo_content['sidebar_blocks'];
            update_option('widget_block', $demo_widgets_block);
            $i++;
        }

        
        $this->set_result(['imported', 'widgets'], $i);

    }


    public static function get_post_types(){
        global $wpdb;
        $post_types = [];
        $sql = "SELECT DISTINCT post_type FROM {$wpdb->posts}";
        $stmt = $wpdb->get_results($sql, ARRAY_N);
        if($stmt){
            foreach($stmt as $post_type){
                $post_type_name = $post_type[0];
                if(in_array($post_type_name, ['nav_menu_item', 'revision'])) continue;
                $post_types[] = $post_type_name;
            }
        }
        return $post_types;
    }

    public static function get_page_by_title($title){
        $post_types = self::get_post_types();
        $post = false;
        foreach ( $post_types as $post_type ) {
            $post = get_page_by_title( $title, OBJECT, $post_type );
            if($post){
                break;
            }
        }
        return $post;
    }

    public static function set_permalinks_structure($structure = '/%postname%/'){
        update_option('permalink_structure', $structure);
        flush_rewrite_rules();
    }

    public static function sanitize_meta_value($value){
        if($value){
            $data = @preg_replace_callback(
                '!s:(\d+):"(.*?)";!',
                function($m) {
                    return 's:'.strlen($m[2]).':"'.$m[2].'";';
                },
                $value);
            if(is_string($data) && is_array(@unserialize($data))){
                $value = @unserialize($data);
            } else {
                $value = mw_tools::maybe_serialize($value);
            }
        }
        return wp_slash_strings_only($value);
    }

    public static function cache_item($item_id, $item_value){
        $_SESSION[$item_id] = $item_value;
    }

    public static function get_cache_item($item_id){
        if(isset($_SESSION[$item_id])){
            return $_SESSION[$item_id];
        }

        return false;
    }

    public static function set_cache_option($item_id, $item_key, $item_value, $type = 'option'){
        $options = get_option('ahura_demo_cache');
        if (!is_array($options) || empty($options)){
            $options = [];
        }
        $options[$type][$item_id][$item_key] = $item_value;
        update_option('ahura_demo_cache', $options);
    }

    public static function get_cache_option($item_id, $item_key, $type = 'option'){
        $options = get_option('ahura_demo_cache');
        return is_array($options) && isset($options[$type][$item_id]) && isset($options[$type][$item_id][$item_key]) ? $options[$type][$item_id][$item_key] : false;
    }

    public static function session_start(){
        if(!session_id()){
            session_start();
        }
    }



    /**
     *
     * Fired after import demo
     *
     * @param null $result Default is NULL
     * @param null $demo_content Default is NULL
     * @return void
     */
    public function handle_after_import_demo($result = null, $demo_content = null){
        $home_page_id = get_option('ahura_demo_home_id');
        $header_page_id = get_option('ahura_demo_header_id');
        $footer_page_id = get_option('ahura_demo_footer_id');

        self::set_permalinks_structure();

        

        if($home_page_id){
            update_option('show_on_front', 'page');
            update_option('page_on_front', $home_page_id);
        }

    

   

        if($helloWorldPost = get_page_by_path('hello-world', '', 'post')){
            wp_delete_post($helloWorldPost->ID);
        }

        if($helloWorldPost = get_page_by_path('سلام-دنیا', '', 'post')){
            wp_delete_post($helloWorldPost->ID);
        }

        if(is_rtl()){
            update_option('woocommerce_currency', 'IRT');
            update_option('woocommerce_price_num_decimals', 0);
            update_option('woocommerce_currency_pos', 'right_space');
        }

        $this->set_woocommerce_pages();

        // update_option( 'elementor_container_width', '1280' );
        // update_option( 'elementor_default_generic_fonts', 'IRANSans' );
        // update_option( 'elementor_disable_typography_schemes', 'yes' );


        // global $wp_customize;
        // if (!empty($wp_customize)){
        //     do_action('customize_save_after', $wp_customize);
        // }

        delete_option('ahura_demo_cache');
    }
    

    private function set_woocommerce_pages(){

        // گرفتن آیدی برگه ها بر اساس slug
        $cart_page_id     = $this->get_page_id_by_slug('cart');
        $checkout_page_id = $this->get_page_id_by_slug('checkout');
        $myaccount_page_id= $this->get_page_id_by_slug('my-account');

        // آپدیت تنظیمات ووکامرس
        if($cart_page_id){
            update_option('woocommerce_cart_page_id', $cart_page_id);
        }
        if($checkout_page_id){
            update_option('woocommerce_checkout_page_id', $checkout_page_id);
        }
        if($myaccount_page_id){
            update_option('woocommerce_myaccount_page_id', $myaccount_page_id);
        }
    }

    /**
     * گرفتن ID برگه بر اساس slug
     */
    private function get_page_id_by_slug($slug){
        $page = get_page_by_path($slug);
        return $page ? $page->ID : false;
    }

}