<?php

/**
 * Plugin Name:       Dynamiques Focal Point
 * Description:       Un plugin pour ajouter un point focal à l'image de la thumbnail
 * Author:            Deligraph
 * Text Domain:       dynamiques-thumbnail-focal-point
 */

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

// Enregistrer les métadonnées pour les post types "revues" et "articles"
add_action('init', function () {
	$supported_post_types = ['revues', 'articles'];

	foreach ($supported_post_types as $post_type) {
		register_post_meta($post_type, 'thumbnail_focal_point', [
			'show_in_rest' => [
				'schema' => [
					'type' => 'object',
					'properties' => [
						'x' => ['type' => 'number'],
						'y' => ['type' => 'number'],
					],
				],
			],
			'single' => true,
			'type' => 'object',
			'auth_callback' => function (): bool {
				return current_user_can('edit_posts');
			}
		]);
	}
});

/**
 * Obtenir le focal point d'un post
 * 
 * @param int|null $post_id ID du post (null pour le post courant)
 * @return array Tableau avec 'x' et 'y' (valeurs entre 0 et 1)
 */
function get_thumbnail_focal_point($post_id = null)
{
	if (!$post_id) {
		$post_id = get_the_ID();
	}

	$focal_point = get_post_meta($post_id, 'thumbnail_focal_point', true);

	// Valeurs par défaut (centre de l'image)
	if (!$focal_point || !is_array($focal_point)) {
		return ['x' => 0.5, 'y' => 0.5];
	}

	return [
		'x' => isset($focal_point['x']) ? $focal_point['x'] : 0.5,
		'y' => isset($focal_point['y']) ? $focal_point['y'] : 0.5
	];
}

/**
 * Obtenir le focal point formaté pour CSS
 * 
 * @param int|null $post_id ID du post (null pour le post courant)
 * @return string Format "50% 50%" pour object-position ou background-position
 */
function get_thumbnail_focal_point_css($post_id = null)
{
	$focal_point = get_thumbnail_focal_point($post_id);
	$x_percent = ($focal_point['x'] * 100);
	$y_percent = ($focal_point['y'] * 100);

	return $x_percent . '% ' . $y_percent . '%';
}

// Enqueue pour l'éditeur Gutenberg (pour "revues" et "articles")
add_action('enqueue_block_editor_assets', function () {
	$screen = get_current_screen();
	$supported_post_types = ['revues', 'articles'];

	if (!$screen || !in_array($screen->post_type, $supported_post_types)) {
		return;
	}

	$asset_file = include(plugin_dir_path(__FILE__) . 'build/index.asset.php');

	wp_enqueue_script(
		'thumbnail-focal-point-panel',
		plugin_dir_url(__FILE__) . 'build/index.js',
		$asset_file['dependencies'],
		$asset_file['version'],
		true
	);

	// Charger les styles personnalisés pour Gutenberg
	wp_enqueue_style(
		'thumbnail-focal-point-gutenberg-css',
		plugin_dir_url(__FILE__) . 'assets/focal-point-gutenberg.css',
		['wp-components'],
		'1.0.0'
	);

	// Optionnel : Enqueue les styles si nécessaire
	if (file_exists(plugin_dir_path(__FILE__) . 'build/index.css')) {
		wp_enqueue_style(
			'thumbnail-focal-point-panel-style',
			plugin_dir_url(__FILE__) . 'build/index.css',
			[],
			$asset_file['version']
		);
	}
});

// Enqueue pour l'éditeur classique (inline dans la meta box de thumbnail, pour "revues" et "articles")
add_action('admin_enqueue_scripts', function ($hook) {
	// Seulement sur les pages d'édition de post
	if (!in_array($hook, ['post.php', 'post-new.php'])) {
		return;
	}

	global $post;
	if (!$post) {
		return;
	}

	// Vérifier que c'est un post type supporté
	$supported_post_types = ['revues', 'articles'];
	$post_type = get_post_type($post);
	if (!in_array($post_type, $supported_post_types)) {
		return;
	}

	// Charger le fichier asset pour les dépendances
	$asset_file = include(plugin_dir_path(__FILE__) . 'build/focal-point-inline.asset.php');

	wp_enqueue_script(
		'thumbnail-focal-point-inline',
		plugin_dir_url(__FILE__) . 'build/focal-point-inline.js',
		$asset_file['dependencies'],
		$asset_file['version'],
		true
	);

	// Charger les styles des composants WordPress
	wp_enqueue_style('wp-components');

	// Charger les styles personnalisés
	wp_enqueue_style(
		'thumbnail-focal-point-inline-css',
		plugin_dir_url(__FILE__) . 'assets/focal-point-inline.css',
		['wp-components'],
		'1.0.0'
	);

	// Passer les données au JavaScript
	$focal_point = get_post_meta($post->ID, 'thumbnail_focal_point', true);
	$x = isset($focal_point['x']) ? $focal_point['x'] : 0.5;
	$y = isset($focal_point['y']) ? $focal_point['y'] : 0.5;

	$thumbnail_id = get_post_thumbnail_id($post->ID);
	$thumbnail_url = $thumbnail_id ? wp_get_attachment_image_url($thumbnail_id, 'large') : '';

	wp_localize_script('thumbnail-focal-point-inline', 'thumbnailFocalPointData', [
		'postId' => $post->ID,
		'thumbnailUrl' => $thumbnail_url,
		'focalPointX' => $x,
		'focalPointY' => $y,
		'nonce' => wp_create_nonce('thumbnail_focal_point_save')
	]);
});


// Sauvegarder les données de la meta box
add_action('save_post', function ($post_id) {
	// Vérifications de sécurité
	if (!isset($_POST['thumbnail_focal_point_nonce'])) {
		return;
	}

	if (!wp_verify_nonce($_POST['thumbnail_focal_point_nonce'], 'thumbnail_focal_point_save')) {
		return;
	}

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

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

	// Sauvegarder les données
	if (isset($_POST['thumbnail_focal_point_x']) && isset($_POST['thumbnail_focal_point_y'])) {
		$x = floatval($_POST['thumbnail_focal_point_x']);
		$y = floatval($_POST['thumbnail_focal_point_y']);

		// S'assurer que les valeurs sont entre 0 et 1
		$x = max(0, min(1, $x));
		$y = max(0, min(1, $y));

		update_post_meta($post_id, 'thumbnail_focal_point', [
			'x' => $x,
			'y' => $y
		]);
	}
});
