<?php

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wondercode.pro/
 * @since      1.0.0
 *
 * @package    Awesome_Designs_For_Woocommerce
 * @subpackage Awesome_Designs_For_Woocommerce/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Awesome_Designs_For_Woocommerce
 * @subpackage Awesome_Designs_For_Woocommerce/admin
 * @author     Mcurly <contact@wondercode.pro>
 */
class Awesome_Designs_For_Woocommerce_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;

		// Add the filter for the settings link
		add_filter( 'plugin_action_links_' . 'awesome-designs-for-woocommerce/awesome-designs-for-woocommerce.php', array( &$this, 'awesome_designs_for_woocommerce_add_settings_link') );

		// Check if WooCommerce is enabled 
		add_action( 'admin_init', array( &$this, 'check_woocommerce_dependency' ) );

		// Ajax for template design selection
		add_action( 'wp_ajax_update_option_with_id', array( &$this, 'update_design_id' ) );
		add_action( 'wp_ajax_nopriv_update_option_with_id', array( &$this, 'update_design_id' ) );

	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/awesome-designs-for-woocommerce-admin.css', array(), $this->version, 'all' );

		// Modal Thickbox
		wp_enqueue_style('thickbox');
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/awesome-designs-for-woocommerce-admin.js', array( 'jquery' ), $this->version, false );

		$adfw_ajax_vars = array(
			'ajax_url' 				=> esc_url( admin_url( 'admin-ajax.php' ) ),
			'nonce' 				=> wp_create_nonce('update_option_nonce'),
			'update_successfull'	=> esc_html__( 'Option updated successfully !', 'awesome-designs-for-woocommerce' ),
			'update_fail'			=> esc_html__( 'Failed to update design', 'awesome-designs-for-woocommerce' ),
			'update_error'			=> esc_html__( 'An error occurred', 'awesome-designs-for-woocommerce' ),

		);

		wp_localize_script( $this->plugin_name, 'adfw_ajax_object', $adfw_ajax_vars );

		// Modal Thickbox for design selection
		wp_enqueue_script('thickbox');
	}



	/**
	 * Adds a settings link to the plugin listing
	 *
	 * @since    1.0.0
	 */
	public function awesome_designs_for_woocommerce_add_settings_link( $actions ) {

		// The link to plugin's settings page
		$settings_link =  array( '<a href="' . admin_url( 'admin.php?page=awesome-designs-for-woocommerce-settings' ) . '">'. esc_html__( 'Settings', 'awesome-designs-for-woocommerce' ) .'</a>' );
		// Add the link at the beginning of the links array
		$actions = array_merge( $settings_link, $actions );

		return $actions;
	}


	/**
	 * Check if WooCommerce is active
	 *
	 * @since    1.0.0
	 */
	public function check_woocommerce_dependency() {
		if (!is_plugin_active('woocommerce/woocommerce.php')) {

			// WooCommerce is not active, disable the plugin
			deactivate_plugins('awesome-designs-for-woocommerce/awesome-designs-for-woocommerce.php');
			
			// Show an error message to the user
			add_action('admin_notices', function() {
				echo '<div class="notice notice-error is-dismissible"><p>';
				esc_html_e('Awesome designs for WooCommerce requires WooCommerce to run. Please activate WooCommerce first. Awesome designs for WooCommerce has been disabled', 'awesome-designs-for-woocommerce');
				echo '</p></div>';
			});
		}
	}

	/**
	 * Add plugin menu
	 *
	 * @since    1.0.0
	 */
	public function add_menu() {
		
		//add_options_page( 'Awesome designs for WooCommerce', 'Awesome designs WC', 'manage_options', $this->plugin_name . '-settings', array( $this, 'page_options' ) );
		
		add_submenu_page(
			'woocommerce', // Parent menu slug
			'Awesome designs for WooCommerce', // Title of page
			'Awesome Designs', // Title of menu
			'manage_options', // Capacity required
			$this->plugin_name . '-settings', // menu slug
			array( $this, 'page_options' )
		);

		register_setting( 'Awesome-designs-for-woocommerce', 'Awesome_designs_for_woocommerce_main_settings' );
	}
	

	/**
	 * Display plugin admin page
	 *
	 * @since    1.0.0
	 */
	public function page_options() {
				
		if ( !current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'awesome-designs-for-woocommerce' ) );
		}
			
		include( plugin_dir_path( __FILE__ ) . 'partials/awesome-designs-for-woocommerce-admin-display.php' );
	}


	/**
	 * Ajax function to update design selection
	 *
	 * @since    1.0.0
	 */
	public function update_design_id() {
		// Check for nonce for security (optional but recommended)
		check_ajax_referer('update_option_nonce', 'security');

		if (isset($_POST['id'])) {
			$id = intval($_POST['id']);
			
			// Define the option name and value based on the ID
			$option_value['design'] = $id; // Replace with the actual value you want to set

			// Update from Gutenberg template to classic editor for WooCommerce pages
			$this->update_archive_product_template();
			$this->update_single_product_template();
			$this->update_cart_page_template();
			
			// Update the option in the database
			if (update_option('Awesome_designs_for_woocommerce_main_settings', $option_value)) {
				wp_send_json_success('Option updated successfully');
			} else {
				wp_send_json_error('Failed to update option');
			}
		} else {
			wp_send_json_error('Invalid ID');
		}
	}


	/**
	 * Update content of WooCommerce product archive template
	 *
	 * @since    1.0.0
	 */
	public function update_archive_product_template() {

		global $wpdb;
	
		// Get ID using post_name & post_type
		$args = array(
			'name'           => 'archive-product',
			'post_type'      => 'wp_template',
			'post_status'    => 'publish',
			'fields'         => 'ids',
			'posts_per_page' => 1,
		);
		
		$query = new WP_Query($args);
		
		$page_id = !empty($query->posts) ? $query->posts[0] : null;
	
		if (!$page_id) {
	
			// MySQL Time
			$current_time 		= current_time('mysql');
			$current_time_gmt 	= gmdate('Y-m-d H:i:s');
	
			$post_data = array(
				'post_author'       => 1,
				'post_date'         => $current_time,
				'post_date_gmt'     => $current_time_gmt,
				'post_content'      => '<!-- wp:template-part {"slug":"header","theme":"twentytwentyfour"} /-->
	<!-- wp:group {"layout":{"inherit":true,"type":"constrained"}} -->
	<div class="wp-block-group"><!-- wp:woocommerce/legacy-template {"template":"archive-product"} /--></div>
	<!-- /wp:group -->
	<!-- wp:template-part {"slug":"footer","theme":"twentytwentyfour"} /-->',
				'post_title'        => 'Product Catalog',
				'post_excerpt'      => 'Displays your products.',
				'post_status'       => 'publish',
				'comment_status'    => 'closed',
				'ping_status'       => 'closed',
				'post_name'         => 'archive-product',
				'post_modified'     => $current_time,
				'post_modified_gmt' => $current_time_gmt,
				'post_parent'       => 0,
				'guid'              => get_post_type_archive_link('product'), // Use URL of product archive
				'menu_order'        => 0,
				'post_type'         => 'wp_template',
				'post_mime_type'    => '',
				'comment_count'     => 0
			);
	
			$shop_id = wp_insert_post($post_data);
	
			if (is_wp_error($shop_id)) {
				echo esc_html( 'Error inserting post: ' . $shop_id->get_error_message() );
				return;
			}
	
			$term = get_term_by('name', 'woocommerce/woocommerce', 'wp_theme');
		
			if (!$term) {
				
				// If the term does not exist, add it
				$result = wp_insert_term(
					'woocommerce/woocommerce', // The name of the term
					'wp_theme', // The taxonomy
					array(
						'slug' => 'woocommerce-woocommerce', // The slug of the term
					)
				);
			
				// Check if the insertion was successful
				if (is_wp_error($result)) {
					echo esc_html( 'Error: ' . $result->get_error_message() );
				} else {
					$term_taxonomy_id = $result['term_taxonomy_id'];
				}
	
			} else {
				$term_taxonomy_id = $term->term_taxonomy_id;
			}
	
			// Add the relationship directly in the wp_term_relationships table
			if (isset($term_taxonomy_id)) {
				$result = $wpdb->insert(
					$wpdb->term_relationships,
					array(
						'object_id' => $shop_id,
						'term_taxonomy_id' => $term_taxonomy_id,
						'term_order' => 0 // Specify the term order, 0 by default
					),
					array(
						'%d',
						'%d',
						'%d'
					)
				);
	
				if ($result === false) {
					echo 'Error adding term-object relationship';
					return;
				}
			}
	
		}
		
		// Clean up after WP_Query
		wp_reset_postdata();
	
		// Make sure $page_id contains a valid value
		if ($page_id) {
	
			// Define new content for the post
			$new_content = '<!-- wp:template-part {"slug":"header"} /-->
	<!-- wp:group {"layout":{"inherit":true,"type":"constrained"}} -->
	<div class="wp-block-group"><!-- wp:woocommerce/legacy-template {"template":"archive-product"} /--></div>
	<!-- /wp:group -->
	<!-- wp:template-part {"slug":"footer"} /-->';
	
			$post_update_data = array(
				'ID'           => $page_id,
				'post_content' => $new_content
			);
	
			// Update the post
			$result = wp_update_post($post_update_data, true);
	
			if (is_wp_error($result)) {
				echo esc_html( 'Error updating post: ' . $result->get_error_message() );
				return;
			}
		}
	
	}	


	/**
	 * Update content of WooCommerce single product template
	 *
	 * @since    1.0.0
	 */
	public function update_single_product_template() {

		global $wpdb;
	
		// Get ID using post_name & post_type
		$args = array(
			'name'           => 'single-product',
			'post_type'      => 'wp_template',
			'post_status'    => 'publish',
			'fields'         => 'ids',
			'posts_per_page' => 1,
		);
		
		$query = new WP_Query($args);
		
		$page_id = !empty($query->posts) ? $query->posts[0] : null;
	
		if (!$page_id) {
	
			// MySQL Time
			$current_time 		= current_time('mysql');
			$current_time_gmt 	= gmdate('Y-m-d H:i:s');
	
			$post_data = array(
				'post_author'       => 1,
				'post_date'         => $current_time,
				'post_date_gmt'     => $current_time_gmt,
				'post_content'      => '<!-- wp:template-part {"slug":"header","theme":"twentytwentyfour"} /-->
	<!-- wp:group {"layout":{"inherit":true,"type":"constrained"}} -->
	<div class="wp-block-group"><!-- wp:woocommerce/legacy-template {"template":"single-product"} /--></div>
	<!-- /wp:group -->
	<!-- wp:template-part {"slug":"footer","theme":"twentytwentyfour"} /-->',
				'post_title'        => 'Single Product',
				'post_excerpt'      => 'Displays a single product.',
				'post_status'       => 'publish',
				'comment_status'    => 'closed',
				'ping_status'       => 'closed',
				'post_name'         => 'single-product',
				'post_modified'     => $current_time,
				'post_modified_gmt' => $current_time_gmt,
				'post_parent'       => 0,
				'guid'              => get_permalink(), // Use permalink of the single product
				'menu_order'        => 0,
				'post_type'         => 'wp_template',
				'post_mime_type'    => '',
				'comment_count'     => 0
			);
	
			$single_product_id = wp_insert_post($post_data);
	
			if (is_wp_error($single_product_id)) {
				echo esc_html( 'Error inserting post: ' . $single_product_id->get_error_message() );
				return;
			}
	
			$term = get_term_by('name', 'woocommerce/woocommerce', 'wp_theme');
		
			if (!$term) {
				
				// If the term does not exist, add it
				$result = wp_insert_term(
					'woocommerce/woocommerce', // The name of the term
					'wp_theme', // The taxonomy (replace with the appropriate taxonomy)
					array(
						'slug' => 'woocommerce-woocommerce', // The slug of the term
					)
				);
			
				// Check if the insertion was successful
				if (is_wp_error($result)) {
					echo esc_html( 'Error: ' . $result->get_error_message() );
					return;
				}
	
			} else {
				$term_taxonomy_id = $term->term_taxonomy_id;
			}
	
			// Add the relationship directly in the wp_term_relationships table
			if (isset($term_taxonomy_id)) {
				$result = $wpdb->insert(
					$wpdb->term_relationships,
					array(
						'object_id' => $single_product_id,
						'term_taxonomy_id' => $term_taxonomy_id,
						'term_order' => 0 // You can specify the term order, 0 by default
					),
					array(
						'%d',
						'%d',
						'%d'
					)
				);
	
				if ($result === false) {
					echo 'Error adding term-object relationship';
					return;
				}
			}
	
		}
		
		// Clean up after WP_Query
		wp_reset_postdata();
	
		// Make sure $page_id contains a valid value
		if ($page_id) {
	
			// Define new content for the post
			$new_content = '<!-- wp:template-part {"slug":"header"} /-->
	<!-- wp:group {"layout":{"inherit":true,"type":"constrained"}} -->
	<div class="wp-block-group"><!-- wp:woocommerce/legacy-template {"template":"single-product"} /--></div>
	<!-- /wp:group -->
	<!-- wp:template-part {"slug":"footer"} /-->';
	
			$post_update_data = array(
				'ID'           => $page_id,
				'post_content' => $new_content
			);
	
			// Update the post
			$result = wp_update_post($post_update_data, true);
	
			if (is_wp_error($result)) {
				echo esc_html( 'Error updating post: ' . $result->get_error_message() );
				return;
			}
		}
	
	}	
	

	/**
	 * Update content of WooCommerce cart page template
	 *
	 * @since    1.0.0
	 */
	public function update_cart_page_template() {

		global $wpdb;
	
		$cart_url 	= wc_get_cart_url();
		$page_id 	= url_to_postid($cart_url);
	
		if (!$page_id) {
			// MySQL Time
			$current_time = current_time('mysql');
			$current_time_gmt = gmdate('Y-m-d H:i:s');
	
			$post_data = array(
				'post_author'       => 1,
				'post_date'         => $current_time,
				'post_date_gmt'     => $current_time_gmt,
				'post_content'      => '<!-- wp:woocommerce/classic-shortcode /-->',
				'post_title'        => 'Cart',
				'post_excerpt'      => 'Displays the shopping cart.',
				'post_status'       => 'publish',
				'comment_status'    => 'closed',
				'ping_status'       => 'closed',
				'post_name'         => 'cart',
				'post_modified'     => $current_time,
				'post_modified_gmt' => $current_time_gmt,
				'post_parent'       => 0,
				'guid'              => wc_get_cart_url(), // Use URL of cart
				'menu_order'        => 0,
				'post_type'         => 'wp_template',
				'post_mime_type'    => '',
				'comment_count'     => 0
			);
	
			$page_id = wp_insert_post($post_data);
	
			if (is_wp_error($page_id)) {
				echo esc_html( 'Error inserting post: ' . $page_id->get_error_message() );
				return;
			}
	
			$term = get_term_by('name', 'woocommerce/woocommerce', 'wp_theme');
		
			if (!$term) {
				
				// If the term does not exist, add it
				$result = wp_insert_term(
					'woocommerce/woocommerce', // The name of the term
					'wp_theme', // The taxonomy (replace with the appropriate taxonomy)
					array(
						'slug' => 'woocommerce-woocommerce', // The slug of the term
					)
				);
			
				// Check if the insertion was successful
				if (is_wp_error($result)) {
					echo esc_html( 'Error: ' . $result->get_error_message() );
					return;
				}
	
			} else {
				$term_taxonomy_id = $term->term_taxonomy_id;
			}
	
			// Add the relationship directly in the wp_term_relationships table
			if (isset($term_taxonomy_id)) {
				$result = $wpdb->insert(
					$wpdb->term_relationships,
					array(
						'object_id' => $page_id,
						'term_taxonomy_id' => $term_taxonomy_id,
						'term_order' => 0 // You can specify the term order, 0 by default
					),
					array(
						'%d',
						'%d',
						'%d'
					)
				);
	
				if ($result === false) {
					echo 'Error adding term-object relationship';
					return;
				}
			}
		}
		
		// Clean up after WP_Query
		wp_reset_postdata();
	
		// Make sure $page_id contains a valid value
		if ($page_id) {
	
			// Define new content for the post
			$new_content = '<!-- wp:woocommerce/classic-shortcode /-->';
	
			$post_update_data = array(
				'ID'           => $page_id,
				'post_content' => $new_content
			);
	
			// Update the post
			$result = wp_update_post($post_update_data, true);
	
			if (is_wp_error($result)) {
				echo esc_html( 'Error updating post: ' . $result->get_error_message() );
				return;
			}
		}
	
	}	
	

}