<?php
/**
 * Custom Customizer Controls
 *
 * @package ChaletMontagne
 * @since 1.0.0
 */

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

/**
 * Register custom controls
 * Only load when customizer is active
 */
function chaletmontagne_register_custom_controls() {
    /**
     * Custom control for luxury theme presets with visual preview
     */
    class ChaletMontagne_Luxury_Preset_Control extends WP_Customize_Control {
    public $type = 'luxury_preset';

    /**
     * Render the control
     */
    public function render_content() {
        $presets = array(
            'marron-sobre' => array(
                'label'  => __('Marron Sobre', 'chalet-montagne'),
                'desc'   => __('Brun raffiné & Sobre', 'chalet-montagne'),
                'colors' => array('#7B5B3A', '#A38B6D', '#FAF8F5'),
                'icon'   => '🤎',
                'category' => 'light',
            ),
            'esprit-bois' => array(
                'label'  => __('Esprit Bois', 'chalet-montagne'),
                'desc'   => __('Authentique & Chaleureux', 'chalet-montagne'),
                'colors' => array('#B07D3A', '#D4A95C', '#F5EDE0'),
                'icon'   => '🪵',
                'category' => 'wood',
            ),
            'noir-prestige' => array(
                'label'  => __('Noir Prestige', 'chalet-montagne'),
                'desc'   => __('Noir & Or, Luxe ultime', 'chalet-montagne'),
                'colors' => array('#C9A84C', '#E8D5A0', '#0A0A0A'),
                'icon'   => '✨',
                'category' => 'dark',
                'dark'   => true,
            ),
            'ardoise-mineral' => array(
                'label'  => __('Ardoise Minéral', 'chalet-montagne'),
                'desc'   => __('Minéral & Contemporain', 'chalet-montagne'),
                'colors' => array('#5A7080', '#8AA0B0', '#F5F7F9'),
                'icon'   => '🪨',
                'category' => 'light',
            ),
            'foret-sauge' => array(
                'label'  => __('Forêt Sauge', 'chalet-montagne'),
                'desc'   => __('Forêt & Sérénité', 'chalet-montagne'),
                'colors' => array('#5A7A5E', '#8AA88C', '#F6F8F5'),
                'icon'   => '🌲',
                'category' => 'light',
            ),
        );
        ?>
        <style>
            .luxury-preset-wrapper {
                margin-top: 12px;
            }
            .luxury-preset-grid {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
                margin-top: 8px;
            }
            .luxury-preset-option {
                position: relative;
                cursor: pointer;
                border: 3px solid #ddd;
                border-radius: 8px;
                padding: 12px;
                transition: all 0.3s ease;
                background: #fff;
            }
            .luxury-preset-option:hover {
                border-color: #999;
                transform: translateY(-2px);
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }
            .luxury-preset-option.selected {
                border-color: #0073aa;
                box-shadow: 0 0 0 1px #0073aa;
            }
            .luxury-preset-option input[type="radio"] {
                position: absolute;
                opacity: 0;
            }
            .luxury-preset-label {
                font-weight: 600;
                font-size: 13px;
                margin-bottom: 4px;
                color: #1d2327;
            }
            .luxury-preset-desc {
                font-size: 11px;
                color: #646970;
                margin-bottom: 8px;
            }
            .luxury-preset-colors {
                display: flex;
                gap: 4px;
                margin-top: 8px;
            }
            .luxury-preset-color {
                width: 30px;
                height: 30px;
                border-radius: 4px;
                border: 1px solid rgba(0,0,0,0.1);
                flex: 1;
            }
            .luxury-preset-check {
                position: absolute;
                top: 8px;
                right: 8px;
                width: 20px;
                height: 20px;
                background: #0073aa;
                border-radius: 50%;
                display: none;
                align-items: center;
                justify-content: center;
                color: #fff;
                font-size: 12px;
            }
            .luxury-preset-option.selected .luxury-preset-check {
                display: flex;
            }
        </style>

        <?php if (!empty($this->label)) : ?>
            <span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
        <?php endif; ?>

        <?php if (!empty($this->description)) : ?>
            <span class="description customize-control-description"><?php echo esc_html($this->description); ?></span>
        <?php endif; ?>

        <div class="luxury-preset-wrapper">
            <div class="luxury-preset-grid">
                <?php foreach ($presets as $preset_id => $preset_data) : ?>
                    <label class="luxury-preset-option <?php echo ($this->value() === $preset_id) ? 'selected' : ''; ?>" data-preset="<?php echo esc_attr($preset_id); ?>">
                        <input
                            type="radio"
                            name="<?php echo esc_attr($this->id); ?>"
                            value="<?php echo esc_attr($preset_id); ?>"
                            <?php $this->link(); ?>
                            <?php checked($this->value(), $preset_id); ?>
                        >
                        <div class="luxury-preset-check">✓</div>
                        <div class="luxury-preset-label"><?php echo esc_html($preset_data['label']); ?></div>
                        <div class="luxury-preset-desc"><?php echo esc_html($preset_data['desc']); ?></div>
                        <div class="luxury-preset-colors">
                            <?php foreach ($preset_data['colors'] as $color) : ?>
                                <div class="luxury-preset-color" style="background-color: <?php echo esc_attr($color); ?>;"></div>
                            <?php endforeach; ?>
                        </div>
                    </label>
                <?php endforeach; ?>
            </div>
        </div>

        <script>
        (function($) {
            $(document).ready(function() {
                $('.luxury-preset-option').on('click', function() {
                    var $this = $(this);
                    var preset = $this.data('preset');

                    // Update visual selection
                    $('.luxury-preset-option').removeClass('selected');
                    $this.addClass('selected');

                    // Trigger change for WordPress Customizer
                    $this.find('input[type="radio"]').prop('checked', true).trigger('change');
                });
            });
        })(jQuery);
        </script>
        <?php
    }
    }

    /**
     * Custom control for slider gallery
     */
    class ChaletMontagne_Gallery_Control extends WP_Customize_Control {
        public $type = 'gallery';

        public function enqueue() {
            wp_enqueue_media();
        }

        public function render_content() {
            $values = $this->value() ? explode(',', $this->value()) : array();
            ?>
            <style>
                .cm-gallery-wrapper {
                    margin-top: 12px;
                }
                .cm-gallery-images {
                    display: grid;
                    grid-template-columns: repeat(3, 1fr);
                    gap: 8px;
                    margin: 12px 0;
                }
                .cm-gallery-image {
                    position: relative;
                    aspect-ratio: 16/9;
                    border-radius: 4px;
                    overflow: hidden;
                    background: #f0f0f0;
                }
                .cm-gallery-image img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
                .cm-gallery-image .remove-image {
                    position: absolute;
                    top: 4px;
                    right: 4px;
                    width: 20px;
                    height: 20px;
                    background: rgba(220, 50, 50, 0.9);
                    color: #fff;
                    border: none;
                    border-radius: 50%;
                    cursor: pointer;
                    font-size: 14px;
                    line-height: 1;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .cm-gallery-image .remove-image:hover {
                    background: #c00;
                }
                .cm-gallery-buttons {
                    display: flex;
                    gap: 8px;
                }
                .cm-gallery-buttons button {
                    flex: 1;
                }
                .cm-gallery-image .image-order {
                    position: absolute;
                    bottom: 4px;
                    left: 4px;
                    background: rgba(0,0,0,0.7);
                    color: #fff;
                    padding: 2px 8px;
                    border-radius: 3px;
                    font-size: 11px;
                }
            </style>

            <?php if (!empty($this->label)) : ?>
                <span class="customize-control-title"><?php echo esc_html($this->label); ?></span>
            <?php endif; ?>

            <?php if (!empty($this->description)) : ?>
                <span class="description customize-control-description"><?php echo esc_html($this->description); ?></span>
            <?php endif; ?>

            <div class="cm-gallery-wrapper">
                <div class="cm-gallery-images" id="<?php echo esc_attr($this->id); ?>-preview">
                    <?php
                    if (!empty($values)) {
                        $order = 1;
                        foreach ($values as $attachment_id) {
                            $img_url = wp_get_attachment_image_url($attachment_id, 'thumbnail');
                            if ($img_url) {
                                echo '<div class="cm-gallery-image" data-id="' . esc_attr($attachment_id) . '">';
                                echo '<img src="' . esc_url($img_url) . '" alt="">';
                                echo '<span class="image-order">' . esc_html($order) . '</span>';
                                echo '<button type="button" class="remove-image" data-id="' . esc_attr($attachment_id) . '">×</button>';
                                echo '</div>';
                                $order++;
                            }
                        }
                    }
                    ?>
                </div>
                <div class="cm-gallery-buttons">
                    <button type="button" class="button cm-gallery-add" id="<?php echo esc_attr($this->id); ?>-add">
                        <?php esc_html_e('Ajouter des images', 'chalet-montagne'); ?>
                    </button>
                    <button type="button" class="button cm-gallery-clear" id="<?php echo esc_attr($this->id); ?>-clear">
                        <?php esc_html_e('Tout supprimer', 'chalet-montagne'); ?>
                    </button>
                </div>
                <input type="hidden" <?php $this->link(); ?> value="<?php echo esc_attr($this->value()); ?>" id="<?php echo esc_attr($this->id); ?>-input">
            </div>

            <script>
            (function($) {
                $(document).ready(function() {
                    var controlId = '<?php echo esc_js($this->id); ?>';
                    var $preview = $('#' + controlId + '-preview');
                    var $input = $('#' + controlId + '-input');
                    var $addBtn = $('#' + controlId + '-add');
                    var $clearBtn = $('#' + controlId + '-clear');

                    // Add images
                    $addBtn.on('click', function(e) {
                        e.preventDefault();
                        var frame = wp.media({
                            title: '<?php esc_html_e("Sélectionner des images pour le slider", "chalet-montagne"); ?>',
                            button: { text: '<?php esc_html_e("Ajouter au slider", "chalet-montagne"); ?>' },
                            multiple: true,
                            library: { type: 'image' }
                        });

                        frame.on('select', function() {
                            var attachments = frame.state().get('selection').toJSON();
                            var currentIds = $input.val() ? $input.val().split(',') : [];

                            attachments.forEach(function(attachment) {
                                if (currentIds.indexOf(attachment.id.toString()) === -1) {
                                    currentIds.push(attachment.id);
                                    var thumbUrl = attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
                                    var order = currentIds.length;
                                    $preview.append(
                                        '<div class="cm-gallery-image" data-id="' + attachment.id + '">' +
                                        '<img src="' + thumbUrl + '" alt="">' +
                                        '<span class="image-order">' + order + '</span>' +
                                        '<button type="button" class="remove-image" data-id="' + attachment.id + '">×</button>' +
                                        '</div>'
                                    );
                                }
                            });

                            $input.val(currentIds.join(',')).trigger('change');
                        });

                        frame.open();
                    });

                    // Remove single image
                    $preview.on('click', '.remove-image', function(e) {
                        e.preventDefault();
                        var idToRemove = $(this).data('id').toString();
                        var currentIds = $input.val() ? $input.val().split(',') : [];
                        currentIds = currentIds.filter(function(id) { return id !== idToRemove; });
                        $input.val(currentIds.join(',')).trigger('change');
                        $(this).closest('.cm-gallery-image').remove();
                        updateImageOrders();
                    });

                    // Clear all
                    $clearBtn.on('click', function(e) {
                        e.preventDefault();
                        $preview.empty();
                        $input.val('').trigger('change');
                    });

                    function updateImageOrders() {
                        $preview.find('.cm-gallery-image').each(function(index) {
                            $(this).find('.image-order').text(index + 1);
                        });
                    }
                });
            })(jQuery);
            </script>
            <?php
        }
    }
}
add_action('customize_register', 'chaletmontagne_register_custom_controls', 1);
