<?php
/**
 * Plugin Name: WP Reels Gallery Pro
 * Plugin URI: https://tonsite.ma
 * Description: Gérez et affichez des galeries de vidéos Reels avec recadrage d'images et paramètres avancés
 * Version: 3.5.0
 * Author: Tonsite
 * License: GPL v2 or later
 */

// Sécurité : empêcher l'accès direct
if (!defined('ABSPATH')) {
    exit;
}

// Constantes du plugin
define('WPRG_VERSION', '3.5.0');
define('WPRG_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('WPRG_PLUGIN_URL', plugin_dir_url(__FILE__));

// Chargement des fichiers requis
require_once WPRG_PLUGIN_DIR . 'includes/post-type.php';
require_once WPRG_PLUGIN_DIR . 'includes/meta-boxes.php';
require_once WPRG_PLUGIN_DIR . 'includes/shortcode.php';
require_once WPRG_PLUGIN_DIR . 'includes/image-cropper.php';
require_once WPRG_PLUGIN_DIR . 'includes/likes-system.php';
require_once WPRG_PLUGIN_DIR . 'includes/views-system.php';

// Activation du plugin
register_activation_hook(__FILE__, 'wprg_activate');
function wprg_activate() {
    wprg_register_post_type();
    flush_rewrite_rules();
}

// Désactivation du plugin
register_deactivation_hook(__FILE__, 'wprg_deactivate');
function wprg_deactivate() {
    flush_rewrite_rules();
}

// Charger les scripts et styles
add_action('wp_enqueue_scripts', 'wprg_enqueue_scripts');
function wprg_enqueue_scripts() {
    wp_enqueue_style('wprg-styles', WPRG_PLUGIN_URL . 'assets/css/reels-gallery.css', array(), WPRG_VERSION);
    wp_enqueue_script('wprg-scripts', WPRG_PLUGIN_URL . 'assets/js/reels-gallery.js', array('jquery'), WPRG_VERSION, true);
    
    // Script pour les likes
    wp_enqueue_script('wprg-likes', WPRG_PLUGIN_URL . 'assets/js/reels-likes.js', array('jquery'), WPRG_VERSION, true);
    wp_localize_script('wprg-likes', 'wprg_likes', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wprg_likes_nonce'),
        'heart_icon' => WPRG_PLUGIN_URL . 'assets/images/heart.svg'
    ));
    
    // Script pour les vues
    wp_enqueue_script('wprg-views', WPRG_PLUGIN_URL . 'assets/js/reels-views.js', array('jquery'), WPRG_VERSION, true);
    wp_localize_script('wprg-views', 'wprg_views', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wprg_views_nonce')
    ));
}

// Charger les scripts admin
add_action('admin_enqueue_scripts', 'wprg_admin_enqueue_scripts');
function wprg_admin_enqueue_scripts($hook) {
    global $post_type;
    
    if ($post_type == 'wprg_reel' && in_array($hook, array('post.php', 'post-new.php'))) {
        // Charger les scripts jQuery UI
        wp_enqueue_script('jquery');
        wp_enqueue_script('jquery-ui-core');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-resizable');
        wp_enqueue_script('jquery-ui-touch-punch');
        
        wp_enqueue_media();
        wp_enqueue_style('wprg-admin-styles', WPRG_PLUGIN_URL . 'assets/css/admin-cropper.css', array(), WPRG_VERSION);
        wp_enqueue_style('wprg-admin-taxonomy', WPRG_PLUGIN_URL . 'assets/css/admin-taxonomy.css', array(), WPRG_VERSION);
        wp_enqueue_script('wprg-cropper', WPRG_PLUGIN_URL . 'assets/js/image-cropper.js', array('jquery', 'jquery-ui-draggable', 'jquery-ui-resizable'), WPRG_VERSION, true);
        
        // Récupérer le nonce pour l'image mise en avant
        $post = get_post();
        $thumbnail_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
        
        wp_localize_script('wprg-cropper', 'wprg_cropper', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('wprg_cropper_nonce'),
            'plugin_url' => WPRG_PLUGIN_URL,
            'thumbnail_nonce' => $thumbnail_nonce
        ));
    }
    
    // Charger les styles pour l'édition des taxonomies
    if ($hook == 'edit-tags.php' || $hook == 'term.php') {
        wp_enqueue_style('wprg-admin-taxonomy', WPRG_PLUGIN_URL . 'assets/css/admin-taxonomy.css', array(), WPRG_VERSION);
    }
    
    // Charger le style admin amélioré pour la liste des reels
    if ($post_type == 'wprg_reel' && $hook == 'edit.php') {
        wp_enqueue_style('wprg-admin-reels', WPRG_PLUGIN_URL . 'assets/css/admin-reels.css', array(), WPRG_VERSION);
    }
}

// Fonction pour vider le cache des thumbnails après recadrage
add_action('wp_ajax_wprg_crop_image', 'wprg_crop_image');
function wprg_crop_image() {
    // Vérifier le nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'wprg_cropper_nonce')) {
        wp_send_json_error('Security check failed');
    }
    
    $post_id = intval($_POST['post_id']);
    $attachment_id = intval($_POST['attachment_id']);
    $crop_data = json_decode(stripslashes($_POST['crop_data']), true);
    
    // Récupérer le chemin de l'image
    $image_path = get_attached_file($attachment_id);
    
    if (!file_exists($image_path)) {
        wp_send_json_error('Image non trouvée');
    }
    
    // Dimensions de recadrage
    $x = intval($crop_data['x']);
    $y = intval($crop_data['y']);
    $width = intval($crop_data['width']);
    $height = intval($crop_data['height']);
    
    // Charger l'image
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $image_editor = wp_get_image_editor($image_path);
    
    if (is_wp_error($image_editor)) {
        wp_send_json_error('Impossible de charger l\'image: ' . $image_editor->get_error_message());
    }
    
    // Recadrer l'image
    $image_editor->crop($x, $y, $width, $height, 1080, 1920);
    
    // Sauvegarder la nouvelle image
    $upload_dir = wp_upload_dir();
    $filename = 'cropped-' . time() . '-' . basename($image_path);
    $cropped_path = $upload_dir['path'] . '/' . $filename;
    
    $saved = $image_editor->save($cropped_path);
    
    if (is_wp_error($saved)) {
        wp_send_json_error('Erreur lors de la sauvegarde');
    }
    
    // Créer une pièce jointe pour l'image recadrée
    $filetype = wp_check_filetype($filename, null);
    
    $attachment = array(
        'post_mime_type' => $filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit',
        'guid'           => $upload_dir['url'] . '/' . $filename
    );
    
    $new_attachment_id = wp_insert_attachment($attachment, $cropped_path, $post_id);
    
    // Générer les métadonnées
    $attach_data = wp_generate_attachment_metadata($new_attachment_id, $cropped_path);
    wp_update_attachment_metadata($new_attachment_id, $attach_data);
    
    // Définir comme image mise en avant
    set_post_thumbnail($post_id, $new_attachment_id);
    
    // Forcer la mise à jour du cache
    clean_post_cache($post_id);
    
    wp_send_json_success(array(
        'thumbnail_url' => wp_get_attachment_url($new_attachment_id),
        'attachment_id' => $new_attachment_id,
        'message' => 'Image recadrée avec succès'
    ));
}

// Ajouter une action AJAX pour récupérer l'URL d'une attachment
add_action('wp_ajax_wprg_get_attachment_url', 'wprg_get_attachment_url');
function wprg_get_attachment_url() {
    // Vérifier le nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'wprg_cropper_nonce')) {
        wp_send_json_error('Security check failed');
    }
    
    $attachment_id = intval($_POST['attachment_id']);
    $url = wp_get_attachment_url($attachment_id);
    
    if ($url) {
        wp_send_json_success(array('url' => $url));
    } else {
        wp_send_json_error('Attachment non trouvée');
    }
}

// Fonction pour extraire l'ID YouTube
function wprg_get_youtube_id($url) {
    $pattern = '/(?:youtube\.com\/(?:shorts\/|watch\?v=)|youtu\.be\/)([^\&\?\/]+)/';
    if (preg_match($pattern, $url, $matches)) {
        return $matches[1];
    }
    return false;
}

// Fonction pour obtenir la miniature YouTube
function wprg_get_youtube_thumbnail($url) {
    $video_id = wprg_get_youtube_id($url);
    if ($video_id) {
        return 'https://img.youtube.com/vi/' . $video_id . '/maxresdefault.jpg';
    }
    return false;
}