<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://immowp.fr
 * @since      1.0.0
 *
 * @package    Immowp_Gestion_Immobiliere
 * @subpackage Immowp_Gestion_Immobiliere/admin
 */

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

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Immowp_Gestion_Immobiliere
 * @subpackage Immowp_Gestion_Immobiliere/admin
 * @author     ImmoWP <contact@immowp.fr>
 */
class Immowp_Gestion_Immobiliere_Admin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string $plugin_name       The name of this plugin.
	 * @param      string $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version     = $version;
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Immowp_Gestion_Immobiliere_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Immowp_Gestion_Immobiliere_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		wp_enqueue_style( $this->plugin_name, esc_url( plugin_dir_url( __FILE__ ) . 'css/immowp-gestion-immobiliere-admin.css' ), array(), '1.0.3', 'all' );
		
		// Enqueue Extensions Pro CSS only on the specific page
		$screen = get_current_screen();
		if ( $screen && strpos( $screen->id, 'immowp-extensions-pro' ) !== false ) {
			wp_enqueue_style( $this->plugin_name . '-extensions-pro', esc_url( plugin_dir_url( __FILE__ ) . 'css/immowp-extensions-pro.css' ), array(), $this->version, 'all' );
		}
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Immowp_Gestion_Immobiliere_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Immowp_Gestion_Immobiliere_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */

		// WordPress media uploader scripts
		if ( ! did_action( 'wp_enqueue_media' ) ) {
			wp_enqueue_media();
		}

		wp_enqueue_script( $this->plugin_name, esc_url( plugin_dir_url( __FILE__ ) . 'js/immowp-gestion-immobiliere-admin.js' ), array( 'jquery' ), '9.2.6', false );
	}

	// Registers the custom post type for Gestion Immobilière listings.
	public function register_post_type() {

		$immowp_archive_slug            = get_option( 'immowp_archive_slug' );
		$immowp_button_activate_archive = get_option( 'immowp_button_activate_archive' );

		$cpt_name = 'immowp_gestion_immo';

		$labels = array(
			'name'               => 'Gestion Immobilière',
			'singular_name'      => 'Gestion Immo',
			'add_new_item'       => 'Ajouter un bien',
			'edit_item'          => 'Editer un bien',
			'new_item'           => 'Nouveau bien',
			'view_item'          => 'Voir le bien',
			'search_items'       => 'Rechercher un bien',
			'not_found'          => 'Aucun bien trouvé',
			'not_found_in_trash' => 'Aucun bien trouvé dans la corbeille',
			'parent_item_colon'  => '',
			'menu_name'          => 'Gestion Immo',
			'all_items'          => 'Tous les biens',
			'add_new'            => 'Ajouter un bien',
		);

		$args = array(
			'labels'              => $labels,
			'description'         => 'bien',
			'public'              => true,
			'show_ui'             => true,
			'show_in_menu'        => true,
			'show_in_nav_menus'   => true,
			'publicly_queryable'  => true,
			'exclude_from_search' => true,
			'rewrite'             => array(
				'slug'       => ( empty( $immowp_archive_slug ) ? 'annonce' : $immowp_archive_slug ),
				'with_front' => false,
			),
			'capability_type'     => 'post',
			'has_archive'         => ( $immowp_button_activate_archive == 'yes' ? true : false ),
			'hierarchical'        => false,
			'menu_position'       => 3,
			'query_var'           => $cpt_name,
			'menu_icon'           => 'dashicons-admin-home',
			'supports'            => array( 'title', 'thumbnail', 'editor' ),
		);

		register_post_type( $cpt_name, $args );

		// Register the taxonomies for Gestion Immobilière listings.
		register_taxonomy(
			'immowp_type',
			$cpt_name,
			array(
				'label'        => 'Types',
				'labels'       => array(
					'name'          => 'Type',
					'singular_name' => 'Type',
					'all_items'     => 'Tous les types',
					'edit_item'     => 'Éditer le type',
					'view_item'     => 'Voir le type',
					'update_item'   => 'Mettre à jour le type',
					'add_new_item'  => 'Ajouter un type',
					'new_item_name' => 'Nouveau type',
					'search_items'  => 'Rechercher parmi les types',
					'popular_items' => 'Types les plus utilisés',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_type', $cpt_name );

		register_taxonomy(
			'immowp_localisation',
			$cpt_name,
			array(
				'label'        => 'Localisation',
				'labels'       => array(
					'name'          => 'Localisation',
					'singular_name' => 'Localisation',
					'all_items'     => 'Toutes les localisations',
					'edit_item'     => 'Éditer la localisation',
					'view_item'     => 'Voir la localisation',
					'update_item'   => 'Mettre à jour la localisation',
					'add_new_item'  => 'Ajouter une localisation',
					'new_item_name' => 'Nouvelle localisation',
					'search_items'  => 'Rechercher parmi les localisations',
					'popular_items' => 'Localisations les plus utilisées',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_localisation', $cpt_name );

		register_taxonomy(
			'immowp_offre',
			$cpt_name,
			array(
				'label'        => 'Offre',
				'labels'       => array(
					'name'          => 'Offre',
					'singular_name' => 'Offre',
					'all_items'     => 'Toutes les offres',
					'edit_item'     => "Éditer l'offre",
					'view_item'     => "Voir l'offre",
					'update_item'   => "Mettre à jour l'offre",
					'add_new_item'  => 'Ajouter une offre',
					'new_item_name' => 'Nouvelle offre',
					'search_items'  => 'Rechercher parmi les offres',
					'popular_items' => 'Offres les plus utilisées',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_offre', $cpt_name );

		register_taxonomy(
			'immowp_caracteristiques',
			$cpt_name,
			array(
				'label'        => 'Caractéristiques',
				'labels'       => array(
					'name'          => 'Caractéristiques',
					'singular_name' => 'Caractéristique',
					'all_items'     => 'Toutes les caractéristique',
					'edit_item'     => 'Éditer la caractéristique',
					'view_item'     => 'Voir la caractéristique',
					'update_item'   => 'Mettre à jour la caractéristique',
					'add_new_item'  => 'Ajouter une caractéristique',
					'new_item_name' => 'Nouvelle caractéristique',
					'search_items'  => 'Rechercher parmi les caractéristiques',
					'popular_items' => 'Caractéristiques les plus utilisées',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_caracteristiques', $cpt_name );

		register_taxonomy(
			'immowp_agences',
			$cpt_name,
			array(
				'label'        => 'Agences',
				'labels'       => array(
					'name'          => 'Agences',
					'singular_name' => 'Agence',
					'all_items'     => 'Toutes les agences',
					'edit_item'     => "Éditer l'agence",
					'view_item'     => "Voir l'agence",
					'update_item'   => "Mettre à jour l'agence",
					'add_new_item'  => 'Ajouter une agence',
					'new_item_name' => 'Nouvelle agence',
					'search_items'  => 'Rechercher parmi les agences',
					'popular_items' => 'Agences les plus utilisées',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_agences', $cpt_name );

		register_taxonomy(
			'immowp_agent',
			$cpt_name,
			array(
				'label'        => 'Agents',
				'labels'       => array(
					'name'          => 'Agent',
					'singular_name' => 'Agent',
					'all_items'     => 'Tous les agents',
					'edit_item'     => 'Éditer le agent',
					'view_item'     => 'Voir le agent',
					'update_item'   => 'Mettre à jour le agent',
					'add_new_item'  => 'Ajouter un agent',
					'new_item_name' => 'Nouveau agent',
					'search_items'  => 'Rechercher parmi les agents',
					'popular_items' => 'Agents les plus utilisés',
				),
				'hierarchical' => true,
				'show_in_rest' => true,
			)
		);
		register_taxonomy_for_object_type( 'immowp_agent', $cpt_name );
	}


	// Registers the custom single page template for Gestion Immobilière listings.
	public function register_single_template( $single_template ) {
		global $post;

		if ( 'immowp_gestion_immo' === $post->post_type ) {
			$single_template = plugin_dir_path( __DIR__ ) . 'public/partials/single/single-real-estate.php';
		}

		return $single_template;
	}

	// Fix rewrite rules & taxonomy templates
	public function taxonomy_rewrite_fix( $wp_rewrite ) {
		$r = array();

		foreach ( $wp_rewrite->rules as $k => $v ) {
			// Apply the replacement for each taxonomy term
			$v = str_replace( 'immowp_offre=$matches[1]&paged=', 'immowp_offre=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_type=$matches[1]&paged=', 'immowp_type=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_agent=$matches[1]&paged=', 'immowp_agent=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_agences=$matches[1]&paged=', 'immowp_agences=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_region=$matches[1]&paged=', 'immowp_region=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_departement=$matches[1]&paged=', 'immowp_departement=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_caracteristiques=$matches[1]&paged=', 'immowp_caracteristiques=$matches[1]&page=', $v );
			$v = str_replace( 'immowp_localisation=$matches[1]&paged=', 'immowp_localisation=$matches[1]&page=', $v );

			// Add the modified rule back to the rules array
			$r[ $k ] = $v;
		}

		// Update the rewrite rules with the modified rules
		$wp_rewrite->rules = $r;
	}

	public function call_taxonomy_template_from_directory() {
		$taxonomy_slug = sanitize_key( get_query_var( 'taxonomy' ) );
		if ( $taxonomy_slug ) {
			$filename_slug = str_replace( '_', '-', $taxonomy_slug ); // Convert underscores to hyphens for filename
			$archive       = IMMOWP_PLUGIN_FOLDER . '/public/partials/taxonomy/taxonomy-' . $filename_slug . '.php';
		} else {
			// Handle case where taxonomy slug is not found or invalid, perhaps load a default or return.
			return;
		}
		load_template( $archive );
	}

	public function show_full_query() {
		// global $wp_query;
		// error_log( print_r( $wp_query->query_vars, true ) );
	}



	// Function to manage the columns of the "Gestion Immobilière Listing" post type
	public function manage_columns( $columns ) {

		// Add a new column for the thumbnail
		$columns['thumbnail']    = 'Thumbnail';
		$columns['offre']        = __( 'Offre', 'immowp-gestion-immobiliere' );
		$columns['type']         = __( 'Type', 'immowp-gestion-immobiliere' );
		$columns['localisation'] = __( 'Localisation', 'immowp-gestion-immobiliere' );

		// Remove the date column
		unset( $columns['date'] );
		unset( $columns['comments'] );
		unset( $columns['author'] );

		return $columns;
	}

	// Function to show the thumbnail and post meta values in the "Gestion Immobilière Listing" post type table
	public function custom_columns( $column, $post_id ) {
		switch ( $column ) {
			case 'thumbnail':
				// Get the post thumbnail
				$thumbnail_id = get_post_thumbnail_id( $post_id );

				// Output the post thumbnail
				if ( $thumbnail_id ) {
					echo wp_get_attachment_image( $thumbnail_id, array( 100, 100 ), false, array( 'style' => 'width:100px;height:100px;object-fit:cover;' ) );
				} else {
					echo '—';
				}
				break;

			case 'offre':
				$immowp_offre = get_the_terms( $post_id, 'immowp_offre' );
				$types     = array();
				if ( $immowp_offre ) {
					foreach ( $immowp_offre as $term ) {
						$types[] = esc_html( $term->name );
					}
				}
				echo esc_html( implode( ',', $types ) );
				break;
			case 'type':
				$immowp_type = get_the_terms( $post_id, 'immowp_type' );
				$types    = array();
				if ( $immowp_type ) {
					foreach ( $immowp_type as $term ) {
						$types[] = esc_html( $term->name );
					}
				}
				echo esc_html( implode( ',', $types ) );
				break;
			case 'localisation':
				$immowp_localisation = get_the_terms( $post_id, 'immowp_localisation' );
				$types            = array();
				if ( $immowp_localisation ) {
					foreach ( $immowp_localisation as $term ) {
						$types[] = esc_html( $term->name );
					}
				}
				echo esc_html( implode( ',', $types ) );
				break;
			default:
				// Output the post meta value for the other columns
				$meta_value = get_post_meta( $post_id, $column, true );
				if ( $meta_value ) {
					echo esc_html( $meta_value );
				} else {
					echo '—';
				}
				break;
		}
	}

	// shortcode
	public function immowp_property( $atts, $content = null, $tag = '' ) {

		ob_start();

		// Enqueue Assets (Archive might need all)
		wp_enqueue_script( $this->plugin_name );
		wp_enqueue_style( $this->plugin_name );

		$a = shortcode_atts(
			array(
				'offre'            => '',
				'type'             => '',
				'localisation'     => '',
				'agence'           => '',
				'agent'            => '',
				'caracteristiques' => '',
				'departement'      => '',
				'region'           => '',
				'post_key'         => '',
				'post_meta'        => '',
			),
			$atts
		);

		$archive = plugin_dir_path( __DIR__ ) . 'public/partials/archive/archive-real-estate.php';

		include $archive;

		$content = ob_get_clean();

		return $content;
	}

	public function create_custom_submenu() {
		add_submenu_page(
			'edit.php?post_type=immowp_gestion_immo',        // Parent slug
			'Réglages',              // Page title
			'Réglages',              // Menu title
			'manage_options',              // Capability required to access the submenu
			'immowp-settings',              // Menu slug
			array( $this, 'render_immowp_settings_page' )    // Callback function to render the submenu page
		);

		add_submenu_page(
			'edit.php?post_type=immowp_gestion_immo',        // Parent slug
			'Extensions Pro',              // Page title
			'⭐ Extensions Pro',              // Menu title with star icon
			'manage_options',              // Capability required to access the submenu
			'immowp-extensions-pro',              // Menu slug
			array( $this, 'render_immowp_extensions_pro_page' )    // Callback function to render the submenu page
		);
	}

	public function redirect_if_deleted_custom_post_type() {
		$immowp_redirect_page = get_option( 'immowp_redirect_page' );

		if ( is_404() && ! empty( $immowp_redirect_page ) ) {
			global $wp_query;
			if ( isset( $wp_query->query_vars['post_type'] ) && 'immowp_gestion_immo' === $wp_query->query_vars['post_type'] ) { // Yoda condition
				wp_safe_redirect( get_permalink( absint( $immowp_redirect_page ) ), 301 ); // Sanitize redirect page ID
				exit();
			}
		}
	}

	public function render_immowp_settings_page() {
		include plugin_dir_path( __FILE__ ) . 'class-immowp-gestion-immobiliere-settings.php';
	}

	public function render_immowp_extensions_pro_page() {
		include plugin_dir_path( __FILE__ ) . 'partials/immowp-gestion-immobiliere-extensions-pro.php';
	}

	public function add_immowp_promotional_banner() {
		$screen = get_current_screen();
		
		// Check if user has dismissed the banner
		$dismissed = get_user_meta( get_current_user_id(), 'immowp_promo_banner_dismissed', true );
		if ( $dismissed ) {
			return;
		}
		
		// Show banner on ImmoWP admin pages (but not on Extensions Pro page)
		if ( $screen && ( 
			$screen->post_type === 'immowp_gestion_immo' || 
			( strpos( $screen->id, 'immowp_gestion_immo' ) !== false && $screen->id !== 'immowp_gestion_immo_page_immowp-extensions-pro' ) ||
			$screen->id === 'immowp_gestion_immo_page_immowp-settings'
		) ) {
			$nonce = wp_create_nonce( 'dismiss_notice_nonce' );
			echo '<div class="immowp-promo-banner notice is-dismissible" data-notice="immowp-promo">
				<input type="hidden" id="immowp_promo_nonce" value="' . esc_attr( $nonce ) . '">
				<div class="immowp-promo-content">
					<div class="immowp-promo-icon">🔧</div>
					<div class="immowp-promo-text">
						<strong>' . esc_html__( 'Besoin de connecter votre site à votre logiciel métier ?', 'immowp-gestion-immobiliere' ) . '</strong>
						<span>' . esc_html__( 'ImmoWP fait la liaison entre votre logiciel de multidiffusion d\'annonces immobilières (Hektor, Immofacile, Ubiflow, Apimo, ...) et votre site WordPress afin de vous éviter une duplication fastidieuse. Compatible avec tous les thèmes WordPress.', 'immowp-gestion-immobiliere' ) . '</span>
					</div>
					<div class="immowp-promo-action">
						<a href="https://www.immowp.fr/" target="_blank" class="immowp-promo-button">
							' . esc_html__( 'Découvrir ImmoWP', 'immowp-gestion-immobiliere' ) . '
						</a>
					</div>
				</div>
			</div>';
		}
	}

	public function handle_banner_dismissal() {
		if ( isset( $_POST['notice'] ) && $_POST['notice'] === 'immowp-promo' ) {
			check_ajax_referer( 'dismiss_notice_nonce', 'nonce' );
			update_user_meta( get_current_user_id(), 'immowp_promo_banner_dismissed', true );
			wp_die();
		}
	}
}
