<?php
/**
* Wizard
* @package Whizzie
* @since 1.0.0
*/

class Whizzie {
	protected $version = '1.1.0';
	protected $theme_name = '';
	protected $theme_title = '';
	protected $page_slug = '';
	protected $page_title = '';
	protected $config_steps = array();
	public $parent_slug;
	/**
	 * Constructor
	 * @param $config Configuration parameters
	 */
	public function __construct( $config ) {
		$this->set_vars( $config );
		$this->init();
	}

	/**
	 * Set variables based on configuration
	 * @param $config Configuration parameters
	 */
	public function set_vars( $config ) {
		if ( isset( $config['page_slug'] ) ) {
			$this->page_slug = esc_attr( $config['page_slug'] );
		}
		if ( isset( $config['page_title'] ) ) {
			$this->page_title = esc_attr( $config['page_title'] );
		}
		if ( isset( $config['steps'] ) ) {
			$this->config_steps = $config['steps'];
		}

		$current_theme = wp_get_theme();
		$this->theme_title = $current_theme->get( 'Name' );
		$this->theme_name = strtolower( preg_replace( '#[^a-zA-Z]#', '', $current_theme->get( 'Name' ) ) );
		$this->page_slug = apply_filters( $this->theme_name . '_theme_setup_wizard_page_slug', $this->theme_name . '-wizard' );
		$this->parent_slug = apply_filters( $this->theme_name . '_theme_setup_wizard_parent_slug', '' );
	}

	/*** Initialize hooks and actions ***/
	public function init() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_menu', array( $this, 'menu_page' ) );
		add_action( 'wp_ajax_setup_widgets', array( $this, 'setup_widgets' ) );
	}

	public function enqueue_scripts() {
		wp_enqueue_style( 'theme-wizard-style', get_template_directory_uri() . '/theme-wizard/assets/css/theme-wizard-style.css');
		wp_register_script( 'theme-wizard-script', get_template_directory_uri() . '/theme-wizard/assets/js/theme-wizard-script.js', array( 'jquery' ));
		wp_localize_script(
			'theme-wizard-script',
			'auto_mechanic_whizzie_params',
			array(
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'verify_text' => esc_html( 'verifying', 'auto-mechanic' )
			)
		);
		wp_enqueue_script( 'theme-wizard-script' );
	}

	public function menu_page() {
		add_theme_page( esc_html( $this->page_title ), esc_html( $this->page_title ), 'manage_options', $this->page_slug, array( $this, 'auto_mechanic_setup_wizard' ) );
	}

	/*** Display the wizard page content ***/
	public function wizard_page() { ?>
		<div class="main-wrap">
			<div class="card whizzie-wrap">
				<ul class="whizzie-menu">
					<?php foreach ( $this->get_steps() as $step ) : ?>
						<li data-step="<?php echo esc_attr( $step['id'] ); ?>" class="step step-<?php echo esc_attr( $step['id'] ); ?>">

							<h2><?php echo esc_html( $step['title'] ); ?></h2>

							<?php
							$content = call_user_func( array( $this, $step['view'] ) );
							?>

							<?php if ( isset( $content['summary'] ) ) : ?>
								<div class="summary">
									<?php echo wp_kses_post( $content['summary'] ); ?>
								</div>
							<?php endif; ?>

							<?php if ( isset( $content['detail'] ) ) : ?>
								<p>
									<a href="#" class="more-info">
										<?php esc_html_e( 'More Info', 'auto-mechanic' ); ?>
									</a>
								</p>
								<div class="detail">
									<?php echo wp_kses_post( $content['detail'] ); ?>
								</div>
							<?php endif; ?>

							<?php if ( ! empty( $step['button_text'] ) ) : ?>
								<div class="button-wrap">

									<?php if ( ! get_option( 'is-demo-imported' ) ) : ?>

										<a href="#"
										class="button button-primary do-it"
										data-callback="<?php echo esc_attr( $step['callback'] ); ?>"
										data-step="<?php echo esc_attr( $step['id'] ); ?>">
											<?php echo esc_html( $step['button_text'] ); ?>
										</a>

									<?php else : ?>

										<a target="_blank"
										href="<?php echo esc_url( home_url() ); ?>"
										class="button button-primary"
										style="font-size:20px;font-weight:600;">
											<?php esc_html_e( 'Visit Site', 'auto-mechanic' ); ?>
										</a>

									<?php endif; ?>

								</div>
							<?php endif; ?>

						</li>
					<?php endforeach; ?>
				</ul>
				<div class="step-loading">
					<span class="spinner"></span>
				</div>
			</div>
		</div>
	<?php }

	/*** Setup wizard page content and options ***/
	public function auto_mechanic_setup_wizard() { ?>
		<div class="wrapper-info get-stared-page-wrap">
			<div class="tab-sec theme-option-tab">
				<div id="demo_offer" class="tabcontent">
					<?php $this->wizard_page(); ?>
				</div>
			</div>
		</div>
	<?php }

	/**
	 * Get the steps for the wizard
	 * @return array
	 */
	public function get_steps() {
		$steps = array(
			'intro' => array(
				'id' => 'intro',
				'title' => __( 'Welcome to ', 'auto-mechanic' ) . $this->theme_title,
				'view' => 'get_step_intro',
				'callback' => 'do_next_step',
				'button_text' => __( 'Start Now', 'auto-mechanic' ),
				'can_skip' => false
			),
			'widgets' => array(
				'id' => 'widgets',
				'title' => __( 'Demo Importer', 'auto-mechanic' ),
				'view' => 'get_step_widgets',
				'callback' => 'install_widgets',
				'button_text' => __( 'Import Demo', 'auto-mechanic' ),
				'can_skip' => true
			),
			'done' => array(
				'id' => 'done',
				'title' => __( 'All Done', 'auto-mechanic' ),
				'view' => 'get_step_done'
			)
		);

		return $steps;
	}

	/*** Display the content for the intro step ***/
	public function get_step_intro() { ?>
		<div class="summary">
			<p style="text-align: center;"><?php esc_html_e( 'Thank you for choosing our theme! We are excited to help you get started with your new website.', 'auto-mechanic' ); ?></p>
			<p style="text-align: center;"><?php esc_html_e( 'This section will guide you through setting up and customizing the theme. You can follow the steps to import demo content or adjust settings at any time to make the website look and work the way you want.', 'auto-mechanic' ); ?></p>
		</div>
	<?php }

	/*** Display the content for the widgets step ***/
	public function get_step_widgets() { ?>
		<div class="summary">
			<p><?php esc_html_e('To get started, use the button below to import demo content and add widgets to your site. After installation, you can manage settings and customize your site using the Customizer. Enjoy your new theme!', 'auto-mechanic'); ?></p>
		</div>
	<?php }

	/*** Display the content for the final step ***/
	public function get_step_done() { ?>
		<div id="aster-demo-setup-guid">
			<div class="aster-setup-menu">
				<h3><?php esc_html_e('Setup Navigation Menu','auto-mechanic'); ?></h3>
				<p><?php esc_html_e('Follow the following Steps to Setup Menu','auto-mechanic'); ?></p>
				<h4><?php esc_html_e('A) Create Pages','auto-mechanic'); ?></h4>
				<ol>
					<li><?php esc_html_e('Go to Dashboard >> Pages >> Add New','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Enter Page Details And Save Changes','auto-mechanic'); ?></li>
				</ol>
				<h4><?php esc_html_e('B) Add Pages To Menu','auto-mechanic'); ?></h4>
				<ol>
					<li><?php esc_html_e('Go to Dashboard >> Appearance >> Menu','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Click On The Create Menu Option','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Select The Pages And Click On The Add to Menu Button','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Select Primary Menu From The Menu Setting','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Click On The Save Menu Button','auto-mechanic'); ?></li>
				</ol>
			</div>
			<div class="aster-setup-widget">
				<h3><?php esc_html_e('Setup Footer Widgets','auto-mechanic'); ?></h3>
				<p><?php esc_html_e('Follow the following Steps to Setup Footer Widgets','auto-mechanic'); ?></p>
				<ol>
					<li><?php esc_html_e('Go to Dashboard >> Appearance >> Widgets','auto-mechanic'); ?></li>
					<li><?php esc_html_e('Drag And Add The Widgets In The Footer Columns','auto-mechanic'); ?></li>
				</ol>
			</div>
			<div style="display:flex; flex-wrap: wrap; justify-content: center; margin-top: 20px; gap:20px">
				<div class="aster-setup-finish">
					<a target="_blank" href="<?php echo esc_url(home_url()); ?>" class="button button-primary">Visit Site</a>
				</div>
				<div class="aster-setup-finish">
					<a target="_blank" href="<?php echo esc_url( admin_url('customize.php') ); ?>" class="button button-primary">Customize Your Demo</a>
				</div>
				<div class="aster-setup-finish">
					<a target="_blank" href="<?php echo esc_url( admin_url('themes.php?page=auto-mechanic-getting-started') ); ?>" class="button button-primary">Dashboard</a>
				</div>
			</div>
		</div>
	<?php }


	//                      ------------- MENUS -----------------                    //

	public function auto_mechanic_customizer_primary_menu(){

		// ------- Create Primary Menu --------
		$auto_mechanic_menuname = $auto_mechanic_themename . 'Primary Menu';
		$auto_mechanic_bpmenulocation = 'primary';
		$auto_mechanic_menu_exists = wp_get_nav_menu_object( $auto_mechanic_menuname );

		if( !$auto_mechanic_menu_exists){
			$auto_mechanic_menu_id = wp_create_nav_menu($auto_mechanic_menuname);
			$auto_mechanic_parent_item = 
			wp_update_nav_menu_item($auto_mechanic_menu_id, 0, array(
				'menu-item-title' =>  __('Home','auto-mechanic'),
				'menu-item-classes' => 'home',
				'menu-item-url' => home_url( '/' ),
				'menu-item-status' => 'publish'));

			wp_update_nav_menu_item($auto_mechanic_menu_id, 0, array(
				'menu-item-title' =>  __('Bikes','auto-mechanic'),
				'menu-item-classes' => 'bikes',
				'menu-item-url' => get_permalink(get_page_by_title('Bikes')),
				'menu-item-status' => 'publish'));

			wp_update_nav_menu_item($auto_mechanic_menu_id, 0, array(
				'menu-item-title' =>  __('Cars','auto-mechanic'),
				'menu-item-classes' => 'cars',
				'menu-item-url' => get_permalink(get_page_by_title('Cars')),
				'menu-item-status' => 'publish'));

			wp_update_nav_menu_item($auto_mechanic_menu_id, 0, array(
				'menu-item-title' =>  __('Blogs','auto-mechanic'),
				'menu-item-classes' => 'blog',
				'menu-item-url' => get_permalink(get_page_by_title('Blogs')),
				'menu-item-status' => 'publish'));

			if( !has_nav_menu( $auto_mechanic_bpmenulocation ) ){
				$locations = get_theme_mod('nav_menu_locations');
				$locations[$auto_mechanic_bpmenulocation] = $auto_mechanic_menu_id;
				set_theme_mod( 'nav_menu_locations', $locations );
			}
		}
	}


	//                      ------------- /*** Imports demo content ***/ -----------------                    //

	public function setup_widgets() {

		// Create a front page and assigned the template
		$auto_mechanic_home_title = 'Home';
		$auto_mechanic_home_check = get_page_by_title($auto_mechanic_home_title);
		$auto_mechanic_home = array(
			'post_type' => 'page',
			'post_title' => $auto_mechanic_home_title,
			'post_status' => 'publish',
			'post_author' => 1,
			'post_slug' => 'home'
		);
		$auto_mechanic_home_id = wp_insert_post($auto_mechanic_home);

		//Set the static front page
		$auto_mechanic_home = get_page_by_title( 'Home' );
		update_option( 'page_on_front', $auto_mechanic_home->ID );
		update_option( 'show_on_front', 'page' );


		// Create a posts page and assigned the template
		$auto_mechanic_blog_title = 'Blogs';
		$auto_mechanic_blog = get_page_by_title($auto_mechanic_blog_title);

		if (!$auto_mechanic_blog) {
			$auto_mechanic_blog = array(
				'post_type' => 'page',
				'post_title' => $auto_mechanic_blog_title,
				'post_status' => 'publish',
				'post_author' => 1,
				'post_name' => 'blog'
			);
			$auto_mechanic_blog_id = wp_insert_post($auto_mechanic_blog);

			if (is_wp_error($auto_mechanic_blog_id)) {
				// Handle error
			}
		} else {
			$auto_mechanic_blog_id = $auto_mechanic_blog->ID;
		}
		// Set the posts page
		update_option('page_for_posts', $auto_mechanic_blog_id);

		
		// Create a BIKES and assigned the template
		$auto_mechanic_bikes_title = 'Bikes';
		$auto_mechanic_bikes_check = get_page_by_title($auto_mechanic_bikes_title);
		$auto_mechanic_bikes = array(
			'post_type' => 'page',
			'post_title' => $auto_mechanic_bikes_title,
			'post_content' => '<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>',
			'post_status' => 'publish',
			'post_author' => 1,
			'post_slug' => 'blog'
		);
		$auto_mechanic_bikes_id = wp_insert_post($auto_mechanic_bikes);

		
		// Create a CARS and assigned the template
		$auto_mechanic_cars_title = 'Cars';
		$auto_mechanic_cars_check = get_page_by_title($auto_mechanic_cars_title);
		$auto_mechanic_cars = array(
			'post_type' => 'page',
			'post_title' => $auto_mechanic_cars_title,
			'post_content' => '<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960 with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>',
			'post_status' => 'publish',
			'post_author' => 1,
			'post_slug' => 'blog'
		);
		$auto_mechanic_cars_id = wp_insert_post($auto_mechanic_cars);


		/*----------------------------------------- Header Button --------------------------------------------------*/

			set_theme_mod( 'auto_mechanic_welcome_topbar_text','Welcome To Our Theme');
			

		// ------------------------------------------ Blogs for Sections --------------------------------------

			// Create categories if not already created
			$auto_mechanic_category_slider = wp_create_category('Slider');
			$auto_mechanic_category_services = wp_create_category('Services');

			// Array of categories to assign to each set of posts
			$auto_mechanic_categories = array($auto_mechanic_category_slider, $auto_mechanic_category_services);

			// Array of image URLs for the "Services" category
			$services_images = array(
				get_template_directory_uri() . '/resource/img/services1.png',
				get_template_directory_uri() . '/resource/img/services2.png',
				get_template_directory_uri() . '/resource/img/services3.png',
			);

			// Loop to create posts
			for ($i = 1; $i <= 6; $i++) {
				$title = array(
					'Excellence in Service',
					'Expert Mechanics, Unmatched Service',
					'Your Car Deserves Excellence in Service',
					'Luxury Cars',
					'Sports Cars',
					'SUV’s Cars'
				);

				$content = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since.';

				// Determine category and post index to use for title
				$category_index = ($i <= 3) ? 0 : 1; // First 3 for Slider, next 3 for Services
				$post_title = $title[$i - 1]; // Adjust for zero-based index in title array

				// Create post object
				$my_post = array(
					'post_title'    => wp_strip_all_tags($post_title),
					'post_content'  => $content,
					'post_status'   => 'publish',
					'post_type'     => 'post',
					'post_category' => array($auto_mechanic_categories[$category_index]), // Assign Slider to first 3, Services to next 3
				);

				// Insert the post into the database
				$post_id = wp_insert_post($my_post);

				// Determine the category and set image URLs based on category
				if ($category_index === 0) { // Slider category
					$slider_index = $i % 3 + 1; // Cycles through 1, 2, 3
					$auto_mechanic_image_url = get_template_directory_uri() . "/resource/img/slider{$slider_index}.png";
					$auto_mechanic_image_name = "slider{$slider_index}.png";
				} else { // Services category
					// Use different images for each post in Services category
					$services_image_index = $i - 4; // Correct index for the Services images array (i: 4, 5, 6 -> index: 0, 1, 2)
					$auto_mechanic_image_url = $services_images[$services_image_index];
					$auto_mechanic_image_name = basename($auto_mechanic_image_url);
				}

				$auto_mechanic_upload_dir = wp_upload_dir();
				$auto_mechanic_image_data = @file_get_contents($auto_mechanic_image_url); // Use @ to suppress errors

				if ($auto_mechanic_image_data === false) {
					continue; // Skip this iteration if image data is not found
				}

				$auto_mechanic_unique_file_name = wp_unique_filename($auto_mechanic_upload_dir['path'], $auto_mechanic_image_name);
				$filename = basename($auto_mechanic_unique_file_name);

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

				if ( ! function_exists( 'WP_Filesystem' ) ) {
					require_once( ABSPATH . 'wp-admin/includes/file.php' );
				}
				
				WP_Filesystem();
				global $wp_filesystem;
				
				if ( ! $wp_filesystem->put_contents( $file, $auto_mechanic_image_data, FS_CHMOD_FILE ) ) {
					wp_die( 'Error saving file!' );
				}

				$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'
				);

				$auto_mechanic_attach_id = wp_insert_attachment($attachment, $file, $post_id);

				require_once(ABSPATH . 'wp-admin/includes/image.php');

				$auto_mechanic_attach_data = wp_generate_attachment_metadata($auto_mechanic_attach_id, $file);
				wp_update_attachment_metadata($auto_mechanic_attach_id, $auto_mechanic_attach_data);
				set_post_thumbnail($post_id, $auto_mechanic_attach_id);
			}

		
		// ---------------------------------------- Slider --------------------------------------------------- //

			set_theme_mod('banner_heading','Precision In Motion');
		
			for($i=1; $i<=3; $i++) {
				set_theme_mod('auto_mechanic_banner_button_label_'.$i,'Explore Now');
				set_theme_mod('auto_mechanic_banner_button_link_'.$i,'');
			}
			

		// ---------------------------------------- Services --------------------------------------------------- //

			set_theme_mod('auto_mechanic_heading_services_section','Types of vehicles we repair');
			set_theme_mod('auto_mechanic_enable_banner_section',true);
			
			set_theme_mod('auto_mechanic_services_number', 2); // Setting 2 tabs for demo.

			// Loop to set default tab text values based on the number of tabs.
			$tabs_to_set = get_theme_mod('auto_mechanic_services_number', 0);
			for ($i = 1; $i <= $tabs_to_set; $i++) {
				set_theme_mod('auto_mechanic_services_text' . $i, ($i == 1) ? '4 Wheeler' : '2 Wheeler');
				set_theme_mod('auto_mechanic_services_category'.$i,'Services');
			}
			set_theme_mod('auto_mechanic_enable_services_section',true);		

		// ---------------------------------------- Footer section --------------------------------------------------- //	
		
			set_theme_mod('auto_mechanic_footer_background_color_setting','#1f1f1f');
			
		// ---------------------------------------- Related post_tag --------------------------------------------------- //	
		
			set_theme_mod('auto_mechanic_post_related_post_label','Related Posts');
			set_theme_mod('auto_mechanic_related_posts_count','3');


		$this->auto_mechanic_customizer_primary_menu();
		update_option('is-demo-imported', true);
	}
}