<?php
$wpgv_company_logo = get_option('wpgv_company_logo') ? get_option('wpgv_company_logo') : '';

function save_base64_image_and_return_id($base64_image, $title)
{
    $upload_dir = wp_upload_dir();
    $upload_path = str_replace('/', DIRECTORY_SEPARATOR, $upload_dir['path']) . DIRECTORY_SEPARATOR;
    $image_data = explode(',', $base64_image);
    $decoded = base64_decode($image_data[1]);
    $filename = sanitize_file_name($title) . '.png';
    $hashed_filename = md5($filename . microtime()) . '_' . $filename;
    $image_upload = file_put_contents($upload_path . $hashed_filename, $decoded);

    if ($image_upload) {
        $file = array(
            'name' => $hashed_filename,
            'type' => 'image/png',
            'tmp_name' => $upload_path . $hashed_filename,
            'error' => 0,
            'size' => filesize($upload_path . $hashed_filename),
        );

        $file_return = wp_handle_sideload($file, array('test_form' => false));

        if (! isset($file_return['error'])) {
            $attachment = array(
                'post_mime_type' => $file_return['type'],
                'post_title' => sanitize_file_name($filename),
                'post_content' => '',
                'post_status' => 'inherit',
            );

            $attach_id = wp_insert_attachment($attachment, $file_return['file']);
            $attach_data = wp_generate_attachment_metadata($attach_id, $file_return['file']);
            wp_update_attachment_metadata($attach_id, $attach_data);

            return $attach_id;
        } else {
            error_log('File return error: ' . print_r($file_return['error'], true));
        }
    } else {
        error_log('Image upload failed for ' . $filename);
    }

    return false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['upload_image']) && $_FILES['upload_image']['size'] > 0) {
        $upload = wp_handle_upload($_FILES['upload_image'], array('test_form' => false));

        if (isset($upload['url'])) {
            $uploaded_image_url = $upload['url'];
        } else {
            $error_message = 'Image upload failed.';
        }
    }

    if (isset($_POST['uploaded_image_url']) && empty($uploaded_image_url)) {
        $uploaded_image_url = $_POST['uploaded_image_url'];
    }

    if (isset($_POST['selected_templates'])) {
        $selected_templates = $_POST['selected_templates'] ?? array();
        $base64_images = $_POST['base64_img'] ?? array();
        $template_jsons = $_POST['template_json'] ?? array();
        $template_types = $_POST['template_type'] ?? array();

        foreach ($selected_templates as $i) {
            $title = 'Giftcard modern ' . ($i + 1);

            $post_meta_values = array(
                'wpgv_customize_template_json_template' => '',
                'wpgv_customize_template_id_bg_template' => '',
                'wpgv_customize_template_bg_result' => '',
                'wpgv_customize_template_check_temp_custom' => 0,
                'wpgv_customize_template_template-style' => '',
                'wpgv_customize_template_status' => 'Active',
                'wpgv_customize_template_voucher_expiry_value' => 60,
                'wpgv_customize_template_select_template' => 'custom',
                'wpgv_customize_template_chosse_template' => sanitize_text_field($template_types[$i]),
            );

            if (! empty($template_jsons[$i])) {
                $post_meta_values['wpgv_customize_template_json_template'] = wp_kses_post($template_jsons[$i]);
            } else {
                echo 'No JSON data found for template ' . $title . '<br>';
                continue;
            }

            if (! empty($uploaded_image_url)) {
                $post_meta_values['wpgv_customize_template_id_bg_template'] = esc_url_raw($uploaded_image_url);

                $file_name = basename($uploaded_image_url);
                $post_meta_values['wpgv_customize_template_template-style'] = 'template-custom-' . sanitize_text_field($template_types[$i]) . '.png';
            } else {
                echo 'No uploaded image URL found for template ' . $title . '<br>';
                continue;
            }

            if (! empty($base64_images[$i])) {
                $image_id = save_base64_image_and_return_id($base64_images[$i], $title);
                if ($image_id) {
                    $post_meta_values['wpgv_customize_template_bg_result'] = $image_id;
                } else {
                    echo 'Failed to save base64 image for template ' . $title . '<br>';
                    continue;
                }
            } else {
                echo 'No base64 image data found for template ' . $title . '<br>';
                continue;
            }

            $post_id = create_voucher_template_post($title, $post_meta_values);

            if ($post_id) {
                echo '<div class="updated notice is-dismissible"> Created post: ' . $title . ' (ID: ' . $post_id . ')<br></div>';
            } else {
                echo '<div class="notice notice-error is-dismissible">Failed to create post: ' . $title . '<br></div>';
            }
        }
    }
}

$template_images = array(
    'template-voucher-lanscape-1.json',
    'template-voucher-lanscape-2.json',
    'template-voucher-lanscape-3.json',
    'template-voucher-portail-1.json',
    'template-voucher-portail-2.json',
    'template-voucher-portail-3.json',
);
global $wpdb;
$setting_table_name = $wpdb->prefix . 'giftvouchers_setting';
$options = $wpdb->get_row("SELECT * FROM $setting_table_name WHERE id = 1");
$company_name = $options->company_name;
$templates = array();
foreach ($template_images as $template_image) {
    $template_type = strpos($template_image, 'lanscape') !== false ? 'lanscape' : 'portail';

    // Fetch the JSON data
    $json_url = WPGIFT__PLUGIN_DIR . '/assets/img/template-images-v2/json/' . $template_image;
    $json_data = json_decode(file_get_contents($json_url));

    // Traverse through the children and find "gift_title_company"
    foreach ($json_data->children[0]->children as &$child) {
        if (isset($child->attrs->name) && $child->attrs->name === 'gift_title_company') {
            // Update the 'text' attribute with the desired value
            $child->attrs->text = $company_name;  // Change 'NEW COMPANY NAME' to whatever you want to set dynamically
        }
    }

    // Store the modified template data
    $templates[] = array(
        'json_url' => $json_url,
        'type' => $template_type,
        'json_data' => $json_data,
    );
}

?>

<div class="wrap wpgiftv-settings">
    <h1><?php echo esc_html__('Automatic Render Giftcard Modern Template', 'gift-voucher'); ?></h1>
    <p><?php echo esc_html__('Follow these steps to create a personalized gift card template. Upload your background image, select a template, and customize it!', 'gift-voucher'); ?></p>
    <div class="wpgiftv-row">
        <div class="wpgiftv-col100">
            <div class="white-box">
                <h2><?php esc_html_e('Step 1: Upload Background Image', 'gift-voucher'); ?></h2>
                <p class="description"><?php echo esc_html__('Start by uploading an image that will serve as the background for your gift card. This could be a company logo, a promotional image, or any graphic that represents your brand.', 'gift-voucher'); ?></p>

                <?php if (isset($error_message)) : ?>
                    <div class="error">
                        <p><?php echo esc_html($error_message); ?></p>
                    </div>
                <?php elseif (isset($success_message)) : ?>
                    <div class="updated">
                        <p><?php echo esc_html($success_message); ?></p>
                    </div>
                <?php endif; ?>

                <form id="template-selection-form" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="uploaded_image_url" id="uploaded_image_url"
                        value="<?php echo esc_attr($uploaded_image_url ?? ''); ?>">

                    <div class="wpgiftv-form-group">
                        <label for="upload_image"><?php esc_html_e('Select Background Giftcard:', 'gift-voucher'); ?></label>
                        <input type="file" id="upload_image" name="upload_image" accept="image/*"
                            class="wpgiftv-file-input">
                    </div>

                    <div id="customization-options" style="display:none;">
                        <h2><?php esc_html_e('Step 2: Toggle Elements and Customize Your Template', 'gift-voucher'); ?></h2>
                        <p class="description"><?php echo esc_html__('Select the elements you want to include in the template and pick a color for all text elements.', 'gift-voucher'); ?></p>

                        <div id="toggle-elements" class="wpgiftv-toggle-elements">
                            <div class="toggle-group">
                                <?php
                                $elements = [
                                    'giftcard_bg' => ['name' => 'Use Upload Gift Card Background', 'show' => false, 'checked' => true],
                                    'giftcard_logo' => ['name' => 'Gift Card Logo', 'show' => true, 'checked' => true],
                                    'gift_title_company' => ['name' => 'Company Name', 'show' => true, 'checked' => true],
                                    'gift_title_first' => ['name' => 'Gift Voucher', 'show' => false, 'checked' => true],
                                    'gift_title_last' => ['name' => 'Last Name on Gift Card', 'show' => false, 'checked' => true],
                                    'giftfrom_label' => ['name' => '"From" Label', 'show' => false, 'checked' => true],
                                    'giftto_label' => ['name' => '"To" Label', 'show' => false, 'checked' => true],
                                    'giftto_input' => ['name' => '"To" Input Field', 'show' => false, 'checked' => true],
                                    'giftfrom_input' => ['name' => '"From" Input Field', 'show' => false, 'checked' => true],
                                    'giftcard_website' => ['name' => 'Website on Gift Card', 'show' => true, 'checked' => true],
                                    'giftcard_email' => ['name' => 'Email on Gift Card', 'show' => true, 'checked' => true],
                                    'giftcard_monney' => ['name' => 'Amount on Gift Card', 'show' => true, 'checked' => true],
                                    'giftcard_monney_label' => ['name' => 'Amount Label', 'show' => false, 'checked' => false],
                                    'giftcard_date_gift_label' => ['name' => 'Date Label', 'show' => false, 'checked' => true],
                                    'giftcard_date_gift_input' => ['name' => 'Date Input Field', 'show' => false, 'checked' => true],
                                    'giftcard_counpon_label' => ['name' => 'Coupon Label', 'show' => false, 'checked' => true],
                                    'giftcard_counpon' => ['name' => 'Coupon Code', 'show' => false, 'checked' => true],
                                    'giftcard_des' => ['name' => 'Description', 'show' => false, 'checked' => true],
                                ];
                                ?>

                                <?php foreach ($elements as $element_id => $element_data) : ?>
                                    <div class="<?php echo $element_data['show'] ? '' : 'hide'; ?>">
                                        <label>
                                            <input type="checkbox" class="element-toggle"
                                                data-element-id="<?php echo esc_attr($element_id); ?>"
                                                <?php checked($element_data['checked']); ?>>
                                            <?php echo esc_html($element_data['name']); ?>
                                        </label><br>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div style="display: flex; align-items: center; margin-top: 20px;">
                            <h2 style="margin: 0; margin-right: 10px;"><?php esc_html_e('Change Text Color', 'gift-voucher'); ?></h2>
                            <input type="color" id="text_color_picker" name="text_color_picker" value="#000000"
                                style="flex-shrink: 0;">
                        </div>

                        <h2><?php esc_html_e('Step 3: Select a Template', 'gift-voucher'); ?></h2>
                        <p class="description"><?php esc_html_e('Choose a template layout to use with your selected background image.', 'gift-voucher'); ?></p>
                        <div id="template-selection">
                            <div class="wpgiftv-template-grid">
                                <?php foreach ($templates as $index => $template) : ?>
                                    <div class="wpgiftv-template-wrapper" id="template-<?php echo $index; ?>">
                                        <input type="checkbox" class="wpgiftv-template-checkbox"
                                            id="template-<?php echo $index; ?>" name="selected_templates[]"
                                            value="<?php echo $index; ?>">
                                        <label for="template-<?php echo $index; ?>"><?php printf(esc_html__('Template %d', 'gift-voucher'), $index + 1); ?></label>

                                        <input type="hidden" name="base64_img[<?php echo $index; ?>]"
                                            id="base64_img-<?php echo $index; ?>">
                                        <input type="hidden" name="template_type[<?php echo $index; ?>]"
                                            value="<?php echo esc_attr($template['type']); ?>">
                                        <input type="hidden" name="template_json[<?php echo $index; ?>]"
                                            id="template-json-<?php echo $index; ?>">

                                        <div id="container-<?php echo $index; ?>" class="wpgiftv-template-container"></div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <button type="submit" id="create-templates-button" class="wpgiftv-button-primary">
                                <?php esc_html_e('Create Selected Templates', 'gift-voucher'); ?>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

    </div>
</div>

<script src="<?php echo WPGIFT__PLUGIN_DIR . '/assets/js/konva.min.js'; ?>"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const imageUploadInput = document.getElementById('upload_image');
        const textColorPicker = document.getElementById('text_color_picker');
        const customizationOptions = document.getElementById('customization-options');
        const templates = <?php echo json_encode($templates); ?>;
        let imageUrl = null;

        // Debouncing function to limit how often a function is called
        function debounce(func, wait) {
            let timeout;
            return function() {
                clearTimeout(timeout);
                timeout = setTimeout(() => func.apply(this, arguments), wait);
            };
        }

        // Read image file and set the imageUrl
        const readImageFile = (file) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                imageUrl = e.target.result;
                redrawAllTemplates(imageUrl);
                customizationOptions.style.display = 'block'; // Show customization options after image upload
            };
            reader.readAsDataURL(file);
        };

        // Handle image upload change
        imageUploadInput.addEventListener('change', function() {
            const file = imageUploadInput.files[0];
            if (file) readImageFile(file);
        });

        // Handle text color change with debounce
        const debouncedTextColorChange = debounce(function() {
            if (imageUrl) redrawAllTemplates(imageUrl);
        }, 300);

        textColorPicker.addEventListener('input', debouncedTextColorChange);

        // Handle element toggle changes
        document.querySelectorAll('.element-toggle').forEach(toggle => {
            toggle.addEventListener('change', function() {
                if (imageUrl) redrawAllTemplates(imageUrl);
            });
        });

        // Redraw all templates with the uploaded image
        function redrawAllTemplates(imageUrl) {
            templates.forEach((template, index) => {
                const containerId = `container-${index}`;
                const dataJson = template.json_data;
                if (dataJson) {
                    initializeTemplateRender(dataJson, imageUrl, containerId, index);
                } else {
                    console.error('No JSON data available for template:', template);
                }
            });
        }

        // Initialize and render template
        function initializeTemplateRender(dataJson, imageUrl, containerId, index) {
            const selectedElements = Array.from(document.querySelectorAll('.element-toggle'))
                .filter(checkbox => checkbox.checked)
                .map(checkbox => checkbox.dataset.elementId);
            const textColor = textColorPicker.value;
            const companyLogo = "<?php echo esc_js($wpgv_company_logo ?: ''); ?>";

            if (!dataJson || !imageUrl) return;

            // Parse the stage from JSON if it exists
            const stage = Konva.Node.create(dataJson, containerId);

            // Find the existing layer or create a new one
            let layer = stage.findOne('Layer');
            if (!layer) {
                layer = new Konva.Layer();
                stage.add(layer);
            }

            // Change text color for all elements with className = Text
            stage.find('Text').forEach(textNode => {
                textNode.fill(textColor);
            });
            if (companyLogo) {
                let logoImage = new Image();
                logoImage.src = companyLogo;
                logoImage.onload = function() {
                    let logoLayer = stage.findOne('#giftcard_logo');
                    if (logoLayer) {
                        logoLayer.image(logoImage);

                        let maxWidth = 40;
                        let maxHeight = 40;
                        let ratio = 0;
                        let width = logoImage.width;
                        let height = logoImage.height;

                        if (width > maxWidth) {
                            ratio = maxWidth / width;
                            height = height * ratio;
                            width = width * ratio;
                        }
                        if (height > maxHeight) {
                            ratio = maxHeight / height;
                            width = width * ratio;
                            height = height * ratio;
                        }

                        logoLayer.width(width);
                        logoLayer.height(height);

                        logoLayer.getLayer().batchDraw();
                    }
                }
            }
            // Load the background image
            const bgImage = new Image();
            bgImage.src = imageUrl;
            bgImage.onload = function() {
                const imageAspectRatio = bgImage.width / bgImage.height;
                const stageAspectRatio = stage.width() / stage.height();
                let newWidth, newHeight;

                if (imageAspectRatio > stageAspectRatio) {
                    newHeight = stage.height();
                    newWidth = stage.height() * imageAspectRatio;
                } else {
                    newWidth = stage.width();
                    newHeight = stage.width() / imageAspectRatio;
                }

                const x = (stage.width() - newWidth) / 2;
                const y = (stage.height() - newHeight) / 2;

                // Check if 'giftcard_bg' already exists in the layer
                let bg = stage.findOne('#giftcard_bg');
                if (bg) {
                    bg.setAttrs({
                        x: x,
                        y: y,
                        image: bgImage,
                        width: newWidth,
                        height: newHeight,
                    });
                } else {
                    // Create and add new background if not found
                    bg = new Konva.Image({
                        x: x,
                        y: y,
                        image: bgImage,
                        width: newWidth,
                        height: newHeight,
                        id: 'giftcard_bg',
                    });
                    layer.add(bg);
                }
                // Process children from dataJson
                if (dataJson.children) {
                    dataJson.children.forEach(layerData => {
                        layerData.children.forEach(element => {
                            if (selectedElements.includes(element.attrs.id)) {
                                let konvaElement = stage.findOne(`#${element.attrs.id}`);
                                if (konvaElement) {
                                    if (element.className === 'Text') {
                                        konvaElement.text(element.attrs.text);
                                        konvaElement.fill(textColor);
                                    }
                                    konvaElement.opacity(1);
                                } else {
                                    switch (element.className) {
                                        case 'Text':
                                            konvaElement = new Konva.Text({
                                                ...element.attrs,
                                                text: element.attrs.text,
                                                fill: textColor,
                                            });
                                            stage.add(konvaElement);
                                            break;

                                        case 'Image':
                                            konvaElement = new Konva.Image({
                                                ...element.attrs,
                                            });
                                            if (element.attrs.id === 'giftcard_logo') {
                                                const logoImage = new Image();
                                                logoImage.src = companyLogo ? companyLogo : element.attrs.src;
                                                logoImage.onload = function() {
                                                    konvaElement.image(logoImage);
                                                    stage.draw();
                                                };
                                            }
                                            stage.add(konvaElement);
                                            break;

                                        default:
                                            console.log(`Element type ${element.className} is not handled.`);
                                            break;
                                    }
                                }
                            } else {
                                let konvaElement = stage.findOne(`#${element.attrs.id}`);
                                if (konvaElement) {
                                    konvaElement.opacity(0);
                                }
                            }
                        });
                    });
                }


                layer.draw();

                // Export data and update hidden fields
                const dataURL = stage.toDataURL({
                    pixelRatio: 1,
                });
                document.getElementById(`template-json-${index}`).value = stage.toJSON();
                document.getElementById(`base64_img-${index}`).value = dataURL;
            };
        }


        // Select all template wrapper elements
        const templateWrappers = document.querySelectorAll('.wpgiftv-template-wrapper');

        templateWrappers.forEach(wrapper => {
            // Add click event listener to each wrapper
            wrapper.addEventListener('click', function() {
                // Find the checkbox inside the wrapper
                const checkbox = wrapper.querySelector('.wpgiftv-template-checkbox');
                if (checkbox) {
                    // Toggle the checkbox state
                    checkbox.checked = !checkbox.checked;

                    // Add or remove the 'wpgiftv-active' class based on the checkbox state
                    wrapper.classList.toggle('wpgiftv-active', checkbox.checked);
                }
            });

            // Prevent the checkbox click event from propagating to the wrapper
            const checkbox = wrapper.querySelector('.wpgiftv-template-checkbox');
            if (checkbox) {
                checkbox.addEventListener('click', function(event) {
                    event.stopPropagation(); // Stop the event from bubbling up
                });
            }
        });


        var createButton = document.getElementById("create-templates-button");
        var checkboxes = document.querySelectorAll(".wpgiftv-template-checkbox");
        var form = document.getElementById("template-selection-form");

        createButton.addEventListener("click", function(e) {
            e.preventDefault();

            var isChecked = false;
            checkboxes.forEach(function(checkbox) {
                if (checkbox.checked) {
                    isChecked = true;
                }
            });

            if (!isChecked) {
                alert("Please select at least one template.");
                return false;
            }

            form.submit();
        });

    });
</script>