<?php
/**
 * Create metabox for custom post types.
 *
 * @link       https://codingfix.com
 * @since      1.0.0
 *
 * @package    Instalist
 * @subpackage Instalist/includes
 */

/**
 * Create metabox for custom post types.
 *
 * Add the metabox for custom post types
 *
 * @package    Instalist
 * @subpackage Instalist/includes
 * @author     Marco Gasi <info@codingfix.com>
 */
class Pluginer_Metabox {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 */
	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'plgnr_add_plugin_list_metabox' ) );
		add_action( 'save_post', array( $this, 'plgnr_save_plugin_list_metabox' ) );
	}

	/**
	 * Add metaboxes for Plugin List CPT.
	 *
	 * @since    1.0.0
	 */
	public function plgnr_add_plugin_list_metabox() {
		add_meta_box(
			'pluginer-plugin-list-metabox',
			__( 'Plugins', 'pluginer' ),
			array( $this, 'plgnr_render_plugin_list_metabox' ),
			'plgnr_plugin_list',
			'normal',
			'high'
		);
		add_meta_box(
			'plgnr_plugin_list_notes',
			__( 'Notes', 'pluginer' ),
			array( $this, 'plgnr_render_notes_meta_box' ),
			'plgnr_plugin_list',
			'normal',
			'high'
		);
	}

	/**
	 * Renders the main metabox for Plugin List CPT.
	 *
	 * @param object $post The current post.
	 * @since    1.0.0
	 */
	public function plgnr_render_plugin_list_metabox( $post ) {
		wp_nonce_field( 'plgnr_plugin_list_metabox_nonce', 'plgnr_plugin_list_metabox_nonce' );
		include_once plugin_dir_path( __DIR__ ) . 'admin/partials/create-plugin-list.php';
	}

	/**
	 * Renders the notes metabox for Plugin List CPT.
	 *
	 * @param object $post The current post.
	 * @since    1.0.0
	 */
	public function plgnr_render_notes_meta_box( $post ) {
		wp_nonce_field( 'plgnr_plugin_list_notes_nonce', 'plgnr_plugin_list_notes_nonce' );
		include_once plugin_dir_path( __DIR__ ) . 'admin/partials/add-list-notes.php';
	}

	/**
	 * Save the metaboxes for Plugin List CPT.
	 *
	 * @param int $post_id The current post.
	 * @since    1.0.0
	 */
	public function plgnr_save_plugin_list_metabox( $post_id ) {
		// Verifica nonce per il plugin list metabox.
		if ( ! isset( $_POST['plgnr_plugin_list_metabox_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['plgnr_plugin_list_metabox_nonce'] ) ), 'plgnr_plugin_list_metabox_nonce' ) ) {
			return;
		}

		// Verifica nonce per il notes metabox.
		if ( ! isset( $_POST['plgnr_plugin_list_notes_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['plgnr_plugin_list_notes_nonce'] ) ), 'plgnr_plugin_list_notes_nonce' ) ) {
			return;
		}

		// Controllo se è un salvataggio automatico.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Verifica permessi.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Controlla se esiste già una lista primaria.
		$primary_exists = get_posts(
			array(
				'post_type'      => 'plgnr_plugin_list',
				'posts_per_page' => 1,
				'meta_key'       => '_is_primary_list',
				'meta_value'     => '1',
				'fields'         => 'ids',
			)
		);

		// Salva i plugin.
		if ( isset( $_POST['plugin_name'] ) && isset( $_POST['plugin_slug'] ) && isset( $_POST['plugin_icon'] ) ) {
			$names = array_map( 'sanitize_text_field', wp_unslash( $_POST['plugin_name'] ) );
			$slugs = array_map( 'sanitize_text_field', wp_unslash( $_POST['plugin_slug'] ) );
			$icons = array_map( 'sanitize_text_field', wp_unslash( $_POST['plugin_icon'] ) );
			update_post_meta( $post_id, '_plgnr_plugin_names', $names );
			update_post_meta( $post_id, '_plgnr_plugin_slugs', $slugs );
			update_post_meta( $post_id, '_plgnr_plugin_icons', $icons );
			if ( empty( $primary_exists ) ) {
				// Nessuna lista primaria, quindi questo diventa la prima.
				update_post_meta( $post_id, '_is_primary_list', '1' );
			}
			// Crea un array per raccogliere tutti i plugin richiesti.
			$all_required_plugins = array();

			foreach ( $slugs as $plugin_slug ) {
				$required_plugins = Pluginer_Helper::find_required_plugins( $plugin_slug );
				// Accumula i plugin richiesti.
				$all_required_plugins = array_merge( $all_required_plugins, $required_plugins );
			}
			update_post_meta( $post_id, '_plgnr_plugin_required_plugins', $all_required_plugins );
		} else {
			delete_post_meta( $post_id, '_plgnr_plugin_names' );
			delete_post_meta( $post_id, '_plgnr_plugin_slugs' );
			delete_post_meta( $post_id, '_plgnr_plugin_icons' );
			delete_post_meta( $post_id, '_is_primary_list' );
			delete_post_meta( $post_id, '_plgnr_plugin_required_plugins' );
		}

		// Salva i dati della metabox Notes.
		if ( isset( $_POST['plugin_list_notes'] ) ) {
			$notes = sanitize_textarea_field( wp_unslash( $_POST['plugin_list_notes'] ) );
			update_post_meta( $post_id, '_plgnr_plugin_list_notes', $notes );
		} else {
			delete_post_meta( $post_id, '_plgnr_plugin_list_notes' );
		}

		// Imposta un transient per indicare che il post è stato salvato.
		set_transient( 'plgnr_post_saved_' . $post_id, true ); // non scade mai.
	}
}
