<?php

use EasyContentManager\Features\RegisterFields;
use EasyContentManager\Utils\Helper;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

class Hooks {

	private function __construct() {
		add_action( 'easy_content_manager_loaded', [ $this, 'on_ecm_loaded' ], 20 );
		add_action( 'init', [ $this, 'register_post_meta' ] );
		add_action( 'init', [ $this, 'register_term_meta' ] );
		add_action( 'user_new_form', [ $this, 'load_user_app_template' ] );
		add_action( 'edit_user_profile', [ $this, 'load_user_app_template' ] );
		add_action( 'show_user_profile', [ $this, 'load_user_app_template' ] );
		add_action( 'wp_footer', [ $this, 'ecm_add_react_wrap' ] );
		add_action( 'user_register', [ $this, 'save_ecm_user_meta_fields' ] );
		add_action( 'personal_options_update', [ $this, 'save_ecm_user_meta_fields' ] );
		add_action( 'edit_user_profile_update', [ $this, 'save_ecm_user_meta_fields' ] );
	}

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

	public function on_ecm_loaded() {
		$cached_fields = array_merge(
			get_transient( 'ecm_cached_prepared_custom_fields' ) ? get_transient( 'ecm_cached_prepared_custom_fields' ) : [],
			get_transient( 'ecm_cached_prepared_field_groups' ) ? get_transient( 'ecm_cached_prepared_field_groups' ) : []
		);

		$local_post_type = ecm_get_json_from_files( ecm_get_plugins_post_type_path() );

		$theme_post_type = [];
		if ( Helper::has_theme_support() ) {
			$theme_post_type = ecm_load_json_files_from_folders( [ Helper::has_theme_support() . '/post-types' ] );
		}

		$all_fields = array_merge( $cached_fields, RegisterFields::prepare_field_for_register( array_merge( $local_post_type, $theme_post_type ), true ) );

		if ( ! empty( $all_fields ) ) {
			Helper::build_field_registry_cache( $all_fields );
		}
	}

	public function register_post_meta() {
		$items = get_posts( [
			'post_type'      => Helper::ECM_POST_TYPE_NAME,
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'fields'         => 'ids',
			'no_found_rows'  => true,
		] );

		if ( empty( $items ) ) {
			return;
		}

		foreach ( $items as $post_id ) {
			$content = maybe_unserialize( get_post_field( 'post_content', $post_id ) );
			register_post_meta(
				$content['post_slug'],
				'ecm_priority',
				[
					'type'              => 'integer',
					'single'            => true,
					'default'           => 0,
					'sanitize_callback' => 'absint',
					'auth_callback'     => function () {
						return current_user_can( 'edit_posts' );
					},
					'show_in_rest'      => true,
				]
			);
		}
	}

	public function register_term_meta() {
		$taxonomies = get_taxonomies( [ 'public' => true ], 'names' );

		foreach ( $taxonomies as $taxonomy ) {
			register_term_meta(
				$taxonomy,
				'term_priority',
				[
					'type'              => 'integer',
					'description'       => __( 'Term display priority/order', 'easy-content-manager' ),
					'single'            => true,
					'sanitize_callback' => 'absint',
					'show_in_rest'      => true,
					'default'           => 0,
				]
			);
		}
	}

	public function load_user_app_template() {
		Helper::get_template( 'admin/users/app.php' );
	}

	public function ecm_add_react_wrap() {
		echo '<div id="ecm-frontend-react-wrap" class="ecm-frontend-react-wrap"></div>';
	}

	public function save_ecm_user_meta_fields( $user_id ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		foreach ( $_POST as $key => $value ) {
			if ( strpos( $key, 'meta_' ) === 0 ) {
				$meta_key = str_replace( 'meta_', '', $key );
				
				$meta_value = $this->sanitize_meta_value( $value );
				
				update_user_meta( $user_id, $meta_key, $meta_value );
			}
		}
	}

	/**
	 * Recursively sanitize meta value based on its type
	 *
	 * @param mixed $value The value to sanitize
	 * @return mixed Sanitized value
	 */
	private function sanitize_meta_value( $value ) {
		if ( is_array( $value ) ) {
			return array_map( [ $this, 'sanitize_meta_value' ], $value );
		}
		
		if ( is_bool( $value ) ) {
			return (bool) $value;
		}
		
		if ( is_numeric( $value ) ) {
			if ( strpos( $value, '.' ) !== false ) {
				return (float) $value;
			}
			return (int) $value;
		}
		
		if ( is_null( $value ) ) {
			return null;
		}

		if ( is_object( $value ) ) {
			return $this->sanitize_meta_value( (array) $value );
		}
		
		return sanitize_text_field( $value );
	}

}

Hooks::get_instance();

