<?php

/**
 * Product Page Gift Checkbox Functionality
 * Allows customers to add a gift card to any product purchase
 */

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

class WPGV_Product_Page_Gift_Checkbox
{

    public function __construct()
    {
        // Check if both WooCommerce and Product page gift checkbox are enabled
        if ($this->is_feature_enabled()) {
            // Add checkbox and form to product page
            add_action('woocommerce_before_add_to_cart_button', array($this, 'display_gift_checkbox_form'), 20);

            // Enqueue scripts and styles
            add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));

            // Handle add to cart with gift voucher data
            add_filter('woocommerce_add_cart_item_data', array($this, 'add_gift_voucher_data_to_cart'), 10, 3);

            // Display gift voucher data in cart
            add_filter('woocommerce_get_item_data', array($this, 'display_gift_voucher_data_in_cart'), 10, 2);

            // Adjust cart item price when gift voucher is added
            add_action('woocommerce_before_calculate_totals', array($this, 'adjust_cart_item_price_with_gift_voucher'), 10, 1);

            // Add gift voucher data to order items
            add_action('woocommerce_checkout_create_order_line_item', array($this, 'add_gift_voucher_data_to_order_items'), 10, 4);

            // Create voucher when order is created (before payment) - use multiple hooks for reliability
            add_action('woocommerce_new_order', array($this, 'create_gift_voucher_on_new_order'), 10, 1);
            add_action('woocommerce_checkout_order_processed', array($this, 'create_gift_voucher_on_new_order'), 10, 1);

            // Process gift voucher on payment completion (update status and send email)
            add_action('woocommerce_order_status_completed', array($this, 'process_gift_voucher_on_order_complete'), 10, 2);
            add_action('woocommerce_payment_complete', array($this, 'process_gift_voucher_on_payment_complete'), 10, 1);

            // AJAX handlers
            add_action('wp_ajax_wpgv_get_modern_templates', array($this, 'ajax_get_modern_templates'));
            add_action('wp_ajax_nopriv_wpgv_get_modern_templates', array($this, 'ajax_get_modern_templates'));
            add_action('wp_ajax_wpgv_get_template_data', array($this, 'ajax_get_template_data'));
            add_action('wp_ajax_nopriv_wpgv_get_template_data', array($this, 'ajax_get_template_data'));
            add_action('wp_ajax_wpgv_save_canvas_image', array($this, 'ajax_save_canvas_image'));
            add_action('wp_ajax_nopriv_wpgv_save_canvas_image', array($this, 'ajax_save_canvas_image'));
            add_action('wp_ajax_wpgv_generate_preview_coupon', array($this, 'ajax_generate_preview_coupon'));
            add_action('wp_ajax_nopriv_wpgv_generate_preview_coupon', array($this, 'ajax_generate_preview_coupon'));

            // AJAX handlers for settings page
            add_action('wp_ajax_wpgv_get_checkbox_templates', array($this, 'ajax_get_checkbox_templates'));
            add_action('wp_ajax_wpgv_get_checkbox_products', array($this, 'ajax_get_checkbox_products'));

            // Hide technical _wpgv_ itemmeta keys in WooCommerce admin item display
            add_filter('woocommerce_hidden_order_itemmeta', array($this, 'hide_wpgv_order_item_meta'), 10, 1);
        }
    }

    /**
     * Check if feature is enabled
     */
    private function is_feature_enabled()
    {
        global $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        return ($options && $options->is_woocommerce_enable == 1 && $options->is_product_page_gift_checkbox == 1);
    }

    /**
     * Hide technical _wpgv_ order item meta keys from WooCommerce admin to avoid duplicate display
     * Keeps meta in DB and available programmatically
     */
    public function hide_wpgv_order_item_meta($hidden_meta)
    {
        $keys_to_hide = array(
            '_wpgv_has_gift_voucher',
            '_wpgv_template_id',
            '_wpgv_your_name',
            '_wpgv_recipient_name',
            '_wpgv_recipient_email',
            '_wpgv_your_email',
            '_wpgv_personal_message',
            '_wpgv_preview_coupon_code',
            '_wpgv_canvas_temp_file',
            '_wpgv_original_product_price',
            '_wpgv_product_regular_price',
            '_wpgv_product_sale_price',
            '_wpgv_template_price',
            '_wpgv_voucher_code',
            '_wpgv_voucher_id',
        );
        // Also hide the human-friendly meta labels we add to avoid duplicate display
        $friendly_keys_to_hide = array(
            'Preview Coupon Code',
            'Canvas Temp File',
            'Original Product Price',
            'Regular Price',
            'Sale Price',
        );

        $keys_to_hide = array_merge($keys_to_hide, $friendly_keys_to_hide);

        if (!is_array($hidden_meta)) {
            $hidden_meta = (array) $hidden_meta;
        }

        return array_unique(array_merge($hidden_meta, $keys_to_hide));
    }

    /**
     * Save canvas base64 data to temporary file
     * Returns filename (without path) on success, false on failure
     */
    private function save_canvas_to_temp_file($canvas_data)
    {
        if (empty($canvas_data)) {
            return false;
        }

        // Validate base64 image data
        if (!preg_match('/^data:image\/(png|jpeg|jpg);base64,/', $canvas_data)) {
            error_log('WPGV: Invalid canvas data format');
            return false;
        }

        // Get upload directory
        $upload = wp_upload_dir();
        $temp_dir = $upload['basedir'] . '/voucherpdfuploads/temp/';

        // Create temp directory if not exists
        if (!file_exists($temp_dir)) {
            wp_mkdir_p($temp_dir);
        }

        // Generate unique filename
        $filename = 'canvas_' . uniqid() . '_' . time() . '.png';
        $file_path = $temp_dir . $filename;

        // Decode and save base64 data
        $canvas_data = substr($canvas_data, strpos($canvas_data, ',') + 1);
        $decoded_data = base64_decode($canvas_data);

        if ($decoded_data === false) {
            error_log('WPGV: Failed to decode canvas data');
            return false;
        }

        $result = file_put_contents($file_path, $decoded_data);

        if ($result === false) {
            error_log('WPGV: Failed to save canvas to temp file: ' . $file_path);
            return false;
        }

        error_log('WPGV: Canvas saved to temp file: ' . $filename . ' (' . $result . ' bytes)');
        return $filename;
    }

    /**
     * Get canvas data (base64) from temporary file
     * Returns base64 string on success, null on failure
     */
    private function get_canvas_from_temp_file($filename)
    {
        if (empty($filename)) {
            return null;
        }

        $upload = wp_upload_dir();
        $temp_dir = $upload['basedir'] . '/voucherpdfuploads/temp/';
        $file_path = $temp_dir . $filename;

        if (!file_exists($file_path)) {
            error_log('WPGV: Canvas temp file not found: ' . $file_path);
            return null;
        }

        $file_data = file_get_contents($file_path);
        if ($file_data === false) {
            error_log('WPGV: Failed to read canvas temp file: ' . $file_path);
            return null;
        }

        // Convert to base64 format expected by PDF generator
        $base64 = 'data:image/png;base64,' . base64_encode($file_data);
        error_log('WPGV: Canvas loaded from temp file: ' . $filename);

        return $base64;
    }

    /**
     * Delete canvas temporary file
     */
    private function delete_canvas_temp_file($filename)
    {
        if (empty($filename)) {
            return;
        }

        $upload = wp_upload_dir();
        $temp_dir = $upload['basedir'] . '/voucherpdfuploads/temp/';
        $file_path = $temp_dir . $filename;

        if (file_exists($file_path)) {
            $result = unlink($file_path);
            if ($result) {
                error_log('WPGV: Deleted canvas temp file: ' . $filename);
            } else {
                error_log('WPGV: Failed to delete canvas temp file: ' . $file_path);
            }
        }
    }

    /**
     * Check if current product should show the gift checkbox
     */
    private function should_show_gift_checkbox()
    {
        global $product, $wpdb;

        if (!$product) {
            return false;
        }

        // Don't show for gift_voucher product type
        $product_type = $product->get_type();
        if ($product_type === 'gift_voucher') {
            return false;
        }

        // Don't show for WC_Gift_Voucher_Product class
        if (is_a($product, 'WC_Gift_Voucher_Product')) {
            return false;
        }

        // Check allowed products filter
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        $allowed_products_json = isset($options->wpgv_checkbox_allowed_products) ? $options->wpgv_checkbox_allowed_products : '';
        $allowed_products = !empty($allowed_products_json) ? json_decode($allowed_products_json, true) : array();

        // If allowed products is not empty and doesn't contain 'all', check if current product is in the list
        if (!empty($allowed_products) && !in_array('all', $allowed_products) && is_array($allowed_products)) {
            $product_id = $product->get_id();
            if (!in_array($product_id, $allowed_products)) {
                return false; // Product not in allowed list
            }
        }

        // Show for all other product types (simple, variable, etc.)
        return true;
    }

    /**
     * Display checkbox and form on product page
     */
    public function display_gift_checkbox_form()
    {
        if (!$this->should_show_gift_checkbox()) {
            return;
        }

        global $product, $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

?>
        <div id="wpgv-product-gift-checkbox-wrapper" class="wpgv-product-gift-checkbox-wrapper">
            <div class="wpgv-gift-checkbox-container">
                <label for="wpgv_add_gift_voucher">
                    <input type="checkbox" id="wpgv_add_gift_voucher" name="wpgv_add_gift_voucher" value="yes">
                    <?php _e('Do you want to add a gift card?', 'gift-voucher'); ?>
                </label>
            </div>

            <div id="wpgv-gift-form-container" class="wpgv-gift-form-container" style="display: none;">
                <p>
                    <strong><?php _e('Select Gift Card Template', 'gift-voucher'); ?></strong>
                </p>

                <?php
                // Only show tabs if orientation filter is 'all'
                $allowed_template_orientation = isset($options->wpgv_checkbox_template_orientation) ? $options->wpgv_checkbox_template_orientation : 'all';
                if ($allowed_template_orientation === 'all') :
                ?>
                <div class="wpgv-template-tabs" id="wpgv-template-tabs">
                    <button type="button" class="wpgv-template-tab active" data-orientation="landscape" title="<?php _e('Landscape', 'gift-voucher'); ?>">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="2" y="6" width="20" height="12" rx="2"/>
                        </svg>
                    </button>
                    <button type="button" class="wpgv-template-tab" data-orientation="portrait" title="<?php _e('Portrait', 'gift-voucher'); ?>">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <rect x="7" y="2" width="10" height="20" rx="2"/>
                        </svg>
                    </button>
                </div>
                <?php endif; ?>

                <div class="wpgv-templates-list" id="wpgv-templates-list">
                    <p><?php _e('Loading templates...', 'gift-voucher'); ?></p>
                </div>

                <input type="hidden" id="wpgv_selected_template_id" name="wpgv_selected_template_id" value="">

                <!-- Canvas container for template preview -->
                <div id="wpgv-template-preview-container" class="wpgv-template-preview" style="display: none;">
                    <p><strong><?php _e('Preview', 'gift-voucher'); ?></strong></p>
                    <div id="wpgv_template_canvas_container">
                        <!-- Konva stage will be rendered here -->
                    </div>
                </div>

                <div class="wpgv-gift-form-fields" id="wpgv-gift-form-fields" style="display: none;">
                    <div class="wpgv-form-field">
                        <label for="wpgv_your_name"><?php _e('Your Name', 'gift-voucher'); ?> <span class="required">*</span></label>
                        <input type="text" id="wpgv_your_name" name="wpgv_your_name" maxlength="30" class="wpgv-input">
                    </div>

                    <div class="wpgv-form-field">
                        <label for="wpgv_recipient_name"><?php _e('Recipient Name', 'gift-voucher'); ?> <span class="required">*</span></label>
                        <input type="text" id="wpgv_recipient_name" name="wpgv_recipient_name" maxlength="30" class="wpgv-input">
                    </div>

                    <div class="wpgv-form-field">
                        <label for="wpgv_recipient_email"><?php _e('Send the voucher to recipient email here', 'gift-voucher'); ?> <span class="required">*</span></label>
                        <input type="email" id="wpgv_recipient_email" name="wpgv_recipient_email" class="wpgv-input">
                    </div>

                    <div class="wpgv-form-field">
                        <label for="wpgv_your_email"><?php _e('Your email address (for the receipt)', 'gift-voucher'); ?> <span class="required">*</span></label>
                        <input type="email" id="wpgv_your_email" name="wpgv_your_email" class="wpgv-input">
                    </div>

                    <div class="wpgv-form-field">
                        <label for="wpgv_personal_message"><?php _e('Personal Message (Optional) (Max: 250 Characters)', 'gift-voucher'); ?></label>
                        <textarea id="wpgv_personal_message" name="wpgv_personal_message" maxlength="250" class="wpgv-input" rows="4"></textarea>
                    </div>

                    <div class="wpgv-form-field">
                        <p class="wpgv-gift-price">
                            <?php _e('Product price:', 'gift-voucher'); ?>
                            <strong><?php echo wc_price($product->get_price()); ?></strong>
                        </p>
                    </div>
                </div>
            </div>
        </div>
<?php
    }

    /**
     * Enqueue scripts and styles
     */
    public function enqueue_scripts()
    {
        if (!is_product()) {
            return;
        }

        wp_enqueue_style(
            'wpgv-product-gift-checkbox',
            WPGIFT__PLUGIN_URL . '/assets/css/product-gift-checkbox.css',
            array(),
            WPGIFT_VERSION
        );

        // Enqueue Konva.js for template rendering
        wp_enqueue_script(
            'wpgv-konva-min-js',
            WPGIFT__PLUGIN_URL . '/assets/js/konva.min.js',
            array('jquery'),
            WPGIFT_VERSION,
            true
        );

        wp_enqueue_script(
            'wpgv-product-gift-checkbox-konva',
            WPGIFT__PLUGIN_URL . '/assets/js/product-gift-checkbox-konva.js',
            array('jquery', 'wpgv-konva-min-js'),
            WPGIFT_VERSION,
            true
        );

        wp_enqueue_script(
            'wpgv-product-gift-checkbox',
            WPGIFT__PLUGIN_URL . '/assets/js/product-gift-checkbox.js',
            array('jquery', 'wpgv-konva-min-js', 'wpgv-product-gift-checkbox-konva'),
            WPGIFT_VERSION,
            true
        );

        global $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        // Get WooCommerce currency settings
        $wc_currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'USD';
        $wc_currency_symbol = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '£';
        $wc_currency_pos = get_option('woocommerce_currency_pos', 'right');

        wp_localize_script('wpgv-product-gift-checkbox', 'wpgv_product_gift_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('wpgv_product_gift_nonce'),
            'please_select_template' => __('Please select a gift card template', 'gift-voucher'),
            'please_fill_fields' => __('Please fill in all required fields', 'gift-voucher'),
            'plugin_url' => WPGIFT__PLUGIN_URL,
            'currency' => $wc_currency,
            'currency_symbol' => $wc_currency_symbol,
            'currency_position' => $wc_currency_pos,
            'company_logo' => get_option('wpgv_company_logo', ''),
            'company_name' => $options ? $options->company_name : '',
            'pdf_footer_email' => $options ? $options->pdf_footer_email : '',
            'pdf_footer_url' => $options ? $options->pdf_footer_url : '',
        ));
    }

    /**
     * AJAX handler to get modern templates
     */
    public function ajax_get_modern_templates()
    {
        check_ajax_referer('wpgv_product_gift_nonce', 'nonce');

        global $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        // Get filter settings
        $allowed_template_orientation = isset($options->wpgv_checkbox_template_orientation) ? $options->wpgv_checkbox_template_orientation : 'all';
        $allowed_templates_json = isset($options->wpgv_checkbox_allowed_templates) ? $options->wpgv_checkbox_allowed_templates : '';
        $allowed_templates = !empty($allowed_templates_json) ? json_decode($allowed_templates_json, true) : array();

        // Check if 'all' is selected for templates
        $filter_templates = !empty($allowed_templates) && !in_array('all', $allowed_templates);

        // Get all Giftcard Modern templates (voucher_template)
        // Don't filter by orientation in WP_Query - we'll filter in PHP instead
        $voucher_arr = array(
            'post_type'      => 'voucher_template',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => array(
                array(
                    'key'     => 'wpgv_customize_template_status',
                    'value'   => 'active',
                    'compare' => '=',
                ),
            )
        );

        $template_voucher_args = new WP_Query($voucher_arr);

        $templates = array();

        if ($template_voucher_args->have_posts()) {
            while ($template_voucher_args->have_posts()) {
                $template_voucher_args->the_post();
                $post_id = get_the_ID();

                // Apply allowed templates filter if specified (skip if 'all' is selected)
                if ($filter_templates && !in_array($post_id, $allowed_templates)) {
                    continue; // Skip this template
                }

                // Get orientation meta value
                $choose_template = get_post_meta($post_id, 'wpgv_customize_template_chosse_template', true);
                $selected_voucher_template = get_post_meta($post_id, 'wpgv_customize_template_template-style', true);

                // Determine if template is landscape
                $is_landscape = (strpos($selected_voucher_template, 'lanscape') !== false || $choose_template == 'lanscape' || $choose_template == 'landscape');

                // Apply orientation filter if not 'all'
                if ($allowed_template_orientation === 'portrait') {
                    // Portrait: empty value, 'portrait', or anything that's not landscape variants
                    if ($is_landscape) {
                        continue; // Skip landscape templates
                    }
                } elseif ($allowed_template_orientation === 'landscape') {
                    // Landscape: only landscape variants
                    if (!$is_landscape) {
                        continue; // Skip portrait templates
                    }
                }

                $select_status_template = get_post_meta($post_id, 'wpgv_customize_template_select_template', true);

                $image_url = '';
                if ($select_status_template == 'custom') {
                    $get_bg_temp = get_post_meta($post_id, 'wpgv_customize_template_bg_result', true);
                    $link_bg_temp = wp_get_attachment_image_src($get_bg_temp, 'large');
                    if ($link_bg_temp) {
                        $image_url = $link_bg_temp[0];
                    }
                } else {
                    $image_url = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/png/' . $selected_voucher_template;
                }

                $template_price = get_post_meta($post_id, 'wpgv_customize_template_voucher_price_frontend', true);

                $templates[] = array(
                    'id' => $post_id,
                    'title' => get_the_title(),
                    'image' => $image_url,
                    'template_style' => $selected_voucher_template,
                    'price' => !empty($template_price) ? floatval($template_price) : 0,
                    'is_landscape' => $is_landscape
                );
            }
            wp_reset_postdata();
        }

        wp_send_json_success($templates);
    }

    /**
     * AJAX handler to get template data (JSON, image, etc.)
     */
    public function ajax_get_template_data()
    {
        try {
            error_log('WPGV: ajax_get_template_data called');
            check_ajax_referer('wpgv_product_gift_nonce', 'nonce');

            $template_id = isset($_POST['template_id']) ? intval($_POST['template_id']) : 0;
            error_log('WPGV: Template ID: ' . $template_id);

            if (!$template_id) {
                error_log('WPGV: Invalid template ID');
                wp_send_json_error(array('message' => 'Invalid template ID'));
                return;
            }

            global $wpdb;
            $setting_table = $wpdb->prefix . 'giftvouchers_setting';
            error_log('WPGV: Settings table: ' . $setting_table);
            $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

            if (!$options) {
                error_log('WPGV: No settings found in database');
                wp_send_json_error(array('message' => 'Plugin settings not found'));
                return;
            }
            error_log('WPGV: Settings loaded successfully');

            // Get template metadata
            $select_status_template = get_post_meta($template_id, 'wpgv_customize_template_select_template', true);
            $selected_voucher_template = get_post_meta($template_id, 'wpgv_customize_template_template-style', true);
            $get_json_temp = get_post_meta($template_id, 'wpgv_customize_template_json_template', true);
            $choose_template = get_post_meta($template_id, 'wpgv_customize_template_chosse_template', true);

            // Get template image
            $images_template = "";
            $json = "";

            if (!empty($select_status_template)) {
                if ($select_status_template == "default") {
                    $title_template = str_replace(".png", ".svg", $selected_voucher_template);
                    $images_template = WPGIFT__PLUGIN_URL . '/assets/img/template-images-v2/' . $title_template;

                    $name_template = str_replace(".png", ".json", $selected_voucher_template);
                    $get_url_json = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/' . $name_template;
                    $json_content = @file_get_contents($get_url_json);
                    $json = $json_content ? $json_content : '';
                } else if ($select_status_template == "custom") {
                    $get_bg_template = get_post_meta($template_id, 'wpgv_customize_template_id_bg_template', true);
                    if (is_numeric($get_bg_template)) {
                        $get_url_bg = wp_get_attachment_image_src($get_bg_template, 'large');
                        $images_template = $get_url_bg[0];
                    } else {
                        $images_template = $get_bg_template;
                    }

                    // Handle JSON - might be array or string
                    $json = $get_json_temp;
                    if (is_array($json)) {
                        error_log('WPGV: Custom template JSON is array, encoding to string');
                        $json = json_encode($json);
                    } else if (empty($json)) {
                        error_log('WPGV: Custom template JSON is empty');
                        $json = '';
                    } else {
                        error_log('WPGV: Custom template JSON found (' . strlen($json) . ' chars)');
                    }
                }
            } else {
                $title_template = str_replace(".png", ".svg", $selected_voucher_template);
                $images_template = WPGIFT__PLUGIN_URL . '/assets/img/template-images-v2/' . $title_template;

                $name_template = str_replace(".png", ".json", $selected_voucher_template);
                $get_url_json = 'https://gift-card-pro.s3.eu-central-1.amazonaws.com/templates/version-1.2/json/' . $name_template;
                $json_content = @file_get_contents($get_url_json);
                $json = $json_content ? $json_content : '';
            }

            // Parse JSON to get labels
            $giftto = __('Gift To', 'gift-voucher');
            $giftfrom = __('Gift From', 'gift-voucher');
            $date_of = __('Date', 'gift-voucher');
            $counpon = __('Coupon', 'gift-voucher');
            $voucher_name_first = __('Voucher', 'gift-voucher');
            $voucher_name_last = __('Name', 'gift-voucher');
            $value_text = __('value', 'gift-voucher');

            if ($json) {
                $jsonArray = json_decode($json, true);
                if ($jsonArray && isset($jsonArray['children'])) {
                    foreach ($jsonArray['children'] as $child) {
                        if (isset($child['children'])) {
                            foreach ($child['children'] as $item) {
                                if (isset($item['attrs'])) {
                                    $attrs = $item['attrs'];
                                    if (isset($attrs['id']) && isset($attrs['text'])) {
                                        switch ($attrs['id']) {
                                            case 'giftto_label':
                                                $giftto = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'giftfrom_label':
                                                $giftfrom = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'giftcard_date_gift_label':
                                                $date_of = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'giftcard_counpon_label':
                                                $counpon = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'gift_title_first':
                                                $voucher_name_first = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'gift_title_last':
                                                $voucher_name_last = __($attrs['text'], 'gift-voucher');
                                                break;
                                            case 'giftcard_monney_label':
                                                $value_text = __($attrs['text'], 'gift-voucher');
                                                break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Get expiry settings
            $wpgv_hide_expiry = get_option('wpgv_hide_expiry') ? get_option('wpgv_hide_expiry') : 'yes';
            $wpgv_expiry_date_format = get_option('wpgv_expiry_date_format') ? get_option('wpgv_expiry_date_format') : 'd.m.Y';
            $voucher_expiry_value = !empty(get_post_meta($template_id, 'wpgv_customize_template_voucher_expiry_value', true))
                ? get_post_meta($template_id, 'wpgv_customize_template_voucher_expiry_value', true)
                : (isset($options->voucher_expiry) ? $options->voucher_expiry : '365');

            if ($wpgv_hide_expiry == 'no') {
                $expiryDate = __('No Expiration', 'gift-voucher');
            } else {
                $voucher_expiry_type = isset($options->voucher_expiry_type) ? $options->voucher_expiry_type : 'days';
                $expiryDate = ($voucher_expiry_type == 'days')
                    ? date($wpgv_expiry_date_format, strtotime('+' . $voucher_expiry_value . ' days', time()))
                    : $voucher_expiry_value;
            }

            $wpgv_leftside_notice = (get_option('wpgv_leftside_notice') != '')
                ? get_option('wpgv_leftside_notice')
                : __('Cash payment is not possible. The terms and conditions apply.', 'gift-voucher');

            $logo = get_option("wpgv_company_logo");
            $template_price = get_post_meta($template_id, 'wpgv_customize_template_voucher_price_frontend', true);

            // Get WooCommerce currency settings
            $wc_currency = function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'USD';
            $wc_currency_symbol = function_exists('get_woocommerce_currency_symbol') ? get_woocommerce_currency_symbol() : '$';
            $wc_currency_pos = get_option('woocommerce_currency_pos', 'left');

            // Determine orientation
            $is_landscape = (strpos($selected_voucher_template, 'lanscape') !== false || $choose_template == 'lanscape');

            $result = array(
                'url' => $images_template,
                'json' => $json,
                'currency' => $wc_currency,
                'currency_symbol' => $wc_currency_symbol,
                'currency_position' => $wc_currency_pos,
                'giftto' => $giftto,
                'giftfrom' => $giftfrom,
                'date_of' => $date_of,
                'company_logo' => $logo,
                'company_name' => isset($options->company_name) ? $options->company_name : '',
                'value_text' => $value_text,
                'email' => isset($options->pdf_footer_email) ? $options->pdf_footer_email : '',
                'web' => isset($options->pdf_footer_url) ? $options->pdf_footer_url : '',
                'leftside_notice' => $wpgv_leftside_notice,
                'expiryDate' => $expiryDate,
                'counpon' => $counpon,
                'price_fe' => !empty($template_price) ? floatval($template_price) : 0,
                'is_landscape' => $is_landscape,
                'template_style' => $selected_voucher_template,
            );

            wp_send_json_success($result);
        } catch (Exception $e) {
            error_log('WPGV ajax_get_template_data error: ' . $e->getMessage());
            error_log('Stack trace: ' . $e->getTraceAsString());
            wp_send_json_error(array('message' => 'Error loading template: ' . $e->getMessage()));
        }
    }

    /**
     * AJAX handler to save canvas image data
     */
    public function ajax_save_canvas_image()
    {
        check_ajax_referer('wpgv_product_gift_nonce', 'nonce');

        $canvas_data = isset($_POST['canvas_data']) ? $_POST['canvas_data'] : '';
        $cart_item_key = isset($_POST['cart_item_key']) ? sanitize_text_field($_POST['cart_item_key']) : '';

        if (empty($canvas_data) || empty($cart_item_key)) {
            wp_send_json_error(array('message' => 'Invalid canvas data or cart item key'));
            return;
        }

        // Save canvas data to transient (expires in 24 hours)
        set_transient('wpgv_canvas_' . $cart_item_key, $canvas_data, DAY_IN_SECONDS);

        wp_send_json_success(array('message' => 'Canvas saved successfully'));
    }

    /**
     * AJAX handler to generate preview coupon code
     * Returns a temporary coupon code for display in template preview
     */
    public function ajax_generate_preview_coupon()
    {
        check_ajax_referer('wpgv_product_gift_nonce', 'nonce');

        global $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $voucher_table = $wpdb->prefix . 'giftvouchers_list';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        // Generate preview coupon code using same logic as real vouchers
        $coupon_type = isset($options->voucher_coupon_type) ? $options->voucher_coupon_type : 'random';
        $coupon_length = isset($options->voucher_coupon_length) ? intval($options->voucher_coupon_length) : 12;

        $max_attempts = 10; // Prevent infinite loop
        $attempt = 0;
        $preview_code = '';

        do {
            $attempt++;

            if ($coupon_type === 'random') {
                // Generate random numeric coupon
                $preview_code = '';
                for ($i = 0; $i < $coupon_length; $i++) {
                    $preview_code .= rand(0, 9);
                }
            } else {
                // Incremental mode - reserve next number temporarily
                // Get current counter and increment it
                $current_number = get_option('wpgv_voucher_counter', isset($options->voucher_start_numbering) ? $options->voucher_start_numbering : '000000000001');

                // Increment for next voucher
                $next_number = strval(intval($current_number) + $attempt);

                // Format preview code
                $preview_code = str_pad($next_number, $coupon_length, '0', STR_PAD_LEFT);
            }

            // Check if code already exists
            $exists = $wpdb->get_var($wpdb->prepare(
                "SELECT COUNT(*) FROM $voucher_table WHERE couponcode = %s",
                $preview_code
            ));

            if (!$exists) {
                break; // Found unique code
            }

        } while ($attempt < $max_attempts);

        if ($attempt >= $max_attempts) {
            // Fallback: add timestamp to ensure uniqueness
            $preview_code = substr($preview_code, 0, -6) . substr(time(), -6);
        }

        error_log('WPGV DEBUG: Generated preview coupon code: ' . $preview_code . ' (Type: ' . $coupon_type . ', Length: ' . $coupon_length . ', Attempts: ' . $attempt . ')');

        wp_send_json_success(array(
            'coupon_code' => $preview_code,
            'type' => $coupon_type,
            'length' => $coupon_length
        ));
    }

    /**
     * AJAX handler to get templates filtered by orientation for settings page
     */
    public function ajax_get_checkbox_templates()
    {
        check_ajax_referer('wpgv_checkbox_settings_nonce', 'nonce');

        $orientation = isset($_POST['orientation']) ? sanitize_text_field($_POST['orientation']) : 'all';

        $args = array(
            'post_type' => 'voucher_template',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC',
            'meta_query' => array(
                'relation' => 'AND',
                array(
                    'key' => 'wpgv_customize_template_status',
                    'value' => 'active',
                    'compare' => '='
                )
            )
        );

        // Don't filter by orientation in WP_Query - we'll filter in PHP instead
        // This is because some templates might not have the meta key set

        $query = new WP_Query($args);
        $templates = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $post_id = get_the_ID();

                // Get orientation meta value
                $template_orientation = get_post_meta($post_id, 'wpgv_customize_template_chosse_template', true);

                // Determine if this template matches the requested orientation
                $include_template = false;

                if ($orientation === 'all') {
                    $include_template = true;
                } elseif ($orientation === 'portrait') {
                    // Portrait: empty value, 'portrait', or anything that's not landscape variants
                    if (empty($template_orientation) ||
                        $template_orientation === 'portrait' ||
                        ($template_orientation !== 'landscape' && $template_orientation !== 'lanscape')) {
                        $include_template = true;
                    }
                } elseif ($orientation === 'landscape') {
                    // Landscape: 'landscape' or 'lanscape' (typo)
                    if ($template_orientation === 'landscape' || $template_orientation === 'lanscape') {
                        $include_template = true;
                    }
                }

                if ($include_template) {
                    $templates[] = array(
                        'id' => $post_id,
                        'title' => get_the_title()
                    );
                }
            }
            wp_reset_postdata();
        }

        wp_send_json_success($templates);
    }

    /**
     * AJAX handler to get products for checkbox feature (excludes gift voucher products)
     */
    public function ajax_get_checkbox_products()
    {
        check_ajax_referer('wpgv_checkbox_settings_nonce', 'nonce');

        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'orderby' => 'title',
            'order' => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_type',
                    'field' => 'slug',
                    'terms' => 'gift_voucher',
                    'operator' => 'NOT IN'
                )
            )
        );

        $query = new WP_Query($args);
        $products = array();

        if ($query->have_posts()) {
            while ($query->have_posts()) {
                $query->the_post();
                $products[] = array(
                    'id' => get_the_ID(),
                    'title' => get_the_title()
                );
            }
            wp_reset_postdata();
        }

        wp_send_json_success($products);
    }

    /**
     * Add gift voucher data to cart item
     */
    public function add_gift_voucher_data_to_cart($cart_item_data, $product_id, $variation_id)
    {
        if (isset($_POST['wpgv_add_gift_voucher']) && $_POST['wpgv_add_gift_voucher'] === 'yes') {

            // Validate required fields
            if (
                empty($_POST['wpgv_selected_template_id']) ||
                empty($_POST['wpgv_your_name']) ||
                empty($_POST['wpgv_recipient_name']) ||
                empty($_POST['wpgv_recipient_email']) ||
                empty($_POST['wpgv_your_email'])
            ) {
                wc_add_notice(__('Please fill in all required gift card fields', 'gift-voucher'), 'error');
                return $cart_item_data;
            }

            $cart_item_data['wpgv_has_gift_voucher'] = true;
            $cart_item_data['wpgv_template_id'] = sanitize_text_field($_POST['wpgv_selected_template_id']);
            $cart_item_data['wpgv_your_name'] = sanitize_text_field($_POST['wpgv_your_name']);
            $cart_item_data['wpgv_recipient_name'] = sanitize_text_field($_POST['wpgv_recipient_name']);
            $cart_item_data['wpgv_recipient_email'] = sanitize_email($_POST['wpgv_recipient_email']);
            $cart_item_data['wpgv_your_email'] = sanitize_email($_POST['wpgv_your_email']);
            $cart_item_data['wpgv_personal_message'] = isset($_POST['wpgv_personal_message']) ? sanitize_textarea_field($_POST['wpgv_personal_message']) : '';

            // Save preview coupon code if provided (for display in canvas)
            if (isset($_POST['wpgv_preview_coupon_code']) && !empty($_POST['wpgv_preview_coupon_code'])) {
                $cart_item_data['wpgv_preview_coupon_code'] = sanitize_text_field($_POST['wpgv_preview_coupon_code']);
            }

            // Save canvas data to temporary file instead of storing base64 in database
            if (isset($_POST['wpgv_canvas_data']) && !empty($_POST['wpgv_canvas_data'])) {
                $canvas_data = $_POST['wpgv_canvas_data'];
                // Save to temp file and store only filename
                $temp_filename = $this->save_canvas_to_temp_file($canvas_data);
                if ($temp_filename) {
                    $cart_item_data['wpgv_canvas_temp_file'] = $temp_filename;
                    error_log('WPGV: Canvas temp file saved for cart: ' . $temp_filename);
                } else {
                    error_log('WPGV: Failed to save canvas to temp file');
                }
            }

            // Store original product price and template price for display
            // IMPORTANT: Prioritize variation_id to get correct variation price, not parent product price
            $product = wc_get_product($variation_id ? $variation_id : $product_id);
            if ($product) {
                $cart_item_data['wpgv_original_product_price'] = floatval($product->get_price());
                $cart_item_data['wpgv_product_regular_price'] = floatval($product->get_regular_price());
                $cart_item_data['wpgv_product_sale_price'] = $product->is_on_sale() ? floatval($product->get_sale_price()) : 0;

                $template_id = sanitize_text_field($_POST['wpgv_selected_template_id']);
                $template_price = get_post_meta($template_id, 'wpgv_customize_template_voucher_price_frontend', true);
                $cart_item_data['wpgv_template_price'] = !empty($template_price) ? floatval($template_price) : 0;

                // Debug log to verify correct prices are being stored
                error_log('WPGV ADD TO CART - Product ID: ' . $product->get_id() . ', Price: ' . $cart_item_data['wpgv_original_product_price'] . ', Regular: ' . $cart_item_data['wpgv_product_regular_price'] . ', Sale: ' . $cart_item_data['wpgv_product_sale_price'] . ', Template: ' . $cart_item_data['wpgv_template_price']);
            }
        }

        return $cart_item_data;
    }

    /**
     * Adjust cart item price with gift voucher
     */
    public function adjust_cart_item_price_with_gift_voucher($cart)
    {
        if (is_admin() && !defined('DOING_AJAX')) {
            return;
        }

        foreach ($cart->get_cart() as $cart_item_key => $cart_item) {
            if (isset($cart_item['wpgv_has_gift_voucher']) && $cart_item['wpgv_has_gift_voucher']) {
                $template_id = $cart_item['wpgv_template_id'];
                $product = $cart_item['data'];
                // Use the original product price stored in cart item to avoid repeated adjustments
                if (isset($cart_item['wpgv_original_product_price'])) {
                    $product_price = floatval($cart_item['wpgv_original_product_price']);
                } else {
                    $product_price = floatval($product->get_price());
                }

                // Get template price
                $template_price = get_post_meta($template_id, 'wpgv_customize_template_voucher_price_frontend', true);

                if (!empty($template_price) && floatval($template_price) > 0) {
                    // Template has fixed price: product price + template price
                    $new_price = $product_price + floatval($template_price);
                } else {
                    // Template has no price: product price + product price (double)
                    $new_price = $product_price + $product_price;
                }

                $product->set_price($new_price);
            }
        }
    }

    /**
     * Display gift voucher data in cart
     */
    public function display_gift_voucher_data_in_cart($item_data, $cart_item)
    {
        if (isset($cart_item['wpgv_has_gift_voucher']) && $cart_item['wpgv_has_gift_voucher']) {
            $item_data[] = array(
                'name'  => __('Gift Card Included', 'gift-voucher'),
                'value' => __('Yes', 'gift-voucher')
            );

            // Display price breakdown
            if (isset($cart_item['wpgv_original_product_price'])) {
                $product_price = $cart_item['wpgv_original_product_price'];
                $template_price = isset($cart_item['wpgv_template_price']) ? $cart_item['wpgv_template_price'] : 0;
                $regular_price = isset($cart_item['wpgv_product_regular_price']) ? $cart_item['wpgv_product_regular_price'] : 0;
                $sale_price = isset($cart_item['wpgv_product_sale_price']) ? $cart_item['wpgv_product_sale_price'] : 0;

                // Product price display
                $product_price_display = '';
                if ($sale_price > 0 && $regular_price > $sale_price) {
                    // Product is on sale
                    $product_price_display = '<del style="color:#999;">' . wc_price($regular_price) . '</del> ';
                    $product_price_display .= '<ins style="text-decoration:none;color:#e2401c;font-weight:bold;">' . wc_price($sale_price) . '</ins> ';
                    $product_price_display .= '<span style="background:#e2401c;color:white;padding:2px 5px;font-size:10px;border-radius:2px;">SALE</span>';
                } else {
                    $product_price_display = wc_price($product_price);
                }

                $item_data[] = array(
                    'name'  => __('Product Price', 'gift-voucher'),
                    'value' => $product_price_display
                );

                // Template price display
                $template_price_display = '';
                if ($template_price > 0) {
                    $template_price_display = '<span style="color:#46b450;font-weight:bold;">+' . wc_price($template_price) . '</span>';
                } else {
                    $template_price_display = '<span style="color:#46b450;font-weight:bold;">+' . wc_price($product_price) . '</span>';
                    $template_price_display .= ' <span style="font-size:11px;color:#666;">(same as product)</span>';
                }

                $item_data[] = array(
                    'name'  => __('Gift Card Price', 'gift-voucher'),
                    'value' => $template_price_display
                );
            }

            $item_data[] = array(
                'name'  => __('Your Name', 'gift-voucher'),
                'value' => $cart_item['wpgv_your_name']
            );

            $item_data[] = array(
                'name'  => __('Recipient Name', 'gift-voucher'),
                'value' => $cart_item['wpgv_recipient_name']
            );

            $item_data[] = array(
                'name'  => __('Recipient Email', 'gift-voucher'),
                'value' => $cart_item['wpgv_recipient_email']
            );

            if (!empty($cart_item['wpgv_personal_message'])) {
                $item_data[] = array(
                    'name'  => __('Personal Message', 'gift-voucher'),
                    'value' => $cart_item['wpgv_personal_message']
                );
            }
        }

        return $item_data;
    }

    /**
     * Add gift voucher data to order items
     */
    public function add_gift_voucher_data_to_order_items($item, $cart_item_key, $values, $order)
    {
        if (isset($values['wpgv_has_gift_voucher']) && $values['wpgv_has_gift_voucher']) {
            // Machine meta (kept for internal logic)
            $item->add_meta_data('_wpgv_has_gift_voucher', 'yes', true);
            $item->add_meta_data('_wpgv_template_id', $values['wpgv_template_id'], true);
            $item->add_meta_data('_wpgv_your_name', $values['wpgv_your_name'], true);
            $item->add_meta_data('_wpgv_recipient_name', $values['wpgv_recipient_name'], true);
            $item->add_meta_data('_wpgv_recipient_email', $values['wpgv_recipient_email'], true);
            $item->add_meta_data('_wpgv_your_email', $values['wpgv_your_email'], true);
            $item->add_meta_data('_wpgv_personal_message', $values['wpgv_personal_message'], true);

            // Human-friendly meta for admin display (preserve originals above)
            $item->add_meta_data(__('Template ID', 'gift-voucher'), $values['wpgv_template_id'], true);
            $item->add_meta_data(__('Sender', 'gift-voucher'), $values['wpgv_your_name'], true);
            $item->add_meta_data(__('Recipient', 'gift-voucher'), $values['wpgv_recipient_name'], true);
            $item->add_meta_data(__('Recipient Email', 'gift-voucher'), $values['wpgv_recipient_email'], true);
            $item->add_meta_data(__('Buyer Email', 'gift-voucher'), $values['wpgv_your_email'], true);
            if (!empty($values['wpgv_personal_message'])) {
                $item->add_meta_data(__('Personal Message', 'gift-voucher'), $values['wpgv_personal_message'], true);
            }

            // Additional friendly meta for technical fields
            if (isset($values['wpgv_preview_coupon_code']) && !empty($values['wpgv_preview_coupon_code'])) {
                $item->add_meta_data(__('Preview Coupon Code', 'gift-voucher'), $values['wpgv_preview_coupon_code'], true);
            }

            if (isset($values['wpgv_canvas_temp_file']) && !empty($values['wpgv_canvas_temp_file'])) {
                $item->add_meta_data(__('Canvas Temp File', 'gift-voucher'), $values['wpgv_canvas_temp_file'], true);
            }

            if (isset($values['wpgv_original_product_price'])) {
                $item->add_meta_data(__('Original Product Price', 'gift-voucher'), wc_price($values['wpgv_original_product_price']), true);
            }

            if (isset($values['wpgv_product_regular_price'])) {
                $item->add_meta_data(__('Regular Price', 'gift-voucher'), wc_price($values['wpgv_product_regular_price']), true);
            }

            if (isset($values['wpgv_product_sale_price'])) {
                $item->add_meta_data(__('Sale Price', 'gift-voucher'), wc_price($values['wpgv_product_sale_price']), true);
            }

            if (isset($values['wpgv_template_price'])) {
                $tp = floatval($values['wpgv_template_price']);
                $item->add_meta_data(__('Template Price', 'gift-voucher'), $tp > 0 ? ('+' . wc_price($tp)) : __('(same as product)', 'gift-voucher'), true);
            }

            // Save preview coupon code if available
            if (isset($values['wpgv_preview_coupon_code']) && !empty($values['wpgv_preview_coupon_code'])) {
                $item->add_meta_data('_wpgv_preview_coupon_code', $values['wpgv_preview_coupon_code'], true);
            }

            // Save canvas temp filename instead of base64 data
            if (isset($values['wpgv_canvas_temp_file']) && !empty($values['wpgv_canvas_temp_file'])) {
                $item->add_meta_data('_wpgv_canvas_temp_file', $values['wpgv_canvas_temp_file'], true);
                error_log('WPGV: Canvas temp file saved to order item: ' . $values['wpgv_canvas_temp_file']);
            }

            // Add price breakdown for order display
            if (isset($values['wpgv_original_product_price'])) {
                $item->add_meta_data('_wpgv_original_product_price', $values['wpgv_original_product_price'], true);
                $item->add_meta_data('_wpgv_product_regular_price', $values['wpgv_product_regular_price'], true);
                $item->add_meta_data('_wpgv_product_sale_price', $values['wpgv_product_sale_price'], true);
                $item->add_meta_data('_wpgv_template_price', $values['wpgv_template_price'], true);

                // Add formatted display for admin
                $product_price = $values['wpgv_original_product_price'];
                $template_price = isset($values['wpgv_template_price']) ? $values['wpgv_template_price'] : 0;
                $regular_price = isset($values['wpgv_product_regular_price']) ? $values['wpgv_product_regular_price'] : 0;
                $sale_price = isset($values['wpgv_product_sale_price']) ? $values['wpgv_product_sale_price'] : 0;

                // Product price display
                $product_price_display = '';
                if ($sale_price > 0 && $regular_price > $sale_price) {
                    $product_price_display = wc_price($regular_price) . ' → ' . wc_price($sale_price) . ' (SALE)';
                } else {
                    $product_price_display = wc_price($product_price);
                }

                $item->add_meta_data(__('Product Price', 'gift-voucher'), $product_price_display, true);

                // Template price display
                if ($template_price > 0) {
                    $item->add_meta_data(__('Gift Card Price', 'gift-voucher'), '+' . wc_price($template_price), true);
                } else {
                    $item->add_meta_data(__('Gift Card Price', 'gift-voucher'), '+' . wc_price($product_price) . ' (same as product)', true);
                }
            }
        }
    }

    /**
     * Create gift voucher when order is created (before payment)
     * This is called by woocommerce_new_order or woocommerce_checkout_order_processed
     */
    public function create_gift_voucher_on_new_order($order_id)
    {
        // Get order object
        $order = wc_get_order($order_id);
        if (!$order) {
            error_log('WPGV ERROR: Order not found for ID: ' . $order_id);
            return;
        }

        error_log('WPGV DEBUG: create_gift_voucher_on_new_order for Order #' . $order_id);

        // Check if already processed (prevent duplicate calls from multiple hooks)
        $processed = $order->get_meta('_wpgv_vouchers_created', true);
        if ($processed) {
            error_log('WPGV DEBUG: Vouchers already created for Order #' . $order_id);
            return;
        }

        global $wpdb;
        $voucher_table = $wpdb->prefix . 'giftvouchers_list';
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        $voucher_ids = array();

        foreach ($order->get_items() as $item_id => $item) {
            $has_gift_voucher = $item->get_meta('_wpgv_has_gift_voucher');

            if ($has_gift_voucher === 'yes') {
                $template_id = $item->get_meta('_wpgv_template_id');
                $your_name = $item->get_meta('_wpgv_your_name');
                $recipient_name = $item->get_meta('_wpgv_recipient_name');
                $recipient_email = $item->get_meta('_wpgv_recipient_email');
                $your_email = $item->get_meta('_wpgv_your_email');
                $personal_message = $item->get_meta('_wpgv_personal_message');

                $product = $item->get_product();
                $product_id = $product->get_id();

                // Determine voucher amount
                $template_price = get_post_meta($template_id, 'wpgv_customize_template_voucher_price_frontend', true);
                if (!empty($template_price) && floatval($template_price) > 0) {
                    $amount = floatval($template_price);
                } else {
                    $amount = floatval($product->get_price());
                }

                // Use preview coupon code if available (to match what was shown to customer in canvas)
                $preview_coupon_code = $item->get_meta('_wpgv_preview_coupon_code');

                if (!empty($preview_coupon_code)) {
                    // Verify preview code is unique (not already used)
                    $existing = $wpdb->get_var($wpdb->prepare(
                        "SELECT id FROM $voucher_table WHERE couponcode = %s",
                        $preview_coupon_code
                    ));

                    if ($existing) {
                        // Preview code already used, generate new one
                        error_log('WPGV WARNING: Preview coupon code already exists, generating new code');
                        $voucher_code = $this->generate_voucher_code();
                    } else {
                        // Use preview code
                        $voucher_code = $preview_coupon_code;
                        error_log('WPGV DEBUG: Using preview coupon code: ' . $voucher_code);
                    }
                } else {
                    // No preview code, generate new one
                    $voucher_code = $this->generate_voucher_code();
                }

                // Calculate expiry date
                $expiry_date = $this->calculate_expiry_date($template_id, $options);

                // Insert voucher with 'Not Paid' status
                $insert_result = $wpdb->insert(
                    $voucher_table,
                    array(
                        'order_type' => 'gift_voucher_product',
                        'order_id' => $order_id,
                        'template_id' => $template_id,
                        'product_id' => $product_id,
                        'buying_for' => 'someone_else',
                        'from_name' => $your_name,
                        'to_name' => $recipient_name,
                        'shipping_email' => $recipient_email,
                        'email' => $your_email,
                        'amount' => $amount,
                        'couponcode' => $voucher_code,
                        'message' => $personal_message,
                        'shipping_type' => 'shipping_as_email',
                        'shipping_method' => 'Email',
                        'pay_method' => $order->get_payment_method(),
                        'payment_status' => 'Not Paid',
                        'expiry' => $expiry_date,
                        'status' => 'unused',
                        'check_send_mail' => 'unsent',
                        'voucherpdf_link' => '',
                    ),
                    array('%s', '%d', '%d', '%d', '%s', '%s', '%s', '%s', '%s', '%f', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
                );

                if ($insert_result === false) {
                    error_log('WPGV ERROR: Failed to insert voucher. Error: ' . $wpdb->last_error);
                    continue;
                }

                $voucher_id = $wpdb->insert_id;
                error_log('WPGV DEBUG: Voucher created with ID: ' . $voucher_id . ', Code: ' . $voucher_code . ', Status: Not Paid');

                // Create activity records
                if ($voucher_id) {
                    $create_note = sprintf(__('Gift voucher created from order #%d (payment pending). Recipient: %s', 'gift-voucher'), $order_id, $recipient_name);
                    WPGV_Gift_Voucher_Activity::record($voucher_id, 'create', '', $create_note, $order_id);

                    $firsttransact_note = sprintf(__('Initial voucher value from order #%d (pending payment)', 'gift-voucher'), $order_id);
                    WPGV_Gift_Voucher_Activity::record($voucher_id, 'firsttransact', $amount, $firsttransact_note, $order_id);
                }

                // Update order item meta with voucher info
                $item->update_meta_data('_wpgv_voucher_code', $voucher_code);
                $item->update_meta_data('_wpgv_voucher_id', $voucher_id);
                $item->save_meta_data();

                // Also add human-friendly voucher meta for admin display
                try {
                    $item->update_meta_data(__('Voucher Code', 'gift-voucher'), $voucher_code, true);
                    $item->update_meta_data(__('Voucher ID', 'gift-voucher'), $voucher_id, true);
                    $item->save_meta_data();
                } catch (Exception $e) {
                    error_log('WPGV WARNING: Failed to save friendly voucher meta: ' . $e->getMessage());
                }

                // Reload item to ensure meta is saved
                $item = WC_Order_Factory::get_order_item($item_id);

                // Get canvas temp filename from order item
                $canvas_temp_file = $item->get_meta('_wpgv_canvas_temp_file');
                $canvas_data = null;

                if (!empty($canvas_temp_file)) {
                    // Load canvas from temp file
                    $canvas_data = $this->get_canvas_from_temp_file($canvas_temp_file);
                    if ($canvas_data) {
                        error_log('WPGV DEBUG: Canvas data loaded from temp file for item #' . $item_id . ', length: ' . strlen($canvas_data));
                    } else {
                        error_log('WPGV DEBUG: Failed to load canvas from temp file: ' . $canvas_temp_file);
                    }
                } else {
                    error_log('WPGV DEBUG: No canvas temp file found for item #' . $item_id);
                }

                // Generate PDF immediately (from canvas + voucher data)
                // Pass temp filename so it can be deleted after PDF generation
                $this->generate_voucher_pdf($voucher_id, $template_id, $canvas_data, $canvas_temp_file);

                $voucher_ids[] = $voucher_id;
            }
        }

        // Mark as processed
        if (!empty($voucher_ids)) {
            $order->update_meta_data('_wpgv_vouchers_created', 'yes');
            $order->update_meta_data('_wpgv_voucher_ids', $voucher_ids);
            $order->save();
            error_log('WPGV DEBUG: Created ' . count($voucher_ids) . ' vouchers for Order #' . $order_id);
        }
    }

    /**
     * Process gift voucher on payment complete
     */
    public function process_gift_voucher_on_payment_complete($order_id)
    {
        $this->update_voucher_payment_status($order_id);
    }

    /**
     * Process gift voucher on order complete
     */
    public function process_gift_voucher_on_order_complete($order_id, $order)
    {
        $this->update_voucher_payment_status($order_id);
    }

    /**
     * Update voucher payment status and send emails when payment is complete
     */
    private function update_voucher_payment_status($order_id)
    {
        global $wpdb;

        error_log('WPGV DEBUG: update_voucher_payment_status for Order #' . $order_id);

        $order = wc_get_order($order_id);

        if (!$order) {
            error_log('WPGV ERROR: Order not found');
            return;
        }

        // Check if already sent emails
        $emails_sent = $order->get_meta('_wpgv_emails_sent', true);
        if ($emails_sent) {
            error_log('WPGV DEBUG: Emails already sent for Order #' . $order_id);
            return;
        }

        // Get voucher IDs from order meta
        $voucher_ids = $order->get_meta('_wpgv_voucher_ids', true);
        if (empty($voucher_ids)) {
            error_log('WPGV DEBUG: No vouchers found for Order #' . $order_id);
            return;
        }

        $voucher_table = $wpdb->prefix . 'giftvouchers_list';
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';

        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");
        $invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");

        foreach ($voucher_ids as $voucher_id) {
            // Update payment status to 'Paid'
            $update_result = $wpdb->update(
                $voucher_table,
                array('payment_status' => 'Paid'),
                array('id' => $voucher_id),
                array('%s'),
                array('%d')
            );

            if ($update_result === false) {
                error_log('WPGV ERROR: Failed to update payment status for voucher #' . $voucher_id);
                continue;
            }

            error_log('WPGV DEBUG: Updated voucher #' . $voucher_id . ' payment status to Paid');

            // Get voucher data
            $voucher_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM $voucher_table WHERE id = %d", $voucher_id));
            if (!$voucher_data) {
                error_log('WPGV ERROR: Voucher data not found for ID: ' . $voucher_id);
                continue;
            }

            // Verify PDF exists (email template contains download link)
            $upload = wp_upload_dir();
            $upload_dir = $upload['basedir'] . '/voucherpdfuploads/';
            $pdf_file = $upload_dir . $voucher_data->voucherpdf_link . '.pdf';

            if (!file_exists($pdf_file)) {
                error_log('WPGV ERROR: PDF file not found: ' . $pdf_file);
                continue;
            }

            // Send emails (no attachments - email templates contain download links)
            // WooCommerce already sends admin notification, so we only send to recipient and buyer
            $this->send_voucher_email($voucher_data, 'recipient');
            $this->send_voucher_email($voucher_data, 'buyer');

            // Update check_send_mail status
            $wpdb->update(
                $voucher_table,
                array('check_send_mail' => 'sent'),
                array('id' => $voucher_id),
                array('%s'),
                array('%d')
            );

            error_log('WPGV DEBUG: Email workflow completed for voucher #' . $voucher_id);
        }

        // Mark emails as sent
        $order->update_meta_data('_wpgv_emails_sent', 'yes');
        $order->save();
        error_log('WPGV DEBUG: Completed payment processing for Order #' . $order_id);
    }

    /**
     * Generate voucher code (always numeric)
     */
    private function generate_voucher_code()
    {
        $wpgv_coupon_code_type = get_option('wpgv_coupon_code_type') ? get_option('wpgv_coupon_code_type') : '';
        $coupon_code_length = get_option('wpgv_coupon_code_length') ? get_option('wpgv_coupon_code_length') : 12;

        if ($wpgv_coupon_code_type == 'sequential' || $wpgv_coupon_code_type == 'incremental') {
            // Sequential/Incremental - use padded number
            $wpgv_current_coupon_number = get_option('wpgv_current_coupon_number') ? get_option('wpgv_current_coupon_number') : 1;
            $code = str_pad($wpgv_current_coupon_number, $coupon_code_length, '0', STR_PAD_LEFT);
            update_option('wpgv_current_coupon_number', $wpgv_current_coupon_number + 1);
        } else {
            // Random - generate numeric only code
            $code = '';
            for ($i = 0; $i < $coupon_code_length; $i++) {
                $code .= rand(0, 9);
            }
        }

        error_log('WPGV DEBUG: Generated numeric coupon code: ' . $code . ' (Type: ' . $wpgv_coupon_code_type . ', Length: ' . $coupon_code_length . ')');

        return $code;
    }

    /**
     * Calculate expiry date
     */
    private function calculate_expiry_date($template_id, $options)
    {
        $voucher_expiry_value = get_post_meta($template_id, 'wpgv_customize_template_voucher_expiry_value', true);
        if (!$voucher_expiry_value) {
            $voucher_expiry_value = $options->voucher_expiry;
        }

        if ($options->voucher_expiry_type == 'days') {
            return date('Y-m-d', strtotime('+' . $voucher_expiry_value . ' days'));
        } else {
            return $voucher_expiry_value;
        }
    }

    /**
     * Generate voucher PDF (from canvas base64 + voucher data)
     * @param int $voucher_id Voucher ID
     * @param int $template_id Template ID
     * @param string|null $canvas_data Canvas base64 data
     * @param string|null $canvas_temp_file Temp filename to delete after PDF generation
     */
    private function generate_voucher_pdf($voucher_id, $template_id, $canvas_data = null, $canvas_temp_file = null)
    {
        global $wpdb;

        error_log('WPGV DEBUG: generate_voucher_pdf called for voucher ID: ' . $voucher_id);

        $voucher_table = $wpdb->prefix . 'giftvouchers_list';
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $invoice_setting_table = $wpdb->prefix . 'giftvouchers_invoice_settings';

        $voucher_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM $voucher_table WHERE id = %d", $voucher_id));
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");
        $invoice_options = $wpdb->get_row("SELECT * FROM $invoice_setting_table WHERE id = 1");

        if (!$voucher_data) {
            error_log('WPGV ERROR: Voucher data not found for ID: ' . $voucher_id);
            return;
        }

        error_log('WPGV DEBUG: Voucher data loaded. Coupon code: ' . $voucher_data->couponcode);

        // Generate main voucher PDF (use canvas base64 + overlay real coupon code)
        require_once(WPGIFT__PLUGIN_DIR . '/include/wpgv_giftcard_modern_pdf_helpers.php');

        if (!empty($canvas_data)) {
            error_log('WPGV DEBUG: Using canvas data from frontend (will overlay real coupon code)');
        } else {
            error_log('WPGV DEBUG: No canvas data, using fallback PDF generation');
        }

        // Pass canvas data (with XXXXX placeholder) and real voucher data
        // PDF generator will overlay real coupon code at correct position from JSON
        $pdf_file = wpgv_generate_modern_giftcard_pdf($voucher_id, $voucher_data, $template_id, $canvas_data);

        if (!$pdf_file || !file_exists($pdf_file)) {
            error_log('WPGV ERROR: Failed to generate PDF for voucher ID ' . $voucher_id);
            // Delete temp file even if PDF generation failed
            if (!empty($canvas_temp_file)) {
                $this->delete_canvas_temp_file($canvas_temp_file);
            }
            return;
        }

        error_log('WPGV DEBUG: PDF generated successfully: ' . $pdf_file);

        // Delete canvas temp file immediately after successful PDF generation
        if (!empty($canvas_temp_file)) {
            $this->delete_canvas_temp_file($canvas_temp_file);
        }

        // WooCommerce orders only need main voucher PDF
        // Receipt and invoice are handled by WooCommerce itself
        error_log('WPGV DEBUG: PDF generation complete for voucher #' . $voucher_id . ' (WooCommerce order - no receipt/invoice)');
    }

    /**
     * Send voucher email (synchronized with shortcode email workflow)
     * No attachments - email templates contain download links
     */
    private function send_voucher_email($voucher_data, $recipient_type = 'recipient')
    {
        global $wpdb;
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        if (!$options) {
            error_log('WPGV ERROR: Email settings not found');
            return false;
        }

        // Get email settings using helper function (same as shortcode)
        $email_settings = wpgv_get_email_settings();

        // Setup email headers using helper function
        $headers = wpgv_setup_email_headers($options);

        if ($recipient_type == 'recipient') {
            $to = stripslashes($voucher_data->to_name) . ' <' . $voucher_data->shipping_email . '>';
            $subject = wpgv_mailvarstr($email_settings['recipientemailsubject'], $options, $voucher_data);
            $message = wpgv_mailvarstr($email_settings['recipientemailbody'], $options, $voucher_data);

            error_log('WPGV DEBUG: Sending recipient email - To: ' . $voucher_data->shipping_email);

            // Send recipient email immediately (no attachments - link in email template)
            $email_sent = wp_mail($to, $subject, $message, $headers);

        } else {
            $to = $voucher_data->email;
            $subject = wpgv_mailvarstr($email_settings['emailsubject'], $options, $voucher_data);
            $message = wpgv_mailvarstr($email_settings['emailbody'], $options, $voucher_data);

            error_log('WPGV DEBUG: Sending buyer email - To: ' . $to);

            // Send buyer email immediately (no attachments - link in email template)
            $email_sent = wp_mail($to, $subject, $message, $headers);
        }

        if ($email_sent) {
            error_log('WPGV DEBUG: Email sent successfully to ' . $to);
        } else {
            error_log('WPGV ERROR: Failed to send email to ' . $to);
        }

        return $email_sent;
    }
}

// Initialize the class
new WPGV_Product_Page_Gift_Checkbox();

/**
 * Backwards-compatible AJAX endpoints for settings page.
 * These are registered unconditionally so the admin settings UI
 * can load templates/products even when the product-page gift
 * checkbox feature is not yet enabled/saved.
 */
add_action('wp_ajax_wpgv_get_checkbox_templates', 'wpgv_ajax_get_checkbox_templates');
add_action('wp_ajax_nopriv_wpgv_get_checkbox_templates', 'wpgv_ajax_get_checkbox_templates');
function wpgv_ajax_get_checkbox_templates()
{
    check_ajax_referer('wpgv_checkbox_settings_nonce', 'nonce');

    $orientation = isset($_POST['orientation']) ? sanitize_text_field($_POST['orientation']) : 'all';

    $args = array(
        'post_type' => 'voucher_template',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC',
        'meta_query' => array(
            'relation' => 'AND',
            array(
                'key' => 'wpgv_customize_template_status',
                'value' => 'active',
                'compare' => '='
            )
        )
    );

    $query = new WP_Query($args);
    $templates = array();

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();

            $template_orientation = get_post_meta($post_id, 'wpgv_customize_template_chosse_template', true);

            $include_template = false;
            if ($orientation === 'all') {
                $include_template = true;
            } elseif ($orientation === 'portrait') {
                if (empty($template_orientation) || $template_orientation === 'portrait' || ($template_orientation !== 'landscape' && $template_orientation !== 'lanscape')) {
                    $include_template = true;
                }
            } elseif ($orientation === 'landscape') {
                if ($template_orientation === 'landscape' || $template_orientation === 'lanscape') {
                    $include_template = true;
                }
            }

            if ($include_template) {
                $templates[] = array(
                    'id' => $post_id,
                    'title' => get_the_title()
                );
            }
        }
        wp_reset_postdata();
    }

    wp_send_json_success($templates);
}

add_action('wp_ajax_wpgv_get_checkbox_products', 'wpgv_ajax_get_checkbox_products');
add_action('wp_ajax_nopriv_wpgv_get_checkbox_products', 'wpgv_ajax_get_checkbox_products');
function wpgv_ajax_get_checkbox_products()
{
    check_ajax_referer('wpgv_checkbox_settings_nonce', 'nonce');

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'post_status' => 'publish',
        'orderby' => 'title',
        'order' => 'ASC',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field' => 'slug',
                'terms' => 'gift_voucher',
                'operator' => 'NOT IN'
            )
        )
    );

    $query = new WP_Query($args);
    $products = array();

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            $products[] = array(
                'id' => get_the_ID(),
                'title' => get_the_title()
            );
        }
        wp_reset_postdata();
    }

    wp_send_json_success($products);
}
