<?php
// Ajouter le meta box de recadrage d'image
add_action('add_meta_boxes', 'wprg_add_cropper_meta_box');
function wprg_add_cropper_meta_box() {
    add_meta_box(
        'wprg_image_cropper',
        '📐 Recadrage Image (1080x1920)',
        'wprg_image_cropper_callback',
        'wprg_reel',
        'side',
        'high'
    );
}

// Callback pour le recadrage
function wprg_image_cropper_callback($post) {

    // 🔐 Sécurisation (sans casser le plugin)
    if (!isset($post->ID)) {
        return;
    }

    $post_id = intval($post->ID);

    $thumbnail_id = get_post_thumbnail_id($post_id);
    $thumbnail_id = $thumbnail_id ? intval($thumbnail_id) : 0;

    $thumbnail_url = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : '';
    
    // Ajouter un nonce pour la sécurité
    wp_nonce_field('wprg_cropper_action', 'wprg_cropper_nonce_field');
    ?>
    <div class="wprg-cropper-container">
        <div class="wprg-cropper-preview">
            <?php if ($thumbnail_url): ?>
                <img src="<?php echo esc_url($thumbnail_url); ?>" id="wprg-cropper-image" style="max-width:100%; max-height:200px; width:auto; height:auto; border-radius: 4px;">
                <p style="margin:5px 0 0; font-size:11px; color:#666;">Image actuelle</p>
            <?php else: ?>
                <div class="wprg-no-image" style="padding: 30px; text-align: center; color: #999;">
                    <span style="font-size: 48px;">📷</span>
                    <p>Aucune image sélectionnée</p>
                    <p style="font-size:12px; margin-top:10px;">Utilisez la boîte "Image mise en avant" ci-dessus</p>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="wprg-cropper-controls">
            <p style="margin:5px 0; padding:8px; background:#f0f6fc; border-radius:4px; font-size:12px; text-align:center;">
                <span class="dashicons dashicons-info"></span> 
                Utilisez la boîte "Image mise en avant" pour sélectionner une image
            </p>
            
            <?php if ($thumbnail_url): ?>
            <button type="button" class="button" id="wprg-crop-image-btn" style="margin-top:10px; width:100%;">✂️ Recadrer cette image (1080x1920)</button>
            <?php endif; ?>
        </div>
        
        <!-- Zone de recadrage -->
        <div id="wprg-crop-area" style="display:none; margin-top:15px; border-top:1px solid #ddd; padding-top:15px;">
            <div class="wprg-crop-wrapper" style="position:relative; max-height:300px; overflow:hidden; border:2px solid #ddd; border-radius:8px; background:#000;">
                <img src="" id="wprg-crop-image" style="display:block; width:100%; height:auto; pointer-events:none;">
                <div class="wprg-crop-overlay" style="position:absolute; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.5);"></div>
                <div class="wprg-crop-selection" style="position:absolute; border:2px solid #e1306c; box-shadow:0 0 0 9999px rgba(0,0,0,0.5); cursor:move; display:none;">
                    <div class="wprg-crop-handle nw" style="position:absolute; width:10px; height:10px; background:white; border:2px solid #e1306c; border-radius:50%; top:-5px; left:-5px; cursor:nw-resize;"></div>
                    <div class="wprg-crop-handle ne" style="position:absolute; width:10px; height:10px; background:white; border:2px solid #e1306c; border-radius:50%; top:-5px; right:-5px; cursor:ne-resize;"></div>
                    <div class="wprg-crop-handle sw" style="position:absolute; width:10px; height:10px; background:white; border:2px solid #e1306c; border-radius:50%; bottom:-5px; left:-5px; cursor:sw-resize;"></div>
                    <div class="wprg-crop-handle se" style="position:absolute; width:10px; height:10px; background:white; border:2px solid #e1306c; border-radius:50%; bottom:-5px; right:-5px; cursor:se-resize;"></div>
                </div>
            </div>
            <div class="wprg-crop-actions" style="margin-top:10px; display:flex; gap:5px;">
                <button type="button" class="button button-primary" id="wprg-apply-crop" style="flex:1;">✅ Appliquer le recadrage</button>
                <button type="button" class="button" id="wprg-cancel-crop" style="flex:1;">❌ Annuler</button>
            </div>
            <p style="margin:5px 0 0; font-size:11px; color:#666; text-align:center;">
                <span class="dashicons dashicons-info"></span> 
                Déplacez et redimensionnez la zone de recadrage (format 9:16)
            </p>
        </div>
        
        <input type="hidden" id="wprg-crop-x" value="0">
        <input type="hidden" id="wprg-crop-y" value="0">
        <input type="hidden" id="wprg-crop-width" value="0">
        <input type="hidden" id="wprg-crop-height" value="0">
        <input type="hidden" id="wprg-attachment-id" value="<?php echo esc_attr($thumbnail_id); ?>">
    </div>
    
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Variables globales
        var currentAttachmentId = $('#wprg-attachment-id').val();
        var originalImageWidth = 0;
        var originalImageHeight = 0;
        var scale = 1;
        
        var cropState = {
            x: 0, y: 0, width: 0, height: 0,
            startX: 0, startY: 0,
            startWidth: 0, startHeight: 0,
            startLeft: 0, startTop: 0,
            isDragging: false,
            isResizing: false,
            resizeHandle: ''
        };
        
        // Écouter les changements d'image mise en avant (système natif WordPress)
        $(document).on('DOMSubtreeModified', '#postimagediv .inside', function() {
            // Vérifier si l'image a changé
            var newThumbId = $('#_thumbnail_id').val();
            var newThumbUrl = $('#postimagediv img').attr('src');
            
            if (newThumbId && newThumbId !== currentAttachmentId) {
                currentAttachmentId = newThumbId;
                
                // Mettre à jour notre aperçu
                if (newThumbUrl) {
                    $('#wprg-cropper-image').attr('src', newThumbUrl + '?t=' + new Date().getTime());
                    $('#wprg-attachment-id').val(newThumbId);
                    
                    // Afficher le bouton de recadrage
                    if ($('#wprg-crop-image-btn').length === 0) {
                        $('.wprg-cropper-controls').append('<button type="button" class="button" id="wprg-crop-image-btn" style="margin-top:10px; width:100%;">✂️ Recadrer cette image (1080x1920)</button>');
                    } else {
                        $('#wprg-crop-image-btn').show();
                    }
                }
            }
        });
        
        // Observer les changements sur le champ _thumbnail_id (alternative plus fiable)
        var thumbnailObserver = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'value') {
                    var newThumbId = $('#_thumbnail_id').val();
                    if (newThumbId && newThumbId !== currentAttachmentId) {
                        currentAttachmentId = newThumbId;
                        
                        // Récupérer l'URL de l'image
                        $.ajax({
                            url: ajaxurl,
                            data: {
                                action: 'wprg_get_attachment_url',
                                attachment_id: newThumbId,
                                nonce: wprg_cropper.nonce
                            },
                            success: function(response) {
                                if (response.success) {
                                    $('#wprg-cropper-image').attr('src', response.data.url + '?t=' + new Date().getTime());
                                    $('#wprg-attachment-id').val(newThumbId);
                                    
                                    if ($('#wprg-crop-image-btn').length === 0) {
                                        $('.wprg-cropper-controls').append('<button type="button" class="button" id="wprg-crop-image-btn" style="margin-top:10px; width:100%;">✂️ Recadrer cette image (1080x1920)</button>');
                                    } else {
                                        $('#wprg-crop-image-btn').show();
                                    }
                                }
                            }
                        });
                    }
                }
            });
        });
        
        // Observer le champ _thumbnail_id
        var thumbnailField = document.getElementById('_thumbnail_id');
        if (thumbnailField) {
            thumbnailObserver.observe(thumbnailField, { attributes: true });
        }
        
        // Ouvrir le recadrage
        $(document).on('click', '#wprg-crop-image-btn', function() {
            var imageUrl = $('#wprg-cropper-image').attr('src');
            
            if (!currentAttachmentId || !imageUrl) {
                alert('Veuillez d\'abord sélectionner une image dans la boîte "Image mise en avant"');
                return;
            }
            
            $('#wprg-crop-image').attr('src', imageUrl.split('?')[0] + '?t=' + new Date().getTime()); // Nettoyer l'URL et ajouter timestamp
            $('#wprg-crop-area').show();
            
            if ($('#wprg-crop-image')[0].complete) {
                initCropper();
            } else {
                $('#wprg-crop-image').on('load', initCropper);
            }
        });
        
        // Initialiser le recadrage
        function initCropper() {
            var $image = $('#wprg-crop-image');
            var $selection = $('.wprg-crop-selection');
            
            // Obtenir les dimensions réelles
            originalImageWidth = $image[0].naturalWidth;
            originalImageHeight = $image[0].naturalHeight;
            
            // Vérifier que les dimensions sont valides
            if (originalImageWidth === 0 || originalImageHeight === 0) {
                setTimeout(initCropper, 100);
                return;
            }
            
            // Calculer l'échelle
            scale = $image.width() / originalImageWidth;
            
            // Calculer le recadrage optimal (ratio 9:16)
            var targetRatio = 9 / 16;
            
            if (originalImageWidth / originalImageHeight > targetRatio) {
                cropState.height = originalImageHeight;
                cropState.width = Math.round(originalImageHeight * targetRatio);
                cropState.x = Math.round((originalImageWidth - cropState.width) / 2);
                cropState.y = 0;
            } else {
                cropState.width = originalImageWidth;
                cropState.height = Math.round(originalImageWidth / targetRatio);
                cropState.x = 0;
                cropState.y = Math.round((originalImageHeight - cropState.height) / 2);
            }
            
            // Positionner la sélection
            $selection.css({
                'left': (cropState.x * scale) + 'px',
                'top': (cropState.y * scale) + 'px',
                'width': (cropState.width * scale) + 'px',
                'height': (cropState.height * scale) + 'px'
            }).show();
            
            // Mettre à jour les champs
            $('#wprg-crop-x').val(cropState.x);
            $('#wprg-crop-y').val(cropState.y);
            $('#wprg-crop-width').val(cropState.width);
            $('#wprg-crop-height').val(cropState.height);
            
            // Attacher les événements
            attachEvents();
        }
        
        // Attacher les événements
        function attachEvents() {
            var $selection = $('.wprg-crop-selection');
            
            // Déplacement
            $selection.on('mousedown', function(e) {
                if ($(e.target).hasClass('wprg-crop-handle')) return;
                
                e.preventDefault();
                cropState.isDragging = true;
                cropState.startX = e.pageX - (cropState.x * scale);
                cropState.startY = e.pageY - (cropState.y * scale);
            });
            
            // Redimensionnement
            $selection.find('.wprg-crop-handle').on('mousedown', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                cropState.isResizing = true;
                cropState.resizeHandle = $(this).hasClass('nw') ? 'nw' : 
                                        $(this).hasClass('ne') ? 'ne' : 
                                        $(this).hasClass('sw') ? 'sw' : 'se';
                
                cropState.startX = e.pageX;
                cropState.startY = e.pageY;
                cropState.startWidth = cropState.width;
                cropState.startHeight = cropState.height;
                cropState.startLeft = cropState.x;
                cropState.startTop = cropState.y;
            });
            
            // Mouvement de la souris
            $(document).on('mousemove', function(e) {
                if (!cropState.isDragging && !cropState.isResizing) return;
                
                e.preventDefault();
                
                if (cropState.isDragging) {
                    var newLeft = (e.pageX - cropState.startX) / scale;
                    var newTop = (e.pageY - cropState.startY) / scale;
                    
                    newLeft = Math.max(0, Math.min(newLeft, originalImageWidth - cropState.width));
                    newTop = Math.max(0, Math.min(newTop, originalImageHeight - cropState.height));
                    
                    cropState.x = Math.round(newLeft);
                    cropState.y = Math.round(newTop);
                }
                
                if (cropState.isResizing) {
                    var dx = (e.pageX - cropState.startX) / scale;
                    var dy = (e.pageY - cropState.startY) / scale;
                    
                    var newWidth = cropState.startWidth;
                    var newHeight = cropState.startHeight;
                    var newX = cropState.startLeft;
                    var newY = cropState.startTop;
                    
                    if (cropState.resizeHandle.includes('e')) {
                        newWidth = Math.max(50, cropState.startWidth + dx);
                        newHeight = Math.round(newWidth * 16 / 9);
                    }
                    if (cropState.resizeHandle.includes('s')) {
                        newHeight = Math.max(89, cropState.startHeight + dy);
                        newWidth = Math.round(newHeight * 9 / 16);
                    }
                    if (cropState.resizeHandle.includes('w')) {
                        newWidth = Math.max(50, cropState.startWidth - dx);
                        newX = cropState.startLeft + (cropState.startWidth - newWidth);
                        newHeight = Math.round(newWidth * 16 / 9);
                    }
                    if (cropState.resizeHandle.includes('n')) {
                        newHeight = Math.max(89, cropState.startHeight - dy);
                        newY = cropState.startTop + (cropState.startHeight - newHeight);
                        newWidth = Math.round(newHeight * 9 / 16);
                    }
                    
                    // Contraindre aux limites
                    if (newX < 0) {
                        newWidth += newX;
                        newX = 0;
                        newHeight = Math.round(newWidth * 16 / 9);
                    }
                    if (newY < 0) {
                        newHeight += newY;
                        newY = 0;
                        newWidth = Math.round(newHeight * 9 / 16);
                    }
                    if (newX + newWidth > originalImageWidth) {
                        newWidth = originalImageWidth - newX;
                        newHeight = Math.round(newWidth * 16 / 9);
                    }
                    if (newY + newHeight > originalImageHeight) {
                        newHeight = originalImageHeight - newY;
                        newWidth = Math.round(newHeight * 9 / 16);
                    }
                    
                    cropState.width = Math.max(50, Math.round(newWidth));
                    cropState.height = Math.max(89, Math.round(newHeight));
                    cropState.x = Math.max(0, Math.min(Math.round(newX), originalImageWidth - cropState.width));
                    cropState.y = Math.max(0, Math.min(Math.round(newY), originalImageHeight - cropState.height));
                }
                
                // Mettre à jour l'affichage
                $selection.css({
                    'left': (cropState.x * scale) + 'px',
                    'top': (cropState.y * scale) + 'px',
                    'width': (cropState.width * scale) + 'px',
                    'height': (cropState.height * scale) + 'px'
                });
                
                $('#wprg-crop-x').val(cropState.x);
                $('#wprg-crop-y').val(cropState.y);
                $('#wprg-crop-width').val(cropState.width);
                $('#wprg-crop-height').val(cropState.height);
            });
            
            // Relâcher la souris
            $(document).on('mouseup', function() {
                cropState.isDragging = false;
                cropState.isResizing = false;
            });
        }
        
        // Appliquer le recadrage
        $('#wprg-apply-crop').on('click', function() {
            if (!currentAttachmentId) {
                alert('Erreur: image non trouvée');
                return;
            }
            
            var postId = $('#post_ID').val();
            
            if (cropState.width < 10 || cropState.height < 10) {
                alert('La zone de recadrage est trop petite');
                return;
            }
            
            var cropData = {
                x: cropState.x,
                y: cropState.y,
                width: cropState.width,
                height: cropState.height
            };
            
            var $btn = $(this);
            var originalText = $btn.text();
            $btn.prop('disabled', true).text('Recadrage en cours...');
            
            $.ajax({
                url: wprg_cropper.ajax_url,
                type: 'POST',
                data: {
                    action: 'wprg_crop_image',
                    post_id: postId,
                    attachment_id: currentAttachmentId,
                    crop_data: JSON.stringify(cropData),
                    nonce: wprg_cropper.nonce
                },
                success: function(response) {
                    if (response.success) {
                        // Mettre à jour l'aperçu
                        var newImageUrl = response.data.thumbnail_url + '?t=' + new Date().getTime();
                        $('#wprg-cropper-image').attr('src', newImageUrl);
                        $('#wprg-attachment-id').val(response.data.attachment_id);
                        currentAttachmentId = response.data.attachment_id;
                        
                        // Mettre à jour l'image mise en avant dans WordPress
                        $('#_thumbnail_id').val(response.data.attachment_id).trigger('change');
                        
                        // Forcer la mise à jour de l'aperçu WordPress
                        if (wp.media.featuredImage && wp.media.featuredImage.frame()) {
                            // Mettre à jour l'image dans la frame média
                            var html = '<img src="' + newImageUrl + '" class="wp-post-image">';
                            $('#postimagediv .inside').html(html);
                        } else {
                            // Recharger l'aperçu via AJAX
                            wp.media.post('get-post-thumbnail-html', {
                                post_id: postId,
                                thumbnail_id: response.data.attachment_id,
                                _wpnonce: wprg_cropper.thumbnail_nonce
                            }).done(function(html) {
                                $('#postimagediv .inside').html(html);
                            });
                        }
                        
                        // Cacher la zone de recadrage
                        $('#wprg-crop-area').hide();
                        $('.wprg-crop-selection').hide();
                        
                        // Afficher un message de succès
                        var $notice = $('<div class="notice notice-success is-dismissible"><p>✅ Image recadrée avec succès !</p></div>');
                        $('.wprg-cropper-container').before($notice);
                        
                        setTimeout(function() {
                            $notice.fadeOut(function() { $(this).remove(); });
                        }, 2000);
                        
                        // Réinitialiser l'état
                        cropState = {
                            x: 0, y: 0, width: 0, height: 0,
                            startX: 0, startY: 0,
                            startWidth: 0, startHeight: 0,
                            startLeft: 0, startTop: 0,
                            isDragging: false,
                            isResizing: false,
                            resizeHandle: ''
                        };
                        
                    } else {
                        alert('Erreur: ' + response.data);
                    }
                },
                error: function(xhr, status, error) {
                    alert('Erreur AJAX: ' + error);
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        });
        
        // Annuler
        $('#wprg-cancel-crop').on('click', function() {
            $('#wprg-crop-area').hide();
            $('.wprg-crop-selection').hide();
        });
        
        // Empêcher la sélection de texte
        $(document).on('selectstart', false);
    });
    </script>
    <?php
}