<?php

if (!defined('ABSPATH')) {
    exit;
}

class FlowDino_WC_Variation_Tab {

    public function __construct() {
    }

    public function render() {
        // Handle form submission
        if (
            isset($_POST['submit'], $_POST['flowdino_variation_nonce']) &&
            wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['flowdino_variation_nonce'])), 'flowdino_variation')
        ) {
            try {
                update_option('flowdino_variation_overlay_enabled', isset($_POST['variation_overlay_enabled']) ? 1 : 0);
                update_option('flowdino_variation_overlay_position', sanitize_text_field(wp_unslash($_POST['variation_overlay_position'] ?? 'top-left')));

                $color = sanitize_hex_color(wp_unslash($_POST['variation_overlay_color'] ?? '#1B5897'));
                update_option('flowdino_variation_overlay_color', $color ?: '#1B5897');

                $size = isset($_POST['variation_overlay_size']) ? intval($_POST['variation_overlay_size']) : 30;
                update_option('flowdino_variation_overlay_size', max(1, $size));

                update_option('flowdino_variation_overlay_mask', esc_url_raw(wp_unslash($_POST['variation_overlay_mask'] ?? '')));

                echo '<div class="notice notice-success"><p>' . esc_html__('Variation settings saved successfully.', 'flowdino') . '</p></div>';
            } catch (Exception $e) {
                // translators: %s is the error message
                echo '<div class="notice notice-error"><p>' . sprintf(esc_html__('Error saving variation settings: %s', 'flowdino'), esc_html($e->getMessage())) . '</p></div>';
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for debugging purposes
                error_log('FlowDino: Variation settings save error - ' . $e->getMessage());
            }
        }

        $enabled  = (bool) get_option('flowdino_variation_overlay_enabled', 0);
        $position = get_option('flowdino_variation_overlay_position', 'top-left');
        $color    = get_option('flowdino_variation_overlay_color', '#1B5897');
        $size     = intval(get_option('flowdino_variation_overlay_size', 30));
        $mask     = get_option('flowdino_variation_overlay_mask', '');

        $position_options = array(
            'top-left'     => __('Top-left', 'flowdino'),
            'top-right'    => __('Top-right', 'flowdino'),
            'center'       => __('Center', 'flowdino'),
            'bottom-left'  => __('Bottom-left', 'flowdino'),
            'bottom-right' => __('Bottom-right', 'flowdino'),
        );
        ?>
        <div class="flowdino-tab-content">
            <h2><?php esc_html_e('Variation Overlay', 'flowdino'); ?></h2>
            <p><?php esc_html_e('Configure how variation labels are sent in the payload as a text overlay on product images.', 'flowdino'); ?></p>

            <form method="post" action="">
                <?php wp_nonce_field('flowdino_variation', 'flowdino_variation_nonce'); ?>

                <div class="card" style="margin-bottom: 20px;">
                    <h3 style="margin: 15px;"><?php esc_html_e('Variation Overlay Settings', 'flowdino'); ?></h3>
                    <div style="padding: 15px;">
                        <table class="form-table">

                            <!-- Enable toggle -->
                            <tr>
                                <th scope="row"><?php esc_html_e('Enable variation overlay', 'flowdino'); ?></th>
                                <td>
                                    <label>
                                        <input
                                            type="checkbox"
                                            name="variation_overlay_enabled"
                                            id="variation_overlay_enabled"
                                            value="1"
                                            <?php checked($enabled, true); ?>
                                            onchange="document.getElementById('variation-overlay-options').style.display = this.checked ? '' : 'none';"
                                        >
                                        <?php esc_html_e('Send variation overlay data in the payload', 'flowdino'); ?>
                                    </label>
                                    <p class="description"><?php esc_html_e('When enabled, a variationOverlay object is included in the API payload for variable products. The content is automatically derived from the variation attributes.', 'flowdino'); ?></p>
                                </td>
                            </tr>

                        </table>

                        <!-- Options shown only when enabled -->
                        <div id="variation-overlay-options" style="<?php echo $enabled ? '' : 'display:none;'; ?>">
                            <table class="form-table">

                                <!-- Position -->
                                <tr>
                                    <th scope="row">
                                        <label for="variation_overlay_position"><?php esc_html_e('Position', 'flowdino'); ?></label>
                                    </th>
                                    <td>
                                        <select name="variation_overlay_position" id="variation_overlay_position" class="regular-text">
                                            <?php foreach ($position_options as $value => $label) : ?>
                                                <option value="<?php echo esc_attr($value); ?>" <?php selected($position, $value); ?>>
                                                    <?php echo esc_html($label); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <p class="description"><?php esc_html_e('Position of the variation text on the image. Default: top-left.', 'flowdino'); ?></p>
                                    </td>
                                </tr>

                                <!-- Color -->
                                <tr>
                                    <th scope="row">
                                        <label for="variation_overlay_color"><?php esc_html_e('Text color', 'flowdino'); ?></label>
                                    </th>
                                    <td>
                                        <input
                                            type="color"
                                            name="variation_overlay_color"
                                            id="variation_overlay_color"
                                            value="<?php echo esc_attr($color); ?>"
                                            style="height:36px;width:80px;padding:2px;vertical-align:middle;"
                                        >
                                        <input
                                            type="text"
                                            id="variation_overlay_color_text"
                                            value="<?php echo esc_attr($color); ?>"
                                            style="width:90px;vertical-align:middle;"
                                            oninput="document.getElementById('variation_overlay_color').value = this.value;"
                                            onchange="document.getElementById('variation_overlay_color').value = this.value;"
                                        >
                                        <script>
                                            document.getElementById('variation_overlay_color').addEventListener('input', function() {
                                                document.getElementById('variation_overlay_color_text').value = this.value;
                                            });
                                        </script>
                                        <p class="description"><?php esc_html_e('Hex color of the variation text. Default: #1B5897.', 'flowdino'); ?></p>
                                    </td>
                                </tr>

                                <!-- Size -->
                                <tr>
                                    <th scope="row">
                                        <label for="variation_overlay_size"><?php esc_html_e('Font size (px)', 'flowdino'); ?></label>
                                    </th>
                                    <td>
                                        <input
                                            type="number"
                                            name="variation_overlay_size"
                                            id="variation_overlay_size"
                                            value="<?php echo esc_attr($size); ?>"
                                            min="1"
                                            max="999"
                                            class="small-text"
                                        >
                                        <p class="description"><?php esc_html_e('Font size of the variation text in pixels. Default: 30.', 'flowdino'); ?></p>
                                    </td>
                                </tr>

                                <!-- Mask -->
                                <tr>
                                    <th scope="row">
                                        <label for="variation_overlay_mask"><?php esc_html_e('Mask image URL', 'flowdino'); ?></label>
                                    </th>
                                    <td>
                                        <div style="display:flex;align-items:center;gap:8px;">
                                            <input
                                                type="url"
                                                name="variation_overlay_mask"
                                                id="variation_overlay_mask"
                                                value="<?php echo esc_attr($mask); ?>"
                                                class="large-text"
                                                placeholder="https://example.com/mask.png"
                                            >
                                            <button type="button" id="variation_overlay_mask_upload" class="button"><?php esc_html_e('Upload', 'flowdino'); ?></button>
                                            <?php if ($mask) : ?>
                                            <button type="button" id="variation_overlay_mask_remove" class="button" style="color:#b32d2e;"><?php esc_html_e('Remove', 'flowdino'); ?></button>
                                            <?php endif; ?>
                                        </div>
                                        <?php if ($mask) : ?>
                                        <div id="variation_overlay_mask_preview" style="margin-top:8px;">
                                            <img src="<?php echo esc_attr($mask); ?>" style="max-height:80px;border:1px solid #ddd;padding:4px;background:#f0f0f0;" alt="">
                                        </div>
                                        <?php else : ?>
                                        <div id="variation_overlay_mask_preview" style="margin-top:8px;display:none;">
                                            <img src="" style="max-height:80px;border:1px solid #ddd;padding:4px;background:#f0f0f0;" alt="">
                                        </div>
                                        <?php endif; ?>
                                        <p class="description"><?php esc_html_e('Optional URL of a PNG image (with transparency) composited behind the variation text.', 'flowdino'); ?></p>
                                        <script>
                                        (function() {
                                            var frame;
                                            document.getElementById('variation_overlay_mask_upload').addEventListener('click', function(e) {
                                                e.preventDefault();
                                                if (frame) { frame.open(); return; }
                                                frame = wp.media({
                                                    title: <?php echo wp_json_encode(__('Select mask image', 'flowdino')); ?>,
                                                    button: { text: <?php echo wp_json_encode(__('Use this image', 'flowdino')); ?> },
                                                    multiple: false,
                                                    library: { type: 'image' }
                                                });
                                                frame.on('select', function() {
                                                    var attachment = frame.state().get('selection').first().toJSON();
                                                    var url = attachment.url;
                                                    document.getElementById('variation_overlay_mask').value = url;
                                                    var preview = document.getElementById('variation_overlay_mask_preview');
                                                    preview.querySelector('img').src = url;
                                                    preview.style.display = '';
                                                    var removeBtn = document.getElementById('variation_overlay_mask_remove');
                                                    if (removeBtn) { removeBtn.style.display = ''; }
                                                });
                                                frame.open();
                                            });
                                            var removeBtn = document.getElementById('variation_overlay_mask_remove');
                                            if (removeBtn) {
                                                removeBtn.addEventListener('click', function(e) {
                                                    e.preventDefault();
                                                    document.getElementById('variation_overlay_mask').value = '';
                                                    var preview = document.getElementById('variation_overlay_mask_preview');
                                                    preview.querySelector('img').src = '';
                                                    preview.style.display = 'none';
                                                    removeBtn.style.display = 'none';
                                                });
                                            }
                                        }());
                                        </script>
                                    </td>
                                </tr>

                            </table>
                        </div><!-- /#variation-overlay-options -->
                    </div>
                </div>

                <?php submit_button(__('Save Variation Settings', 'flowdino')); ?>
            </form>
        </div>
        <?php
    }
}
