<?php
namespace BricksUltimate\WooCommerce;

if ( ! defined( 'ABSPATH' ) ) exit;

use BricksUltimate\Helpers;

class WooLinkedProducts {
	public static $instance = null;
	public $post_type = 'bu_linked_variations';

	public function __construct(){
		$this->bu_register_post_type();

		if( is_admin() ) {
			add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 30 );
			add_action( 'save_post', [ $this, 'save_linked_variations_post' ], PHP_INT_MAX - 10, 2 );
			add_action( 'admin_enqueue_scripts', array( $this, 'scripts' ) );
			add_filter( 'parent_file', [ $this, 'bu_parent_menu_active' ] );
			add_filter( "manage_{$this->post_type}_posts_columns", [ $this, 'bu_lv_posts_columns' ] );
			add_action( "manage_{$this->post_type}_posts_custom_column", [ $this, 'bu_lv_post_columns_data' ], 10, 2 );
		} else {
			//add_action( 'wp_head', [ $this, 'bulv_generate_seo_schema'] );
		}
	}

	/**
	 * Add Order Bumps Meta boxes.
	 */
	public function add_meta_boxes() {
		// Products.
		add_meta_box( 'bu-lv-data', __( 'Settings', 'bricksultimate' ), [ $this, 'output' ], $this->post_type, 'normal', 'high' );
	}

	/**
	 * Order Bumps meta boxes output.
	 */
	public function output( $post ) {
		global $thepostid;
		$thepostid = $post->ID;
		wp_nonce_field( 'bu_lv_save_data', 'bu_lv_meta_nonce' );

		include_once __DIR__ . '../../Admin/views/html-linked-products-data.php';
	}

	public function scripts() {
		$screen  = get_current_screen();
		if ( in_array( $screen->id, array( $this->post_type ), true ) ) {
			wp_enqueue_style( 'woocommerce_admin_styles' );

			wp_enqueue_script( 'woocommerce_admin' );
			//wp_enqueue_script( 'wc-enhanced-select' );

			wp_register_script( 'wc-admin-product-meta-boxes', WC()->plugin_url() . '/assets/js/admin/meta-boxes-product.min.js', array( 'wc-admin-meta-boxes', 'media-models' ), '9.5.3' );
			wp_enqueue_script( 'wc-admin-product-meta-boxes' );

			wp_enqueue_script( 'bu-linked-products', Helpers::get_asset_url('js') . 'bulinkedproducts.min.js', [], filemtime(Helpers::get_asset_path('js') . 'bulinkedproducts.min.js' ),true);

			wp_enqueue_style( 'bu-linked-products', Helpers::get_asset_url('css') . 'bulp.min.css', filemtime(Helpers::get_asset_path('css') . 'bulp.min.css' ) );

			$params = array(
				'urls' => array(
					'add_product'     => null,
					'import_products' => null,
					'export_products' => null,
				),
			);
			wp_localize_script( 'woocommerce_admin', 'woocommerce_admin', $params );
			wp_localize_script( 'wc-admin-meta-boxes', 'woocommerce_admin_meta_boxes', [] );
		}
	}

	public function bu_register_post_type() {
		register_post_type(
			$this->post_type,
			array(
				'label'              => esc_html__( 'Linked Variations', 'bricksultimate' ),
				'labels'             => array(
					'name'          => esc_html__( 'Linked Variations', 'bricksultimate' ),
					'singular_name' => esc_html__( 'Linked Variation', 'bricksultimate' ),
					'menu_name'     => esc_html__( 'Linked Variations', 'bricksultimate' ),
					'add_new'       => esc_html__( 'Add New', 'bricksultimate' ),
					'add_new_item'  => esc_html__( 'Add New', 'bricksultimate' ),
				),
				'supports'           => array( 'title' ),
				'hierarchical'       => false,
				'public'             => true,
				'show_in_menu'       => false,
				'publicly_queryable' => false,
				'exclude_from_search' => true,
				'show_in_rest'       => true,
				'capability_type'    => 'product',
			)
		);
	}

	public function save_linked_variations_post( $post_id, $post ) {
		if ( ! current_user_can( 'edit_posts' ) ) {
			return $post_id;
		}

		// Check if the nonce is set
	    if ( ! isset( $_POST['bu_lv_meta_nonce'] ) ) {
	        return $post_id; // No nonce, no save
	    }

	    // Verify the nonce
	    if ( ! wp_verify_nonce( $_POST['bu_lv_meta_nonce'], 'bu_lv_save_data' ) ) {
	        return $post_id; // Nonce verification failed
	    }

		// Revision
		if ( wp_is_post_revision( $post_id ) ) {
			return $post_id;
		}

		// Autosave
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return $post_id;
		}

		if ( $this->post_type !== $post->post_type ) {
			return $post_id;
		}

		if( isset($_POST['bulv_products'] ) ) {
			update_post_meta( $post_id, '_bulv_products', $_POST['bulv_products'] ?? 0 );
		} else {
			delete_post_meta( $post_id, '_bulv_products' );
		}

		if( isset($_POST['bulv_attributes'] ) ) {
			update_post_meta( $post_id, '_bulv_attributes', $_POST['bulv_attributes'] ?? 0 );
		} else {
			delete_post_meta( $post_id, '_bulv_attributes' );
		}

		if( isset($_POST['bulv_attributes_only_text'] ) ) {
			update_post_meta( $post_id, '_bulv_attributes_only_text', $_POST['bulv_attributes_only_text'] ?? 0 );
		} else {
			delete_post_meta( $post_id, '_bulv_attributes_only_text' );
		}

		if( isset($_POST['bulv_attributes_image'] ) ) {
			update_post_meta( $post_id, '_bulv_attributes_image', $_POST['bulv_attributes_image'] ?? 0 );
		} else {
			delete_post_meta( $post_id, '_bulv_attributes_image' );
		}

		return $post_id;
	}

	public function bu_lv_posts_columns( $columns ) {
		$date = array_pop( $columns );

		$columns['lv_products'] 	= __('Products Linked', 'bricksultimate');
		$columns['lv_attributes'] 	= __('Attributes Linked', 'bricksultimate');
		$columns['date'] 			= $date;

		return $columns;
	}

	public function bu_lv_post_columns_data( $column, $post_id ) {
		if ( 'lv_products' === $column ) {
			$products = get_post_meta( $post_id, '_bulv_products', true ) ?? array();
			foreach ( $products as $index => $product_id ) {
				printf( "<a href='%s'>%s</a>", esc_url( get_edit_post_link( $product_id ) ), get_the_title( $product_id ) );

				if( count( $products ) > 0 && ( $index + 1 ) < count( $products ) )
					echo ', ';
			}
		}

		if( 'lv_attributes' == $column ) {
			$attributes = get_post_meta( $post_id, '_bulv_attributes', true ) ?? array();
			$wc_attributes = wc_get_attribute_taxonomies();
			$i = 0;

			foreach ( $wc_attributes as $wc_attribute ) {
				$att_name = 'pa_' . $wc_attribute->attribute_name;

				if ( $attributes && in_array($att_name, $attributes) ) {
					$link = "edit-tags.php?taxonomy=$att_name&amp;post_type=product";
					printf( "<a href='%s'>%s</a>", admin_url( $link ), esc_html( htmlspecialchars( wp_kses_post( $wc_attribute->attribute_label ) ) ) );

					if( count( $attributes ) > 0 && ( $i + 1 ) < count( $attributes ) )
						echo ', ';

					$i++;
				}
			}
		}
	}

	/**
	 * Active the parent menu.
	 */
	public function bu_parent_menu_active( $parent_file ) {
		global $plugin_page, $post_type;

		if ( $this->post_type === $post_type ) {
			$plugin_page = 'bricks';
		}

		return $parent_file;
	}

	public static function get_instance() {
        if ( null == self::$instance ) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /*private function bulv_generate_seo_schema() {
    	global $product;
    	$product = wc_get_product( get_the_ID() );
    	if( is_singular( 'product') && $product ) {
	    	$isLinkedProduct = $this->isLinkedProduct( $product->get_id() );
	    	if( $isLinkedProduct ) {
	    		//echo 
	    	}
	    }
    }*/

    public function isLinkedProduct( $product_id ) {
    	global $wpdb;

		$post_type = $this->post_type;

		// Prepare the SQL query
		$query = $wpdb->prepare(
			"
			SELECT SQL_CALC_FOUND_ROWS posts.ID 
			FROM {$wpdb->posts} AS posts
			INNER JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id
			WHERE posts.post_type = %s
			AND posts.post_status = 'publish'
			AND meta.meta_key = '_bulv_products'
			AND meta.meta_value LIKE %s
			ORDER BY posts.post_date DESC
			LIMIT 1
			",
			$post_type,
			'%"' . (int) $product_id . '"%'
		);

		return $wpdb->get_row($query);
    }
}