<?php 
namespace QuizPressWoocommerce;

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


class Integration {
    public static function init() {
        $self = new self();
        // Add dropdown field in product data -> General tab
		add_action( 'woocommerce_product_options_general_product_data', array( $self, 'quizpress_quiz_linked_with_woo_product' ), 10, 2 );
		// Save product with courses
		add_action( 'woocommerce_admin_process_product_object', array( $self, 'save_quizpress_quiz_meta' ) );
		// save meta value
		add_filter( 'product_type_options', array( $self, 'add_quizpress_type_in_wc_product' ) );
		add_action( 'save_post_product', array( $self, 'save_wc_product_meta' ) );
		add_action( 'rest_after_insert_quizpress_quiz', array( $self, 'update_product_meta' ), 10, 1 );
		add_action( 'before_delete_post', array( $self, 'quizpress_clear_quiz_product_relation' ) );
		add_action( 'wp_trash_post', array( $self, 'quizpress_clear_quiz_product_relation' ) );
    }

    public function quizpress_quiz_linked_with_woo_product() {
		$quizzes = get_posts( [
			'post_type' => 'quizpress_quiz',
			'posts_per_page' => -1,
			'post_status' => 'publish'
		] );

		if ( $quizzes ) {
			woocommerce_wp_select( [
				'id'      => '_linked_quizpress_quiz',
				'label'   => __( 'Linked QuizPress Quiz', 'quizpress' ),
				'options' => wp_list_pluck( $quizzes, 'post_title', 'ID' ),
				'desc_tip' => true,
				'description' => __( 'Select a quiz to link with this product.', 'quizpress' ),
			] );
		}

	}

	public function save_quizpress_quiz_meta( $product ) {
		if ( empty( $_POST['_linked_quizpress_quiz'] ) ) {
			return;
		}

		$quiz_id  = absint( $_POST['_linked_quizpress_quiz'] );
		$product_id = absint( $product->get_id() );

		if ( ! empty( $_POST['_quizpress_product'] ) ) {
			// Paid course
			$product->update_meta_data( '_linked_quizpress_quiz', $quiz_id );
			$symbol = function_exists( 'get_woocommerce_currency_symbol' )
			? html_entity_decode(
				get_woocommerce_currency_symbol(),
				ENT_HTML5,
				'UTF-8'
			)
			: '';
			update_post_meta( $quiz_id, 'quizpress_quiz_product_id', $product_id );
			update_post_meta( $quiz_id, 'quizpress_quiz_product_type', 'paid' );
			update_post_meta( $quiz_id, 'quizpress_quiz_sale_price', $product->get_sale_price() );
			update_post_meta( $quiz_id, 'quizpress_quiz_regular_price', $product->get_regular_price() );
			update_post_meta( $quiz_id, 'quizpress_quiz_product_currency', $symbol );
		} else {
			// Free course
			update_post_meta( $quiz_id, 'quizpress_quiz_product_id', 0 );
			update_post_meta( $quiz_id, 'quizpress_quiz_product', 'free' );
		}
	}

	public function add_quizpress_type_in_wc_product( $types ) {
		$types['quizpress_product'] = array(
			'id'            => '_quizpress_product',
			'wrapper_class' => 'show_if_simple',
			'label'         => __( 'For QuizPress', 'quizpress' ),
			'description'   => __( 'This checkmark ensure that you will sell a specific quiz via this product.', 'quizpress' ),
			'default'       => 'no',
		);
		return $types;
	}

	public function save_wc_product_meta( $post_ID ) {
		$is_quizpress_product = sanitize_text_field( ( isset( $_POST['_quizpress_product'] ) ? $_POST['_quizpress_product'] : '' ) ); // phpcs:ignore input var ok, CSRF ok.
		if ( 'on' === $is_quizpress_product ) {
			update_post_meta( $post_ID, '_quizpress_product', 'yes' );
		} else {
			delete_post_meta( $post_ID, '_quizpress_product' );
		}
	}

	public function update_product_meta( $post ) {
		$product_id = (int) get_post_meta( $post->ID, 'quizpress_quiz_product_id', true );
		if ( $product_id ) {
			update_post_meta( $product_id, '_virtual', 'yes' );
			update_post_meta( $product_id, '_quizpress_product', 'yes' );
		}
	}

	public function quizpress_clear_quiz_product_relation( $product_id ) {
		// Get all quizzes that use this product
		$args = [
			'post_type'  => 'quizpress_quiz',
			'meta_key'   => 'quizpress_quiz_product_id',
			'meta_value' => $product_id,
			'fields'     => 'ids',
			'posts_per_page' => -1
		];

		$quizzes = get_posts( $args );

		if ( ! empty( $quizzes ) ) {
			foreach ( $quizzes as $quiz_id ) {
				update_post_meta( $quiz_id, 'quizpress_quiz_product_id', 0 );
				update_post_meta( $quiz_id, 'quizpress_quiz_product_type', 'free' );
			}
		}
	}

}