<?php

namespace HulkPlugins\Woo\ProductDescriptionInLoop\Admin\Controllers;

use HulkPlugins\Woo\ProductDescriptionInLoop\Core\BaseController;
use HulkPlugins\Woo\ProductDescriptionInLoop\Core\SingletonTrait;

defined( 'ABSPATH' ) || exit;

class ProductLoopDescMetaBoxController extends BaseController {

	use SingletonTrait;

	private string $post_type = 'product';

	public function init_hooks(): void {
		add_action( 'add_meta_boxes', [ $this, 'add_product_loop_description_meta_box' ] );
		add_action( "save_post_$this->post_type", [ $this, 'save_product_loop_description_meta' ], 10, 2 );
	}

	/**
	 * Add a loop description meta box
	 * @return void
	 */
	public function add_product_loop_description_meta_box(): void {
		add_meta_box(
			'hulk_woo_pdil_loop_desc',
			esc_attr__( 'Product loop description', 'product-description-in-loop-for-woocommerce' ),
			[ $this, 'render_product_description_meta_box' ],
			'product',
			'normal'
		);
	}

	/**
	 * Render loop description meta box
	 *
	 * @param $post
	 *
	 * @return void
	 */
	public function render_product_description_meta_box( $post ): void {

		$settings = [
			'textarea_name' => 'hulk_woo_pdil_loop_desc',
			'quicktags'     => [ 'buttons' => 'em,strong,link' ],
			'tinymce'       => [
				'theme_advanced_buttons1' => 'bold,italic,strikethrough,separator,bullist,numlist,separator,blockquote,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator,undo,redo,separator',
				'theme_advanced_buttons2' => '',
			],
			'editor_css'    => /** @lang text */
			'<style>#wp-hulk-woo-pdil-loop-desc-editor-container .wp-editor-area{height:175px; width:100%;}</style>',
		];

		$value = get_post_meta( $post->ID, 'hulk_woo_pdil_loop_desc', true );

		wp_editor(
			htmlspecialchars_decode( $value, ENT_QUOTES ),
			'hulk-woo-pdil-loop-desc',
			apply_filters( 'hulk_woo_pdil_product_loop_description_editor_settings', $settings )
		);

		wp_nonce_field( 'hulk_woo_pdil_save_loop_desc', 'hulk_woo_pdil_loop_desc_nonce' );
	}

	/**
	 *  Save the field value using woocommerce_process_product_meta
	 *
	 * @param $post_id
	 */
	public function save_product_loop_description_meta( $post_id ): void {

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if (
			! isset( $_POST['hulk_woo_pdil_loop_desc_nonce'] ) ||
			! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hulk_woo_pdil_loop_desc_nonce'] ) ), 'hulk_woo_pdil_save_loop_desc' )
		) {
			return;
		}

		// Check if the field is set in the $_POST data
		if ( isset( $_POST['hulk_woo_pdil_loop_desc'] ) ) {
			// Sanitize and update the meta value
			$value = wp_kses_post( wp_unslash( $_POST['hulk_woo_pdil_loop_desc'] ) );
			update_post_meta( $post_id, 'hulk_woo_pdil_loop_desc', $value );
		}
	}
}
