(function ($) {

    function fixElementorTimeField() {

        const field = document.querySelector('[name="form_fields[field_0d60bf7]"]');
        if (!field) return;

        // Elementor already initialized flatpickr → destroy it
        if (field._flatpickr) {
            field._flatpickr.destroy();
        }

        // Re-init with AM/PM display
        flatpickr(field, {
            enableTime: true,
            noCalendar: true,
            time_24hr: false,

            altInput: true,
            altFormat: "h K",     // ✅ 8 PM, 9 PM
            dateFormat: "H:i",   // backend safe

            allowInput: true
        });
    }

    // Elementor frontend hook
    $(window).on('elementor/frontend/init', function () {

        elementorFrontend.hooks.addAction(
            'frontend/element_ready/form.default',
            function () {
                setTimeout(fixElementorTimeField, 300);
            }
        );

    });

})(jQuery);

				
			
				
					add_action( 'template_redirect', 'tiki_madman_force_login_before_checkout' );

function tiki_madman_force_login_before_checkout() {
    if ( is_page( wc_get_page_id( 'checkout' ) ) && ! is_user_logged_in() ) {
        // Optional notice (may not show if your login page doesn't support WooCommerce notices)
        wc_add_notice( 'You must be logged in to checkout. Please login or register first.', 'error' );

        // Redirect to your custom login page
        wp_redirect( 'https://asonvincent.webworkscraft.com/?page_id=1097' );
        exit;
    }
}

				
			
				
					// === 1. Output product name and quantity (normal) ===
// Move "Remove" button to the subtotal/price column (after price)
add_filter('woocommerce_checkout_cart_item_quantity', function ($quantity_html, $cart_item, $cart_item_key) {
    if (is_checkout()) {
        $product_name = $cart_item['data']->get_name();
        $product_qty  = $cart_item['quantity'];
        return esc_html($product_name) . '&nbsp;<strong class="product-quantity">×&nbsp;' . $product_qty . '</strong>';
    }
    return $quantity_html;
}, 10, 3);

// === 2. Add Remove Button After Price in Checkout Row ===
add_filter('woocommerce_cart_item_subtotal', function ($subtotal, $cart_item, $cart_item_key) {
    if (is_checkout()) {
        $remove_button = '<button class="checkout-remove-item" data-cart-key="' . esc_attr($cart_item_key) . '" title="Remove" style="margin-left:10px; color:red; background:none; border:none; cursor:pointer;">&#10006;</button>';
        return $subtotal . $remove_button;
    }
    return $subtotal;
}, 10, 3);

// === 3. Handle AJAX Request to Remove Cart Item ===
add_action('wp_ajax_remove_checkout_item', 'ajax_remove_checkout_item');
add_action('wp_ajax_nopriv_remove_checkout_item', 'ajax_remove_checkout_item');

function ajax_remove_checkout_item() {
    if (empty($_POST['cart_key'])) {
        wp_send_json_error('Missing cart key.');
    }

    $cart_key = sanitize_text_field($_POST['cart_key']);

    if (WC()->cart->remove_cart_item($cart_key)) {
        WC()->cart->calculate_totals();
        wp_send_json_success('Item removed.');
    } else {
        wp_send_json_error('Failed to remove item.');
    }
}

// === 4. Enqueue Inline JS for AJAX Remove ===
add_action('wp_enqueue_scripts', function () {
    if (is_checkout()) {
        wp_add_inline_script('woocommerce', <<<JS
        jQuery(function($) {
            $('body').on('click', '.checkout-remove-item', function(e) {
                e.preventDefault();
                const cartKey = $(this).data('cart-key');

                $.post(wc_checkout_params.ajax_url, {
                    action: 'remove_checkout_item',
                    cart_key: cartKey
                }, function(response) {
                    if (response.success) {
                        $('body').trigger('update_checkout');
                    } else {
                        alert('Failed to remove item.');
                    }
                });
            });
        });
        JS);
    }
});

				
			
				
					// Add Dashboard Widget
function custom_dashboard_widget() {
    wp_add_dashboard_widget('custom_dashboard_widget', 'Manage PDF Shortcodes', 'custom_dashboard_widget_display');
}
add_action('wp_dashboard_setup', 'custom_dashboard_widget');

// Display Dashboard Widget Form
function custom_dashboard_widget_display() {
    $pdf_shortcodes = get_option('custom_pdf_shortcodes', []);

    // Handle form submission for adding/editing shortcodes
    if (isset($_POST['submit_pdf_shortcode']) && check_admin_referer('pdf_shortcode_nonce')) {
        $index = isset($_POST['index']) ? intval($_POST['index']) : -1;
        $action = sanitize_text_field($_POST['pdf_action']);
        $title = sanitize_text_field($_POST['pdf_title']);
        $meta_field = sanitize_text_field($_POST['pdf_meta_field']);
        $shortcode_name = $action . '_' . $meta_field;

        $shortcode_data = ['action' => $action, 'title' => $title, 'meta_field' => $meta_field, 'shortcode_name' => $shortcode_name];

        if ($index >= 0 && isset($pdf_shortcodes[$index])) {
            $pdf_shortcodes[$index] = $shortcode_data;
        } else {
            array_unshift($pdf_shortcodes, $shortcode_data);
        }

        update_option('custom_pdf_shortcodes', $pdf_shortcodes);
    }

    // Handle remove requests
    if (isset($_POST['remove_pdf_shortcode']) && check_admin_referer('pdf_shortcode_nonce')) {
        $index = isset($_POST['index']) ? intval($_POST['index']) : -1;
        if ($index >= 0 && isset($pdf_shortcodes[$index])) {
            array_splice($pdf_shortcodes, $index, 1);
            update_option('custom_pdf_shortcodes', $pdf_shortcodes);
        }
    }

    // Handle edit requests
    $edit_index = -1;
    if (isset($_POST['edit_pdf_shortcode'])) {
        $edit_index = isset($_POST['index']) ? intval($_POST['index']) : -1;
    }

    // Display form for adding a new shortcode or editing an existing one
    $current_action = $edit_index >= 0 ? $pdf_shortcodes[$edit_index]['action'] : '';
    $current_title = $edit_index >= 0 ? $pdf_shortcodes[$edit_index]['title'] : '';
    $current_meta_field = $edit_index >= 0 ? $pdf_shortcodes[$edit_index]['meta_field'] : '';
    custom_pdf_shortcode_form($current_action, $current_title, $current_meta_field, $edit_index);

    // Display existing shortcodes
    echo '<h4>Existing Shortcodes:</h4>';
    echo '<ul style="list-style: none; padding: 0;">';
    foreach ($pdf_shortcodes as $index => $shortcode) {
        echo '<li style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">';
        echo ($index + 1) . '. Title: ' . esc_html($shortcode['title']) . ', Meta Field: ' . esc_html($shortcode['meta_field']) . '<br>';
        echo '<span style="margin-top: 15px; display: block;"><strong>Shortcode: [' . esc_attr($shortcode['shortcode_name']) . ']</strong></span>';
        echo '<form method="post" style="display:inline; margin-left: 0px;"><input type="hidden" name="index" value="' . esc_attr($index) . '">';
        echo '<input type="submit" name="edit_pdf_shortcode" value="Edit" style="margin-right: 5px; background-color: #0073aa; color: white; border: none; border-radius: 6px; padding: 5px 10px; margin-top: 10px;">';
        echo '<input type="submit" name="remove_pdf_shortcode" value="Remove" style="background-color: #dc3232; color: white; border: none; border-radius: 6px; padding: 5px 10px; margin-top: 10px;">';
        wp_nonce_field('pdf_shortcode_nonce');
        echo '</form>';
        echo '</li>';
    }
    echo '</ul>';

    // Display CSS class information
    echo '<div style="border: 2px dotted red; font-size: 16px; font-weight: 400; padding: 10px; margin-top: 20px; border-radius: 6px;">';
    echo '<strong>For styling, use the shortcode name as the CSS class.</strong><br>';
    echo 'Example: If the shortcode is [view_download_pdf], use .view_download_pdf as the CSS class.';
    echo '</div>';
}

// Form for adding/editing a shortcode
function custom_pdf_shortcode_form($action = '', $title = '', $meta_field = '', $index = -1) {
    ?>
    <form action="" method="post" style="margin-bottom: 20px;">
        <input type="hidden" name="index" value="<?php echo esc_attr($index); ?>">
        <p>
            <label for="pdf_action">Action (view/download):</label>
            <select id="pdf_action" name="pdf_action" style="width: 100%; padding: 5px; border-radius: 6px; border: 1px solid #ddd;">
                <option value="view" <?php selected($action, 'view'); ?>>View</option>
                <option value="download" <?php selected($action, 'download'); ?>>Download</option>
            </select>
        </p>
        <p>
            <label for="pdf_title">Title:</label>
            <input type="text" id="pdf_title" name="pdf_title" value="<?php echo esc_attr($title); ?>" style="width: 100%; padding: 5px; border-radius: 6px; border: 1px solid #ddd;">
        </p>
        <p>
            <label for="pdf_meta_field">Meta Field Name:</label>
            <input type="text" id="pdf_meta_field" name="pdf_meta_field" value="<?php echo esc_attr($meta_field); ?>" style="width: 100%; padding: 5px; border-radius: 6px; border: 1px solid #ddd;">
        </p>
        <?php
        wp_nonce_field('pdf_shortcode_nonce');
        ?>
        <input type="submit" name="submit_pdf_shortcode" value="<?php echo $index >= 0 ? 'Save Changes' : 'Add Shortcode'; ?>" style="background-color: #0073aa; color: white; border: none; border-radius: 6px; padding: 5px 10px;">
    </form>
    <?php
}

// Register Shortcodes
foreach (get_option('custom_pdf_shortcodes', []) as $shortcode) {
    add_shortcode($shortcode['shortcode_name'], function($atts) use ($shortcode) {
        return custom_pdf_shortcode_handler($shortcode['meta_field'], $shortcode['action'], $shortcode['title'], $shortcode['shortcode_name']);
    });
}

// Shortcode Handler
function custom_pdf_shortcode_handler($meta_field_name, $action, $title, $shortcode_name) {
    $post_id = get_the_ID();
    $file_id = get_post_meta($post_id, $meta_field_name, true);

    if (empty($file_id)) {
        return ''; // Return empty if no file ID
    }

    $file_url = wp_get_attachment_url($file_id);
    if (empty($file_url)) {
        return ''; // Return empty if no file URL
    }

    $link_text = !empty($title) ? $title : ucfirst($action) . ' PDF';
    $download_attr = $action === 'download' ? ' download' : '';
    $target_attr = $action === 'view' ? ' target="_blank"' : '';

    return "<a href='" . esc_url($file_url) . "' class='" . esc_attr($shortcode_name) . "'$download_attr$target_attr>$link_text</a>";
}
				
			
				
					/* Style for Download PDF link */
.Your Custom Class {
    color: #ffffff;
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
    background-color: #1D5D7C;
    border-radius: 8px;   
    padding: 10px 20px;        
    display: inline-block;
    transition: background-color 0.3s ease;
}

.Your Custom Class:hover {
    background-color: #C47A39;
    color: #ffffff;
}





/* Style for View PDF link */
.Your Custom Class {
    color: #ffffff;
    font-size: 12px;
    font-weight: 600;
    text-decoration: none;
    background-color: #C47A39;
    border-radius: 08px;   
    padding: 10px 20px;        
    display: inline-block;
    transition: background-color 0.3s ease;
}

.Your Custom Class:hover {
    background-color: #1D5D7C;
    color: #ffffff;
}

				
			
				
					/**
 * ===================================================================
 * LCP & HEAD OPTIMIZATION SNIPPET
 * ===================================================================
 * 1. Preloads LCP elements (hero image or font).
 * 2. Excludes the first 2 images from lazy-loading (helps LCP).
 * 3. Removes unnecessary junk from wp_head (improves TTFB).
 */

// 1. Preload Your LCP Element
add_action('wp_head', 'my_preload_lcp_elements');

function my_preload_lcp_elements() {
    
    // --- IF YOUR LCP IS AN IMAGE ---
    // ❗ IMPORTANT: Change this to your real LCP image path
    // You can use if ( is_front_page() ) { ... } to run only on the homepage.
    
    echo '<link rel="preload" href="/wp-content/uploads/2025/10/your-hero-image.webp" as="image">';


    // --- IF YOUR LCP IS TEXT (H1, etc.) ---
    // ❗ IMPORTANT: Uncomment (remove //) and change this if your LCP is text
    
    // echo '<link rel="preload" href="/wp-content/themes/your-theme/fonts/your-font-file.woff2" as="font" type="font/woff2" crossorigin>';
}


// 2. Exclude Your LCP Image from Lazy Loading
add_filter('wp_omit_loading_attr_threshold', 'my_omit_lcp_lazy_load');

function my_omit_lcp_lazy_load($threshold) {
    // This skips lazy-loading for the first 2 images on the page.
    // 1 is the default. Change 2 to 1 if you only need to skip the first image.
    return 2; 
}


// 3. Remove Unnecessary "Junk" from wp_head
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_shortlink_wp_head');


				
			
				
					<?php
/**
 * The base configuration for WordPress
 *
 * @package WordPress
 */

// ** Database settings ** //
define( 'DB_NAME', 'wp_6rzdu' );
define( 'DB_USER', 'wp_akxos' );
define( 'DB_PASSWORD', '*Hm@Sch^ptZE27z2' );
define( 'DB_HOST', 'localhost:3306' );
define( 'DB_CHARSET', 'utf8' );
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication unique keys and salts.
 */
define('AUTH_KEY', 'So8:/3+d%SY9B6t%odDgXLS!8H]46D28Pep2euv*c19ibU]%/ga+H%724miCjPo|');
define('SECURE_AUTH_KEY', '@-9|8~+vPUC~0rtx52v#3)8z4WhKa6l-OGU_Vg2-P94CkPvP|_jG:67#(DTDtn79');
define('LOGGED_IN_KEY', 'ZpORwmT]_7o5RW:yxU8zCQ5Sivh3yW@nE9q484%yUM96%89IhJd4t019~nHk_i)8');
define('NONCE_KEY', 'lJAqw[F(##G0F6Y|6&au:&nM!fSU136rgt3l3a3w05|I[GsEJm]-09~|N|KRO@M!');
define('AUTH_SALT', 'A4mJ7hogUl50)%i-%WC39_a|N+OSt!6)!U9)5)%_%82-/]frv89fP0yKI6SYfBt|');
define('SECURE_AUTH_SALT', 'm4-Q%6%|m&J313qTA%z#|g)VA&yiB0~c;]0W!1-mtfY%/r1B1T~%7CG5J/uu&M1Y');
define('LOGGED_IN_SALT', 'YS4%!@&vpM44+9X[:9nf9a#rnT:nGSY0/4%5c3p0Ta)N)49:#:eO9wh7@psmV;2/');
define('NONCE_SALT', '*_k!eBg0(IYri*5-8qlmz:6X-|9972L!#U6d/~#P7R4[|5onO1p88w)*_rF5&7;[');
/**#@-*/

/**
 * WordPress database table prefix.
 */
$table_prefix = 'QSSc8NgT_';

/* Add any custom values between this line and the "stop editing" line. */

define('WP_ALLOW_MULTISITE', true);

/**
 * For developers: WordPress debugging mode.
 */
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);


/* 🟩🟩🟩🟩🟩  ✅ এখানে আমি এই দুটি লাইন যোগ করেছি 🟩🟩🟩🟩🟩 */
define('WP_MEMORY_LIMIT', '1024M');
define('WP_MAX_MEMORY_LIMIT', '1024M');
/* 🟩🟩🟩🟩🟩  ✅ এখানে শেষ 🟩🟩🟩🟩🟩 */


/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';

				
			
				
					/**
 * Add "Enable Minimum Quantity" toggle and "Minimum Quantity Value" field in Product Edit page
 */
add_action('woocommerce_product_options_general_product_data', function() {
    echo '<div class="options_group">';
    
    // Enable toggle
    woocommerce_wp_checkbox([
        'id' => '_enable_min_qty',
        'label' => __('Enable Minimum Quantity', 'custom'),
        'description' => __('Enable custom minimum quantity for this product.', 'custom'),
    ]);

    // Minimum Quantity field
    woocommerce_wp_text_input([
        'id' => '_min_qty_value',
        'label' => __('Minimum Quantity Value', 'custom'),
        'description' => __('Set minimum quantity (e.g. 5, 10, etc.)', 'custom'),
        'type' => 'number',
        'custom_attributes' => [
            'min' => '1',
            'step' => '1'
        ]
    ]);

    echo '</div>';
});

/**
 * Save the custom product fields
 */
add_action('woocommerce_process_product_meta', function($post_id) {
    $enable_min_qty = isset($_POST['_enable_min_qty']) ? 'yes' : 'no';
    update_post_meta($post_id, '_enable_min_qty', $enable_min_qty);

    if (isset($_POST['_min_qty_value'])) {
        update_post_meta($post_id, '_min_qty_value', absint($_POST['_min_qty_value']));
    }
});

/**
 * Set default quantity and increment steps on single product page
 */
add_filter('woocommerce_quantity_input_args', function($args, $product) {
    $enable = get_post_meta($product->get_id(), '_enable_min_qty', true);
    $min_qty = (int) get_post_meta($product->get_id(), '_min_qty_value', true);

    if ($enable === 'yes' && $min_qty > 0) {
        $args['input_value'] = $min_qty; // Default quantity
        $args['min_value']   = $min_qty; // Minimum allowed
        $args['step']        = $min_qty; // Increment step
    }

    return $args;
}, 10, 2);

/**
 * Enforce minimum quantity in cart
 */
add_action('woocommerce_before_calculate_totals', function($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;

    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $enable = get_post_meta($product_id, '_enable_min_qty', true);
        $min_qty = (int) get_post_meta($product_id, '_min_qty_value', true);

        if ($enable === 'yes' && $min_qty > 0) {
            $qty = $cart_item['quantity'];
            $new_qty = max($min_qty, ceil($qty / $min_qty) * $min_qty);
            if ($qty !== $new_qty) {
                $cart_item['quantity'] = $new_qty;
            }
        }
    }
});

/**
 * Auto update price dynamically on frontend when quantity changes (AJAX)
 */
add_action('wp_footer', function() {
    if (!is_product()) return;
    ?>
    <script>
    jQuery(function($){
        $('form.cart').on('change input', 'input.qty', function(){
            let qty = parseFloat($(this).val());
            let priceElement = $('.woocommerce-Price-amount bdi').first();
            let basePrice = parseFloat($('.woocommerce-Price-amount bdi').first().text().replace(/[^0-9.,]/g, '').replace(',', '.'));

            if (isNaN(qty) || isNaN(basePrice)) return;

            // Calculate new price
            let total = basePrice * qty;

            // Update displayed price
            $('.woocommerce-Price-amount bdi').last().text(total.toFixed(2));
        });
    });
    </script>
    <?php
});

				
			
				
					/**
 * Add "Enable Minimum Quantity" toggle and "Minimum Quantity Value" field in Product Edit page
 */
add_action('woocommerce_product_options_general_product_data', function() {
    echo '<div class="options_group">';
    
    // Enable toggle
    woocommerce_wp_checkbox([
        'id' => '_enable_min_qty',
        'label' => __('Enable Minimum Quantity', 'custom'),
        'description' => __('Enable custom minimum quantity for this product.', 'custom'),
    ]);

    // Minimum Quantity field
    woocommerce_wp_text_input([
        'id' => '_min_qty_value',
        'label' => __('Minimum Quantity Value', 'custom'),
        'description' => __('Set minimum quantity (e.g. 5, 10, etc.)', 'custom'),
        'type' => 'number',
        'custom_attributes' => [
            'min' => '1',
            'step' => '1'
        ]
    ]);

    echo '</div>';
});

/**
 * Save the custom product fields
 */
add_action('woocommerce_process_product_meta', function($post_id) {
    $enable_min_qty = isset($_POST['_enable_min_qty']) ? 'yes' : 'no';
    update_post_meta($post_id, '_enable_min_qty', $enable_min_qty);

    if (isset($_POST['_min_qty_value'])) {
        update_post_meta($post_id, '_min_qty_value', absint($_POST['_min_qty_value']));
    }
});

/**
 * Set default quantity and increment steps on single product page
 */
add_filter('woocommerce_quantity_input_args', function($args, $product) {
    $enable = get_post_meta($product->get_id(), '_enable_min_qty', true);
    $min_qty = (int) get_post_meta($product->get_id(), '_min_qty_value', true);

    if ($enable === 'yes' && $min_qty > 0) {
        $args['input_value'] = $min_qty; // Default quantity
        $args['min_value']   = $min_qty; // Minimum allowed
        $args['step']        = $min_qty; // Increment step
    }

    return $args;
}, 10, 2);

/**
 * Enforce minimum quantity in cart
 */
add_action('woocommerce_before_calculate_totals', function($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;

    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $enable = get_post_meta($product_id, '_enable_min_qty', true);
        $min_qty = (int) get_post_meta($product_id, '_min_qty_value', true);

        if ($enable === 'yes' && $min_qty > 0) {
            $qty = $cart_item['quantity'];
            $new_qty = max($min_qty, ceil($qty / $min_qty) * $min_qty);
            if ($qty !== $new_qty) {
                $cart_item['quantity'] = $new_qty;
            }
        }
    }
});

/**
 * Auto update price dynamically on frontend when quantity changes (AJAX)
 */
add_action('wp_footer', function() {
    if (!is_product()) return;
    ?>
    <script>
    jQuery(function($){
        $('form.cart').on('change input', 'input.qty', function(){
            let qty = parseFloat($(this).val());
            let priceElement = $('.woocommerce-Price-amount bdi').first();
            let basePrice = parseFloat($('.woocommerce-Price-amount bdi').first().text().replace(/[^0-9.,]/g, '').replace(',', '.'));

            if (isNaN(qty) || isNaN(basePrice)) return;

            // Calculate new price
            let total = basePrice * qty;

            // Update displayed price
            $('.woocommerce-Price-amount bdi').last().text(total.toFixed(2));
        });
    });
    </script>
    <?php
});

				
			
				
					/**
 * Add "Enable Minimum Quantity" toggle and "Minimum Quantity Value" field in Product Edit page
 */
add_action('woocommerce_product_options_general_product_data', function() {
    echo '<div class="options_group">';
    
    // Enable toggle
    woocommerce_wp_checkbox([
        'id' => '_enable_min_qty',
        'label' => __('Enable Minimum Quantity', 'custom'),
        'description' => __('Enable custom minimum quantity for this product.', 'custom'),
    ]);

    // Minimum Quantity field
    woocommerce_wp_text_input([
        'id' => '_min_qty_value',
        'label' => __('Minimum Quantity Value', 'custom'),
        'description' => __('Set minimum quantity (e.g. 5, 10, etc.)', 'custom'),
        'type' => 'number',
        'custom_attributes' => [
            'min' => '1',
            'step' => '1'
        ]
    ]);

    echo '</div>';
});

/**
 * Save the custom product fields
 */
add_action('woocommerce_process_product_meta', function($post_id) {
    $enable_min_qty = isset($_POST['_enable_min_qty']) ? 'yes' : 'no';
    update_post_meta($post_id, '_enable_min_qty', $enable_min_qty);

    if (isset($_POST['_min_qty_value'])) {
        update_post_meta($post_id, '_min_qty_value', absint($_POST['_min_qty_value']));
    }
});

/**
 * Set default quantity and increment steps on single product page
 */
add_filter('woocommerce_quantity_input_args', function($args, $product) {
    $enable = get_post_meta($product->get_id(), '_enable_min_qty', true);
    $min_qty = (int) get_post_meta($product->get_id(), '_min_qty_value', true);

    if ($enable === 'yes' && $min_qty > 0) {
        $args['input_value'] = $min_qty; // Default quantity
        $args['min_value']   = $min_qty; // Minimum allowed
        $args['step']        = $min_qty; // Increment step
    }

    return $args;
}, 10, 2);

/**
 * Enforce minimum quantity in cart
 */
add_action('woocommerce_before_calculate_totals', function($cart) {
    if (is_admin() && !defined('DOING_AJAX')) return;

    foreach ($cart->get_cart() as $cart_item) {
        $product_id = $cart_item['product_id'];
        $enable = get_post_meta($product_id, '_enable_min_qty', true);
        $min_qty = (int) get_post_meta($product_id, '_min_qty_value', true);

        if ($enable === 'yes' && $min_qty > 0) {
            $qty = $cart_item['quantity'];
            $new_qty = max($min_qty, ceil($qty / $min_qty) * $min_qty);
            if ($qty !== $new_qty) {
                $cart_item['quantity'] = $new_qty;
            }
        }
    }
});

/**
 * Auto update price dynamically on frontend when quantity changes (AJAX)
 */
add_action('wp_footer', function() {
    if (!is_product()) return;
    ?>
    <script>
    jQuery(function($){
        $('form.cart').on('change input', 'input.qty', function(){
            let qty = parseFloat($(this).val());
            let priceElement = $('.woocommerce-Price-amount bdi').first();
            let basePrice = parseFloat($('.woocommerce-Price-amount bdi').first().text().replace(/[^0-9.,]/g, '').replace(',', '.'));

            if (isNaN(qty) || isNaN(basePrice)) return;

            // Calculate new price
            let total = basePrice * qty;

            // Update displayed price
            $('.woocommerce-Price-amount bdi').last().text(total.toFixed(2));
        });
    });
    </script>
    <?php
});

				
			
				
					(function ($) {

    function fixElementorTimeField() {

        const field = document.querySelector('[name="form_fields[field_0d60bf7]"]');
        if (!field) return;

        // Elementor already initialized flatpickr → destroy it
        if (field._flatpickr) {
            field._flatpickr.destroy();
        }

        // Re-init with AM/PM display
        flatpickr(field, {
            enableTime: true,
            noCalendar: true,
            time_24hr: false,

            altInput: true,
            altFormat: "h K",     // ✅ 8 PM, 9 PM
            dateFormat: "H:i",   // backend safe

            allowInput: true
        });
    }

    // Elementor frontend hook
    $(window).on('elementor/frontend/init', function () {

        elementorFrontend.hooks.addAction(
            'frontend/element_ready/form.default',
            function () {
                setTimeout(fixElementorTimeField, 300);
            }
        );

    });

})(jQuery);
(function ($) {

    function fixElementorDateField() {

        const field = document.querySelector('[name="form_fields[field_26149d6]"]');
        if (!field) return;

        // Destroy existing flatpickr (Elementor default)
        if (field._flatpickr) {
            field._flatpickr.destroy();
        }

        flatpickr(field, {
            dateFormat: "Y-m-d",     // backend format (keep safe)
            altInput: true,
            altFormat: "d M Y",      // ✅ 20 Jan 2026
            allowInput: true
        });
    }

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/form.default',
            function () {
                setTimeout(fixElementorDateField, 300);
            }
        );
    });

})(jQuery);

				
			
				
					/**
 * Plugin Name: MCQ Master System V46.0
 * Description: Advanced MCQ Quiz System with Full Elementor Styling Controls
 * Version: 46.0
 * Author: MCQ Master
 */

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

/**
 * MCQ Master System: Extreme Customization V46.0
 * Features: Full Typography, Border, Margin, Padding, Hover Effects, Popup Input Styling
 * Security: Nonce verification, sanitization, capability checks
 */

// ============================================================================
// 1. REGISTER CUSTOM POST TYPES & TAXONOMIES
// ============================================================================

add_action('init', function() {
    // Quiz CPT
    register_post_type('quiz', array(
        'public' => true,
        'label' => 'ALL MCQ',
        'labels' => array(
            'name' => 'ALL MCQ',
            'singular_name' => 'MCQ Quiz',
            'add_new' => 'ADD NEW MCQ',
            'all_items' => 'ALL MCQ',
            'edit_item' => 'Edit Quiz',
            'view_item' => 'View Quiz'
        ),
        'supports' => array('title'),
        'menu_icon' => 'dashicons-welcome-learn-more',
        'has_archive' => true,
        'taxonomies' => array('mcq_category', 'mcq_tag'),
        'capability_type' => 'post',
        'query_var' => true,
        'show_in_rest' => false,
    ));

    // Taxonomies
    register_taxonomy('mcq_category', 'quiz', array(
        'label' => 'MCQ Category',
        'hierarchical' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'rewrite' => array('slug' => 'mcq-category')
    ));
    
    register_taxonomy('mcq_tag', 'quiz', array(
        'label' => 'MCQ Tags',
        'hierarchical' => false,
        'show_ui' => true,
        'rewrite' => array('slug' => 'mcq-tag')
    ));

    // Settings CPT
    register_post_type('mcq_setting', array(
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => 'edit.php?post_type=quiz',
        'label' => 'MCQ Settings',
        'supports' => array('title'),
        'capability_type' => 'post',
    ));

    // Leads CPT
    register_post_type('quiz_leads', array(
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => 'edit.php?post_type=quiz',
        'label' => 'Student Leads',
        'supports' => array('title'),
        'capability_type' => 'post',
    ));

    // Submissions CPT
    register_post_type('quiz_submission', array(
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => 'edit.php?post_type=quiz',
        'label' => 'Quiz Results',
        'supports' => array('title'),
        'capability_type' => 'post',
    ));
}, 1);

// ============================================================================
// 2. ADMIN COLUMNS & REPORTING UI
// ============================================================================

add_filter('manage_quiz_leads_posts_columns', function($cols) {
    $new_cols = array();
    $new_cols['cb'] = $cols['cb'];
    $new_cols['title'] = 'Student Name';
    $new_cols['lead_details'] = 'Contact & Info';
    $new_cols['final_score'] = 'Quiz Score';
    $new_cols['action_btn'] = 'Action';
    $new_cols['date'] = $cols['date'];
    return $new_cols;
});

add_action('manage_quiz_leads_posts_custom_column', function($col, $id) {
    $info = get_post_meta($id, '_user_data', true) ?: array();
    $sub_id = get_post_meta($id, '_related_submission_id', true);
    
    if ($col === 'lead_details') {
        foreach($info as $key => $val) {
            if($key != 'name') {
                echo '<strong>'.esc_html(ucfirst($key)).':</strong> '.esc_html($val).'<br>';
            }
        }
    }
    
    if ($col === 'final_score' && $sub_id) {
        echo '<span style="background:#e7fcf3; color:#1a7f64; padding:5px 12px; border-radius:20px; font-weight:600; font-size:12px;">' . 
             esc_html(get_post_meta($sub_id, '_submission_score', true)) . '</span>';
    }
    
    if ($col === 'action_btn' && $sub_id) {
        echo '<button type="button" class="button button-primary view-analysis-inline" style="border-radius:4px;" data-id="'.esc_attr($sub_id).'">View Analysis</button>';
    }
}, 10, 2);

add_filter('manage_quiz_submission_posts_columns', function($cols) {
    $new_cols = array();
    $new_cols['cb'] = $cols['cb'];
    $new_cols['title'] = 'Submission User';
    $new_cols['score_display'] = 'Score';
    $new_cols['action_inline'] = 'Detailed Report';
    $new_cols['date'] = $cols['date'];
    return $new_cols;
});

add_action('manage_quiz_submission_posts_custom_column', function($col, $id) {
    if ($col === 'score_display') {
        echo '<strong style="color:#2271b1; background:#f0f6fb; padding:4px 10px; border-radius:4px;">' . 
             esc_html(get_post_meta($id, '_submission_score', true) ?: 'N/A') . '</strong>';
    }
    
    if ($col === 'action_inline') {
        echo '<button type="button" class="button view-analysis-inline" style="border-radius:4px;" data-id="'.esc_attr($id).'">View Report</button>';
    }
}, 10, 2);

add_action('admin_footer', function() {
    ?>
    <div id="mcq-admin-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15, 23, 42, 0.8); backdrop-filter: blur(4px); z-index:999999; justify-content:center; align-items:center;">
        <div style="background:#fff; width:90%; max-width:800px; max-height:85vh; overflow-y:auto; padding:40px; border-radius:12px; position:relative; box-shadow:0 25px 50px -12px rgba(0,0,0,0.25);">
            <span class="close-admin-modal" style="position:absolute; top:20px; right:25px; font-size:30px; cursor:pointer; color:#64748b;">&times;</span>
            <div id="modal-content-area">Loading...</div>
        </div>
    </div>
    <script>
    jQuery(document).ready(function($) {
        $(document).on('click', '.view-analysis-inline', function() {
            let subId = $(this).data('id');
            $('#mcq-admin-modal').css('display', 'flex');
            $.post(ajaxurl, { action: 'view_quiz_analysis_html', sub_id: subId }, function(res) {
                $('#modal-content-area').html(res);
            });
        });
        $(document).on('click', '.close-admin-modal', function() {
            $('#mcq-admin-modal').hide();
        });
    });
    </script>
    <?php
});

add_action('wp_ajax_view_quiz_analysis_html', function() {
    // Security: Capability check
    if (!current_user_can('edit_posts')) {
        wp_die('Access denied');
    }
    
    $id = intval($_POST['sub_id']);
    
    // Verify post type
    if (get_post_type($id) !== 'quiz_submission') {
        wp_die('Invalid submission');
    }
    
    $details = get_post_meta($id, '_submission_details_array', true);
    $score = get_post_meta($id, '_submission_score', true);
    
    echo '<h2 style="margin-bottom:20px; font-size:24px;">Quiz Analysis <span style="color:#2563eb;">(Score: '.$score.')</span></h2>';
    echo '<table class="wp-list-table widefat fixed striped" style="border:none; box-shadow:none;">';
    echo '<thead><tr><th>Question</th><th>User Answer</th><th>Correct Answer</th><th>Status</th></tr></thead>';
    echo '<tbody>';
    
    if (is_array($details)) {
        foreach($details as $d) {
            $status_style = $d['ok'] ? 'color:#059669; font-weight:bold;' : 'color:#dc2626; font-weight:bold;';
            $status_text = $d['ok'] ? '✔ Correct' : '✘ Wrong';
            
            echo "<tr>";
            echo "<td style='padding:12px; width:50%;'>" . esc_html($d['q']) . "</td>";
            echo "<td style='width:15%;'>" . esc_html(strtoupper($d['u'])) . "</td>";
            echo "<td style='width:15%;'>" . esc_html(strtoupper($d['c'])) . "</td>";
            echo "<td style='$status_style width:20%;'>$status_text</td>";
            echo "</tr>";
        }
    } else {
        echo "<tr><td colspan='4' style='text-align:center; padding:20px;'>No data available</td></tr>";
    }
    
    echo '</tbody></table>';
    wp_die();
});

// ============================================================================
// 3. META BOXES & SETTINGS
// ============================================================================

add_action('add_meta_boxes', function() {
    add_meta_box('quiz_settings_box', 'Quiz General Settings', 'render_quiz_settings_v46', 'quiz', 'normal', 'high');
    add_meta_box('quiz_repeater_box', 'Question Builder', 'render_quiz_repeater_v46', 'quiz', 'normal', 'high');
    add_meta_box('mcq_redir_box', 'Redirect URL Configuration', 'render_mcq_redir_v46', 'mcq_setting', 'normal', 'high');
});

function render_mcq_redir_v46($post) {
    $redir_url = get_post_meta($post->ID, '_mcq_redirect_url', true);
    wp_nonce_field('save_mcq_meta_v46', 'mcq_nonce_v46');
    
    echo '<div style="padding:15px;">';
    echo '<label style="display:block; margin-bottom:10px; font-weight:600; color:#334155;">Success Redirect URL:</label>';
    echo '<input type="url" name="mcq_redirect_url" value="'.esc_url($redir_url).'" style="width:100%; padding:12px; border-radius:6px; border:1px solid #cbd5e1; font-size:14px;" placeholder="https://example.com/thank-you">';
    echo '<p style="margin-top:8px; color:#64748b; font-size:13px;">After quiz completion, users will be redirected to this URL</p>';
    echo '</div>';
}

function render_quiz_settings_v46($post) {
    $timer = get_post_meta($post->ID, '_quiz_timer', true) ?: 10;
    $is_req = get_post_meta($post->ID, '_is_required', true);
    $expiry = get_post_meta($post->ID, '_quiz_expiry', true);
    $selected_setting = get_post_meta($post->ID, '_linked_setting_id', true);
    $fields = get_post_meta($post->ID, '_enabled_fields', true) ?: array();
    $settings_posts = get_posts(array('post_type' => 'mcq_setting', 'numberposts' => -1));
    
    wp_nonce_field('save_mcq_meta_v46', 'mcq_nonce_v46');
    ?>
    <style>
        .modern-admin-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; padding: 15px; background: #fff; }
        .admin-field-box { border: 1px solid #e2e8f0; padding: 15px; border-radius: 8px; background: #f8fafc; }
        .admin-field-box label { font-weight: 600; color: #334155; margin-bottom: 8px; display: inline-block; }
        .admin-field-box input[type="datetime-local"], 
        .admin-field-box input[type="number"], 
        .admin-field-box select { 
            width: 100%; padding: 10px; border-radius: 5px; border: 1px solid #cbd5e1; font-size: 14px;
        }
        .popup-fields-grid { display: flex; gap: 15px; flex-wrap: wrap; margin-top: 10px; }
        .popup-fields-grid label { 
            background: #fff; padding: 8px 15px; border: 1px solid #cbd5e1; border-radius: 20px; 
            font-size: 13px; cursor: pointer; display: inline-flex; align-items: center;
        }
        .popup-fields-grid input { margin-right: 8px; }
    </style>
    <div class="modern-admin-grid">
        <div class="admin-field-box">
            <label>Quiz Expiry Date & Time</label>
            <input type="datetime-local" name="quiz_expiry" value="<?php echo esc_attr($expiry); ?>">
            <p style="margin-top:8px; color:#64748b; font-size:12px;">Leave empty for no expiry</p>
        </div>
        <div class="admin-field-box">
            <label>Redirect Delay (Seconds)</label>
            <input type="number" name="quiz_timer" value="<?php echo esc_attr($timer); ?>" min="1" max="60">
            <p style="margin-top:8px; color:#64748b; font-size:12px;">Time before redirect after completion</p>
        </div>
        <div class="admin-field-box" style="grid-column: span 2;">
            <label>Student Info Popup Fields</label>
            <div class="popup-fields-grid">
                <?php foreach(array('name','email','phone','roll','class') as $f): ?>
                    <label>
                        <input type="checkbox" name="enabled_fields[]" value="<?php echo esc_attr($f); ?>" <?php checked(in_array($f, $fields)); ?>> 
                        <?php echo esc_html(ucfirst($f)); ?>
                    </label>
                <?php endforeach; ?>
            </div>
            <p style="margin-top:10px; color:#64748b; font-size:12px;">Fields to collect before showing results</p>
        </div>
        <div class="admin-field-box">
            <label style="font-weight:500;">
                <input type="checkbox" name="is_required" value="yes" <?php checked($is_req, 'yes'); ?>> 
                Force Answer All Questions
            </label>
            <p style="margin-top:8px; color:#64748b; font-size:12px;">Users must answer all questions to submit</p>
        </div>
        <div class="admin-field-box">
            <label>Success Redirect Setting</label>
            <select name="linked_setting_id">
                <option value="">Default (Home Page)</option>
                <?php foreach($settings_posts as $s): ?>
                    <option value='<?php echo esc_attr($s->ID); ?>' <?php selected($selected_setting, $s->ID); ?>>
                        <?php echo esc_html($s->post_title); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p style="margin-top:8px; color:#64748b; font-size:12px;">Select redirect configuration</p>
        </div>
    </div>
    <?php
}

function render_quiz_repeater_v46($post) {
    $questions = get_post_meta($post->ID, '_quiz_questions', true) ?: array();
    ?>
    <style>
        .q-row-card { 
            border: 1px solid #e2e8f0; padding: 25px; margin-bottom: 20px; background: #fff; 
            border-radius: 10px; position: relative; box-shadow: 0 1px 3px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }
        .q-row-card:hover { 
            box-shadow: 0 4px 6px rgba(0,0,0,0.1); 
            border-color: #3b82f6;
        }
        .q-row-card .remove-q { 
            position: absolute; top: 15px; right: 15px; background: #fee2e2; color: #dc2626; 
            border: none; width: 30px; height: 30px; border-radius: 50%; cursor: pointer; 
            font-weight: bold; transition: all 0.2s;
        }
        .q-row-card .remove-q:hover { 
            background: #fecaca; transform: scale(1.1);
        }
        .q-input-main { 
            width: 100%; padding: 12px; font-size: 15px; border: 1px solid #cbd5e1; 
            border-radius: 6px; margin-bottom: 15px; font-weight: 600;
        }
        .opt-grid-admin { 
            display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px;
        }
        .opt-grid-admin input { 
            padding: 10px; border: 1px solid #e2e8f0; border-radius: 6px; background: #fdfdfd;
            font-size: 14px;
        }
        .correct-select-wrap { 
            margin-top: 15px; padding-top: 15px; border-top: 1px dashed #e2e8f0;
        }
        .correct-select-wrap strong { 
            color: #1e40af; font-size: 14px;
        }
    </style>
    <div id="mcq-repeater">
        <?php foreach ($questions as $idx => $q): ?>
            <div class="q-row-card">
                <button type="button" class="remove-q" title="Remove Question">&times;</button>
                <input type="text" name="quiz_questions[<?php echo esc_attr($idx); ?>][question]" 
                       value="<?php echo esc_attr($q['question'] ?? ''); ?>" 
                       class="q-input-main" placeholder="Type your question here...">
                <div class="opt-grid-admin">
                    <?php foreach(array('a','b','c','d') as $o): ?>
                        <input type="text" name="quiz_questions[<?php echo esc_attr($idx); ?>][<?php echo esc_attr($o); ?>]" 
                               value="<?php echo esc_attr($q[$o] ?? ''); ?>" 
                               placeholder="Option <?php echo strtoupper($o); ?>">
                    <?php endforeach; ?>
                </div>
                <div class="correct-select-wrap">
                    <strong>Correct Answer:</strong> 
                    <select name="quiz_questions[<?php echo esc_attr($idx); ?>][correct]" style="margin-left:10px; padding:10px 20px 10px 20px; border-radius:4px; border:1px solid #cbd5e1;">
                        <?php foreach(array('a','b','c','d') as $o): ?>
                            <option value="<?php echo esc_attr($o); ?>" <?php selected($q['correct'] ?? '', $o); ?>>
                                <?php echo strtoupper($o); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <button type="button" id="add-q" class="button button-primary button-large" style="margin-top:10px; height:45px; padding:0 30px; border-radius:6px;">
        + Add New Question
    </button>
    <script>
        jQuery(document).ready(function($){ 
            let i = <?php echo count($questions); ?>; 
            $('#add-q').click(function(){ 
                let h = `<div class="q-row-card">
                    <button type="button" class="remove-q" title="Remove Question">&times;</button>
                    <input type="text" name="quiz_questions[${i}][question]" class="q-input-main" placeholder="Type your question here...">
                    <div class="opt-grid-admin">
                        <input type="text" name="quiz_questions[${i}][a]" placeholder="Option A">
                        <input type="text" name="quiz_questions[${i}][b]" placeholder="Option B">
                        <input type="text" name="quiz_questions[${i}][c]" placeholder="Option C">
                        <input type="text" name="quiz_questions[${i}][d]" placeholder="Option D">
                    </div>
                    <div class="correct-select-wrap">
                        <strong>Correct Answer:</strong> 
                        <select name="quiz_questions[${i}][correct]" style="margin-left:10px; padding:8px; border-radius:4px; border:1px solid #cbd5e1;">
                            <option value="a">A</option>
                            <option value="b">B</option>
                            <option value="c">C</option>
                            <option value="d">D</option>
                        </select>
                    </div>
                </div>`; 
                $('#mcq-repeater').append(h); 
                i++; 
            }); 
            $(document).on('click', '.remove-q', function(){ 
                if (confirm('Are you sure you want to remove this question?')) {
                    $(this).parent().remove(); 
                }
            }); 
        });
    </script>
    <?php
}

// ============================================================================
// 4. SAVE META DATA WITH SECURITY
// ============================================================================

add_action('save_post', function($post_id) {
    // Security: Verify nonce
    if (!isset($_POST['mcq_nonce_v46']) || !wp_verify_nonce($_POST['mcq_nonce_v46'], 'save_mcq_meta_v46')) {
        return;
    }
    
    // Security: Check post type
    $post_type = get_post_type($post_id);
    if (!in_array($post_type, ['quiz', 'mcq_setting'])) {
        return;
    }
    
    // Security: Don't save during autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // Security: Check user permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Sanitize and save quiz questions
    if (isset($_POST['quiz_questions']) && is_array($_POST['quiz_questions'])) {
        $sanitized_questions = array();
        foreach ($_POST['quiz_questions'] as $q) {
            $sanitized_questions[] = array(
                'question' => sanitize_text_field($q['question']),
                'a' => sanitize_text_field($q['a']),
                'b' => sanitize_text_field($q['b']),
                'c' => sanitize_text_field($q['c']),
                'd' => sanitize_text_field($q['d']),
                'correct' => in_array($q['correct'], ['a','b','c','d']) ? $q['correct'] : 'a'
            );
        }
        update_post_meta($post_id, '_quiz_questions', $sanitized_questions);
    }
    
    // Save other fields with sanitization
    if (isset($_POST['quiz_timer'])) {
        update_post_meta($post_id, '_quiz_timer', absint($_POST['quiz_timer']));
    }
    
    if (isset($_POST['quiz_expiry'])) {
        update_post_meta($post_id, '_quiz_expiry', sanitize_text_field($_POST['quiz_expiry']));
    }
    
    update_post_meta($post_id, '_is_required', isset($_POST['is_required']) ? 'yes' : 'no');
    
    if (isset($_POST['enabled_fields']) && is_array($_POST['enabled_fields'])) {
        $sanitized_fields = array_map('sanitize_text_field', $_POST['enabled_fields']);
        update_post_meta($post_id, '_enabled_fields', $sanitized_fields);
    } else {
        delete_post_meta($post_id, '_enabled_fields');
    }
    
    if (isset($_POST['linked_setting_id'])) {
        update_post_meta($post_id, '_linked_setting_id', absint($_POST['linked_setting_id']));
    }
    
    if (isset($_POST['mcq_redirect_url'])) {
        update_post_meta($post_id, '_mcq_redirect_url', esc_url_raw($_POST['mcq_redirect_url']));
    }
}, 10, 1);

// ============================================================================
// 5. ELEMENTOR WIDGET V46 - FULL STYLING CONTROLS
// ============================================================================

add_action('elementor/widgets/register', function($widgets_manager) {
    class MCQ_Master_Widget_V46 extends \Elementor\Widget_Base {
        
        public function get_name() {
            return 'mcq_master_v46';
        }
        
        public function get_title() {
            return 'MCQ Master V46 (Full Custom Styling)';
        }
        
        public function get_icon() {
            return 'eicon-form-horizontal';
        }
        
        public function get_categories() {
            return array('general');
        }
        
        protected function register_controls() {
            
            // ------------------------------------------------------------------------
            // CONTENT SECTION
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('content', array(
                'label' => 'Quiz Settings'
            ));
            
            $quizzes = get_posts(array('post_type' => 'quiz', 'numberposts' => -1));
            $options = array('' => 'Select Quiz');
            foreach ($quizzes as $q) {
                $options[$q->ID] = $q->post_title;
            }
            
            $this->add_control('qid', array(
                'label' => 'Choose Quiz',
                'type' => \Elementor\Controls_Manager::SELECT,
                'options' => $options,
                'description' => 'Select a quiz to display'
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // TIMER STYLE SECTION
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_timer', array(
                'label' => 'Timer Style',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 't_typo',
                    'selector' => '{{WRAPPER}} .live-expiry-timer',
                )
            );
            
            $this->add_control('t_color', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .live-expiry-timer' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('t_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .live-expiry-timer' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 't_border',
                    'selector' => '{{WRAPPER}} .live-expiry-timer',
                )
            );
            
            $this->add_control('t_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .live-expiry-timer' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('t_margin', array(
                'label' => 'Margin',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .live-expiry-timer' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('t_padding', array(
                'label' => 'Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .live-expiry-timer' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // QUESTION STYLE SECTION
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_q', array(
                'label' => 'Question Style',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 'q_typo',
                    'selector' => '{{WRAPPER}} .mcq-q-text',
                )
            );
            
            $this->add_control('q_color', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-q-text' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('q_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .q-block' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 'q_border',
                    'selector' => '{{WRAPPER}} .q-block',
                )
            );
            
            $this->add_control('q_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .q-block' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Box_Shadow::get_type(),
                array(
                    'name' => 'q_shadow',
                    'selector' => '{{WRAPPER}} .q-block',
                )
            );
            
            $this->add_responsive_control('q_margin', array(
                'label' => 'Margin',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .q-block' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('q_padding', array(
                'label' => 'Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .q-block' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // OPTIONS STYLE SECTION
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_opts', array(
                'label' => 'Options (Answers)',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 'a_typo',
                    'selector' => '{{WRAPPER}} .opt-text',
                )
            );
            
            $this->start_controls_tabs('a_tabs');
            
            // Normal State
            $this->start_controls_tab('a_norm', array('label' => 'Normal'));
            
            $this->add_control('a_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('a_color', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .opt-text' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('a_border_color', array(
                'label' => 'Border Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label' => 'border-color: {{VALUE}};',
                ),
            ));
            
            $this->end_controls_tab();
            
            // Hover/Selected State
            $this->start_controls_tab('a_hov', array('label' => 'Hover/Selected'));
            
            $this->add_control('a_bg_h', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label:hover, {{WRAPPER}} .mcq-option-label.is-selected' => 'background-color: {{VALUE}} !important;',
                ),
            ));
            
            $this->add_control('a_color_h', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label:hover .opt-text, {{WRAPPER}} .mcq-option-label.is-selected .opt-text' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('a_border_color_h', array(
                'label' => 'Border Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label:hover, {{WRAPPER}} .mcq-option-label.is-selected' => 'border-color: {{VALUE}} !important;',
                ),
            ));
            
            $this->add_control('a_hov_anim', array(
                'label' => 'Hover Animation',
                'type' => \Elementor\Controls_Manager::HOVER_ANIMATION,
            ));
            
            $this->end_controls_tab();
            
            $this->end_controls_tabs();
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 'a_border',
                    'selector' => '{{WRAPPER}} .mcq-option-label',
                )
            );
            
            $this->add_control('a_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => array('px', '%'),
                'range' => array(
                    'px' => array('min' => 0, 'max' => 50),
                    '%' => array('min' => 0, 'max' => 50),
                ),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label' => 'border-radius: {{SIZE}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('a_padding', array(
                'label' => 'Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-option-label' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('a_gap', array(
                'label' => 'Gap Between Options',
                'type' => \Elementor\Controls_Manager::SLIDER,
                'size_units' => array('px'),
                'range' => array(
                    'px' => array('min' => 0, 'max' => 50),
                ),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-grid' => 'gap: {{SIZE}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // MAIN SUBMIT BUTTON STYLE
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_btn', array(
                'label' => 'Main Submit Button',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 'btn_typo',
                    'selector' => '{{WRAPPER}} .mcq-submit-btn',
                )
            );
            
            $this->start_controls_tabs('btn_tabs');
            
            // Normal State
            $this->start_controls_tab('btn_norm', array('label' => 'Normal'));
            
            $this->add_control('btn_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('btn_color', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->end_controls_tab();
            
            // Hover State
            $this->start_controls_tab('btn_hov', array('label' => 'Hover'));
            
            $this->add_control('btn_bg_h', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn:hover' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('btn_color_h', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn:hover' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('btn_hov_anim', array(
                'label' => 'Hover Animation',
                'type' => \Elementor\Controls_Manager::HOVER_ANIMATION,
            ));
            
            $this->end_controls_tab();
            
            $this->end_controls_tabs();
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 'btn_border',
                    'selector' => '{{WRAPPER}} .mcq-submit-btn',
                )
            );
            
            $this->add_control('btn_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Box_Shadow::get_type(),
                array(
                    'name' => 'btn_shadow',
                    'selector' => '{{WRAPPER}} .mcq-submit-btn',
                )
            );
            
            $this->add_responsive_control('btn_margin', array(
                'label' => 'Margin',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('btn_padding', array(
                'label' => 'Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-submit-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // REGISTRATION POPUP STYLE
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_popup', array(
                'label' => 'Registration Popup',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            // Popup Background
            $this->add_control('pop_heading', array(
                'label' => 'Popup Background',
                'type' => \Elementor\Controls_Manager::HEADING,
            ));
            
            $this->add_control('pop_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_overlay_bg', array(
                'label' => 'Overlay Background',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .lead-modal' => 'background-color: {{VALUE}};',
                ),
            ));
            
            // Input Fields
            $this->add_control('pop_input_heading', array(
                'label' => 'Input Fields',
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 'pop_in_typo',
                    'selector' => '{{WRAPPER}} .mcq-popup-inner input',
                )
            );
            
            $this->start_controls_tabs('pop_in_tabs');
            
            // Normal State
            $this->start_controls_tab('pop_in_norm', array('label' => 'Normal'));
            
            $this->add_control('pop_in_bg', array(
                'label' => 'Input Background',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_in_color', array(
                'label' => 'Input Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_in_border_color', array(
                'label' => 'Border Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input' => 'border-color: {{VALUE}};',
                ),
            ));
            
            $this->end_controls_tab();
            
            // Focus State
            $this->start_controls_tab('pop_in_focus', array('label' => 'Focus'));
            
            $this->add_control('pop_in_focus_bg', array(
                'label' => 'Input Background',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input:focus' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_in_focus_color', array(
                'label' => 'Input Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input:focus' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_in_focus_border', array(
                'label' => 'Focus Border Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input:focus' => 'border-color: {{VALUE}}; box-shadow: 0 0 0 3px {{VALUE}}33;',
                ),
            ));
            
            $this->end_controls_tab();
            
            $this->end_controls_tabs();
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 'pop_in_border',
                    'selector' => '{{WRAPPER}} .mcq-popup-inner input',
                )
            );
            
            $this->add_control('pop_in_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('pop_in_padding', array(
                'label' => 'Input Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .mcq-popup-inner input' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            // Popup Submit Button
            $this->add_control('pop_btn_heading', array(
                'label' => 'Popup Submit Button',
                'type' => \Elementor\Controls_Manager::HEADING,
                'separator' => 'before',
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Typography::get_type(),
                array(
                    'name' => 'pop_btn_typo',
                    'selector' => '{{WRAPPER}} .pop-submit-btn',
                )
            );
            
            $this->add_control('pop_btn_bg', array(
                'label' => 'Button Background',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .pop-submit-btn' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('pop_btn_color', array(
                'label' => 'Button Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .pop-submit-btn' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_group_control(
                \Elementor\Group_Control_Border::get_type(),
                array(
                    'name' => 'pop_btn_border',
                    'selector' => '{{WRAPPER}} .pop-submit-btn',
                )
            );
            
            $this->add_control('pop_btn_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .pop-submit-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_responsive_control('pop_btn_padding', array(
                'label' => 'Button Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .pop-submit-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
            
            // ------------------------------------------------------------------------
            // SUCCESS MESSAGE STYLE
            // ------------------------------------------------------------------------
            
            $this->start_controls_section('style_success', array(
                'label' => 'Success Message',
                'tab' => \Elementor\Controls_Manager::TAB_STYLE
            ));
            
            $this->add_control('success_bg', array(
                'label' => 'Background Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box' => 'background-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('success_border_color', array(
                'label' => 'Border Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box' => 'border-color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('success_text_color', array(
                'label' => 'Text Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_control('success_timer_color', array(
                'label' => 'Timer Color',
                'type' => \Elementor\Controls_Manager::COLOR,
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box .redir-timer' => 'color: {{VALUE}};',
                ),
            ));
            
            $this->add_responsive_control('success_padding', array(
                'label' => 'Padding',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->add_control('success_radius', array(
                'label' => 'Border Radius',
                'type' => \Elementor\Controls_Manager::DIMENSIONS,
                'size_units' => array('px', '%'),
                'selectors' => array(
                    '{{WRAPPER}} .inline-success-box' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ),
            ));
            
            $this->end_controls_section();
        }
        
        protected function render() {
            $settings = $this->get_settings_for_display();
            $qid = intval($settings['qid']);
            
            if (!$qid) {
                echo '<div style="padding:30px; background:#fff3cd; border:1px solid #ffc107; border-radius:8px; text-align:center;">';
                echo '<strong>Please select a quiz in the widget settings.</strong>';
                echo '</div>';
                return;
            }
            
            // Get quiz data
            $quiz_post = get_post($qid);
            if (!$quiz_post || $quiz_post->post_type !== 'quiz') {
                echo '<div style="padding:30px; background:#f8d7da; border:1px solid #f5c6cb; border-radius:8px; text-align:center;">';
                echo '<strong>Invalid quiz selected.</strong>';
                echo '</div>';
                return;
            }
            
            // Get expiry timestamp
            $expiry = get_post_meta($qid, '_quiz_expiry', true);
            $expiry_ts = $expiry ? strtotime($expiry) : 0;
            
            // Get animation classes
            $btn_anim = !empty($settings['btn_hov_anim']) ? 'elementor-animation-' . $settings['btn_hov_anim'] : '';
            $opt_anim = !empty($settings['a_hov_anim']) ? 'elementor-animation-' . $settings['a_hov_anim'] : '';
            
            $widget_id = $this->get_id();
            
            // Inline styles for base structure
            echo "<style>
                #mcq-wrap-{$widget_id} .live-expiry-timer { 
                    text-align: center; 
                    font-weight: 600;
                    transition: all 0.3s ease;
                }
                #mcq-wrap-{$widget_id} .q-block { 
                    transition: all 0.3s ease;
                }
                #mcq-wrap-{$widget_id} .mcq-grid { 
                    display: flex; 
                    flex-direction: row; 
                    gap: 10px; 
                    margin-top: 15px; 
                    flex-wrap: wrap;
                }
                #mcq-wrap-{$widget_id} .mcq-option-label { 
                    display: flex; 
                    align-items: center; 
                    cursor: pointer; 
                    transition: all 0.3s ease; 
                    flex: 1; 
                    min-width: 200px;
                    position: relative;
                }
                #mcq-wrap-{$widget_id} .mcq-option-label input { 
                    margin-right: 10px; 
                    cursor: pointer;
                    accent-color: inherit;
                }
                #mcq-wrap-{$widget_id} .mcq-submit-btn, 
                #mcq-wrap-{$widget_id} .pop-submit-btn { 
                    width: 100%; 
                    border: none; 
                    cursor: pointer; 
                    transition: all 0.3s ease; 
                    display: block; 
                    text-align: center;
                    font-weight: 600;
                }
                #mcq-wrap-{$widget_id} .lead-modal { 
                    position: fixed; 
                    top: 0; 
                    left: 0; 
                    width: 100%; 
                    height: 100%; 
                    z-index: 999999; 
                    display: none; 
                    align-items: center; 
                    justify-content: center;
                }
                #mcq-wrap-{$widget_id} .mcq-popup-inner { 
                    width: 90%; 
                    max-width: 450px; 
                    padding: 30px; 
                    border-radius: 12px;
                    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
                }
                #mcq-wrap-{$widget_id} .mcq-popup-inner input { 
                    width: 100%; 
                    margin-bottom: 15px; 
                    transition: all 0.3s ease;
                }
                #mcq-wrap-{$widget_id} .mcq-popup-inner input:focus { 
                    outline: none;
                }
                #mcq-wrap-{$widget_id} .inline-success-box { 
                    display: none; 
                    margin-top: 20px; 
                    text-align: center;
                    border-width: 2px;
                    border-style: solid;
                }
                #mcq-wrap-{$widget_id} .error-txt { 
                    color: #dc2626; 
                    display: none; 
                    margin-top: 12px; 
                    font-weight: 600; 
                    font-size: 13px;
                    animation: shake 0.5s;
                }
                @keyframes shake {
                    0%, 100% { transform: translateX(0); }
                    25% { transform: translateX(-5px); }
                    75% { transform: translateX(5px); }
                }
            </style>";
            
            // Widget wrapper
            echo "<div class='mcq-wrapper' id='mcq-wrap-{$widget_id}'>";
            
            // Timer display
            if ($expiry_ts > 0) {
                echo "<div class='live-expiry-timer' id='timer-{$widget_id}'>Loading Timer...</div>";
            }
            
            // MCQ content area
            echo "<div class='mcq-content-area' id='content-{$widget_id}'>";
            echo "<div style='text-align:center; padding:40px;'><div style='display:inline-block; width:40px; height:40px; border:4px solid #3b82f6; border-top-color:transparent; border-radius:50%; animation:spin 1s linear infinite;'></div></div>";
            echo "</div>";
            
            echo "</div>";
            
            // JavaScript to load MCQ
            ?>
            <script>
            jQuery(document).ready(function($) {
                const widgetId = '<?php echo $widget_id; ?>';
                const wrapSelector = '#mcq-wrap-<?php echo $widget_id; ?>';
                
                // Load MCQ via AJAX
                $.post('<?php echo admin_url('admin-ajax.php'); ?>', {
                    action: 'load_mcq_v46',
                    qid: <?php echo $qid; ?>,
                    widget_id: '<?php echo $widget_id; ?>'
                }, function(res) {
                    if (res.success) {
                        $(wrapSelector + ' .mcq-content-area').html(res.data.html);
                        
                        // Add animation classes
                        if ('<?php echo $btn_anim; ?>' !== '') {
                            $(wrapSelector + ' .mcq-submit-btn').addClass('<?php echo $btn_anim; ?>');
                        }
                        if ('<?php echo $opt_anim; ?>' !== '') {
                            $(wrapSelector + ' .mcq-option-label').addClass('<?php echo $opt_anim; ?>');
                        }
                    } else {
                        $(wrapSelector + ' .mcq-content-area').html('<div style="padding:30px; background:#f8d7da; border:1px solid #f5c6cb; border-radius:8px; text-align:center;"><strong>Error loading quiz.</strong></div>');
                    }
                });
                
                // Timer countdown
                <?php if ($expiry_ts > 0): ?>
                const expiryTimestamp = <?php echo $expiry_ts; ?>;
                const timerInterval = setInterval(function() {
                    const now = Math.floor(Date.now() / 1000);
                    const diff = expiryTimestamp - now;
                    
                    if (diff <= 0) {
                        clearInterval(timerInterval);
                        location.reload();
                        return;
                    }
                    
                    const days = Math.floor(diff / 86400);
                    const hours = Math.floor((diff % 86400) / 3600);
                    const minutes = Math.floor((diff % 3600) / 60);
                    const seconds = Math.floor(diff % 60);
                    
                    let timerText = 'Closing in: ';
                    if (days > 0) timerText += days + 'd ';
                    timerText += hours + 'h ' + minutes + 'm ' + seconds + 's';
                    
                    $('#timer-<?php echo $widget_id; ?>').text(timerText);
                }, 1000);
                <?php endif; ?>
                
                // Option selection handling
                $(document).on('change', wrapSelector + ' input[type="radio"]', function() {
                    const $grid = $(this).closest('.mcq-grid');
                    $grid.find('.mcq-option-label').removeClass('is-selected');
                    if (this.checked) {
                        $(this).closest('.mcq-option-label').addClass('is-selected');
                    }
                });
            });
            </script>
            <?php
        }
    }
    
    $widgets_manager->register(new MCQ_Master_Widget_V46());
});

// ============================================================================
// 6. AJAX HANDLERS - LOAD & SUBMIT
// ============================================================================

add_action('wp_ajax_load_mcq_v46', 'handle_load_mcq_v46');
add_action('wp_ajax_nopriv_load_mcq_v46', 'handle_load_mcq_v46');

function handle_load_mcq_v46() {
    $qid = intval($_POST['qid']);
    $widget_id = sanitize_text_field($_POST['widget_id']);
    
    // Validate quiz
    $quiz_post = get_post($qid);
    if (!$quiz_post || $quiz_post->post_type !== 'quiz') {
        wp_send_json_error('Invalid quiz');
    }
    
    // Check expiry
    $expiry = get_post_meta($qid, '_quiz_expiry', true);
    if ($expiry && strtotime($expiry) < time()) {
        wp_send_json_error(array(
            'html' => '<div style="padding:30px; background:#f8d7da; border:1px solid #f5c6cb; border-radius:8px; text-align:center;"><strong>This quiz has expired.</strong></div>'
        ));
    }
    
    $questions = get_post_meta($qid, '_quiz_questions', true);
    $fields = get_post_meta($qid, '_enabled_fields', true);
    $is_required = get_post_meta($qid, '_is_required', true);
    
    if (empty($questions) || !is_array($questions)) {
        wp_send_json_error(array(
            'html' => '<div style="padding:30px; background:#fff3cd; border:1px solid #ffc107; border-radius:8px; text-align:center;"><strong>No questions found in this quiz.</strong></div>'
        ));
    }
    
    ob_start();
    ?>
    <div class="mcq-final-wrap" 
         data-qid="<?php echo esc_attr($qid); ?>" 
         data-popup="<?php echo !empty($fields) ? 'yes' : 'no'; ?>" 
         data-required="<?php echo esc_attr($is_required); ?>"
         data-widget-id="<?php echo esc_attr($widget_id); ?>">
        
        <form class="mcq-main-form">
            <?php foreach($questions as $i => $q): ?>
            <div class="q-block" data-idx="<?php echo esc_attr($i); ?>">
                <p class="mcq-q-text">
                    <strong>Q<?php echo esc_html($i + 1); ?>. <?php echo esc_html($q['question']); ?></strong>
                </p>
                <div class="mcq-grid">
                    <?php foreach(array('a','b','c','d') as $o): ?>
                    <label class="mcq-option-label">
                        <input type="radio" name="q_<?php echo esc_attr($i); ?>" value="<?php echo esc_attr($o); ?>" data-index="<?php echo esc_attr($i); ?>"> 
                        <span class="opt-text"><?php echo strtoupper($o); ?>. <?php echo esc_html($q[$o]); ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <div class="error-txt">⚠️ Please select an answer</div>
            </div>
            <?php endforeach; ?>
            
            <button type="submit" class="mcq-submit-btn">Finish Exam</button>
        </form>
        
        <!-- Registration Popup -->
        <div class="lead-modal">
            <div class="mcq-popup-inner">
                <h3 style="margin-top:0; margin-bottom:20px;">Identity Information</h3>
                <p style="color:#64748b; margin-bottom:25px;">Please provide your details to see results.</p>
                <form class="pop-form">
                    <?php if(!empty($fields)): ?>
                        <?php foreach($fields as $f): ?>
                        <div class="f-wrap" style="margin-bottom:15px;">
                            <label style="display:block; margin-bottom:5px; font-weight:600;">
                                <?php echo esc_html(ucfirst($f)); ?>
                            </label>
                            <input type="text" name="<?php echo esc_attr($f); ?>" required>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    <button type="submit" class="pop-submit-btn">Submit & View Results</button>
                </form>
            </div>
        </div>
        
        <!-- Success Message -->
        <div class="inline-success-box">
            <h3 style="margin-top:0;">Congratulations!</h3>
            <p>You have successfully completed the test.</p>
            <p style="margin-top:15px;">Redirecting in <span class="redir-timer" style="font-weight:bold; font-size:20px;">0</span> seconds.</p>
        </div>
    </div>
    <?php
    
    wp_send_json_success(array('html' => ob_get_clean()));
}

add_action('wp_ajax_submit_mcq_v46', 'handle_submit_mcq_v46');
add_action('wp_ajax_nopriv_submit_mcq_v46', 'handle_submit_mcq_v46');

function handle_submit_mcq_v46() {
    // Security: Verify nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'mcq_submit_' . $_POST['qid'])) {
        wp_send_json_error('Security validation failed');
    }
    
    $qid = intval($_POST['qid']);
    $ans = isset($_POST['ans']) ? $_POST['ans'] : array();
    $info = isset($_POST['info']) ? $_POST['info'] : array();
    
    // Validate quiz
    $quiz_post = get_post($qid);
    if (!$quiz_post || $quiz_post->post_type !== 'quiz') {
        wp_send_json_error('Invalid quiz');
    }
    
    // Check expiry (server-side validation)
    $expiry = get_post_meta($qid, '_quiz_expiry', true);
    if ($expiry && strtotime($expiry) < time()) {
        wp_send_json_error('Quiz has expired');
    }
    
    $questions = get_post_meta($qid, '_quiz_questions', true);
    $score = 0;
    $details = array();
    
    if (!is_array($questions)) {
        wp_send_json_error('No questions found');
    }
    
    foreach($questions as $i => $q) {
        $user_answer = isset($ans[$i]) ? sanitize_text_field($ans[$i]) : 'N/A';
        $is_correct = ($user_answer === $q['correct']);
        
        if($is_correct) $score++;
        
        $details[] = array(
            'q' => sanitize_text_field($q['question']),
            'u' => $user_answer,
            'c' => sanitize_text_field($q['correct']),
            'ok' => $is_correct
        );
    }
    
    // Save submission
    $submission_title = !empty($info['name']) ? 'Result: ' . sanitize_text_field($info['name']) : 'Result: Guest';
    $sid = wp_insert_post(array(
        'post_type' => 'quiz_submission',
        'post_title' => $submission_title,
        'post_status' => 'publish',
        'post_author' => get_current_user_id()
    ));
    
    if ($sid) {
        update_post_meta($sid, '_submission_details_array', $details);
        update_post_meta($sid, '_submission_score', "$score / " . count($questions));
        update_post_meta($sid, '_submission_quiz_id', $qid);
    }
    
    // Save lead info if provided
    if (!empty($info)) {
        $lead_title = sanitize_text_field($info['name']);
        $lid = wp_insert_post(array(
            'post_type' => 'quiz_leads',
            'post_title' => $lead_title,
            'post_status' => 'publish',
            'post_author' => get_current_user_id()
        ));
        
        if ($lid) {
            // Sanitize all info fields
            $sanitized_info = array_map('sanitize_text_field', $info);
            update_post_meta($lid, '_user_data', $sanitized_info);
            update_post_meta($lid, '_related_submission_id', $sid);
            update_post_meta($lid, '_quiz_id', $qid);
        }
    }
    
    // Get redirect settings
    $timer = absint(get_post_meta($qid, '_quiz_timer', true)) ?: 5;
    $setting_id = get_post_meta($qid, '_linked_setting_id', true);
    $redirect_url = home_url('/');
    
    if ($setting_id) {
        $custom_url = get_post_meta($setting_id, '_mcq_redirect_url', true);
        if (!empty($custom_url)) {
            $redirect_url = esc_url_raw($custom_url);
        }
    }
    
    wp_send_json_success(array(
        'score' => $score,
        'total' => count($questions),
        'timer' => $timer,
        'redir' => wp_sanitize_redirect($redirect_url),
        'submission_id' => $sid
    ));
}

// ============================================================================
// 7. FRONTEND JAVASCRIPT ENGINE
// ============================================================================

add_action('wp_footer', function() {
    ?>
    <script>
    jQuery(document).ready(function($) {
        // Main form submission
        $(document).on('submit', '.mcq-main-form', function(e) {
            e.preventDefault();
            
            const $form = $(this);
            const $wrap = $form.closest('.mcq-final-wrap');
            const widgetId = $wrap.data('widget-id');
            const isRequired = $wrap.data('required') === 'yes';
            const hasPopup = $wrap.data('popup') === 'yes';
            
            let answers = {};
            let hasError = false;
            
            // Validate and collect answers
            $wrap.find('.q-block').each(function() {
                const $block = $(this);
                const index = $block.data('idx');
                const selected = $block.find('input[type="radio"]:checked').val();
                
                if (isRequired && !selected) {
                    $block.find('.error-txt').fadeIn();
                    hasError = true;
                } else {
                    $block.find('.error-txt').hide();
                    answers[index] = selected || 'N/A';
                }
            });
            
            // Scroll to first error if any
            if (hasError) {
                const $firstError = $wrap.find('.error-txt:visible').first();
                if ($firstError.length) {
                    $('html, body').animate({
                        scrollTop: $firstError.offset().top - 150
                    }, 500);
                }
                return;
            }
            
            // Store answers in wrapper data
            $wrap.data('answers', answers);
            
            // Show popup if needed, otherwise submit directly
            if (hasPopup) {
                $('#' + widgetId + ' .lead-modal').fadeIn();
            } else {
                submitQuiz($wrap, {});
            }
        });
        
        // Popup form submission
        $(document).on('submit', '.pop-form', function(e) {
            e.preventDefault();
            
            const $form = $(this);
            const $wrap = $form.closest('.mcq-final-wrap');
            const formData = {};
            
            // Collect form data
            $form.serializeArray().forEach(function(item) {
                formData[item.name] = item.value;
            });
            
            // Close modal and submit
            $wrap.find('.lead-modal').fadeOut();
            submitQuiz($wrap, formData);
        });
        
        // Close popup on overlay click
        $(document).on('click', '.lead-modal', function(e) {
            if ($(e.target).hasClass('lead-modal')) {
                $(this).fadeOut();
            }
        });
        
        // Escape key to close popup
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape') {
                $('.lead-modal').fadeOut();
            }
        });
        
        // Submit quiz function
        function submitQuiz($wrap, userInfo) {
            const qid = $wrap.data('qid');
            const answers = $wrap.data('answers');
            const nonce = '<?php echo wp_create_nonce("mcq_submit_" . $qid); ?>'.replace(/&quot;/g, '"');
            
            $.post('<?php echo admin_url('admin-ajax.php'); ?>', {
                action: 'submit_mcq_v46',
                qid: qid,
                ans: answers,
                info: userInfo,
                nonce: nonce
            }, function(res) {
                if (res.success) {
                    // Hide form and show success message
                    $wrap.find('.mcq-main-form').fadeOut(300, function() {
                        const $successBox = $wrap.find('.inline-success-box');
                        $successBox.fadeIn(300);
                        
                        // Update score display if needed
                        if (res.data.score !== undefined) {
                            $successBox.find('h3').after('<p style="font-size:18px; margin:15px 0;"><strong>Your Score: ' + res.data.score + ' / ' + res.data.total + '</strong></p>');
                        }
                        
                        // Countdown timer
                        let countdown = res.data.timer;
                        const $timer = $successBox.find('.redir-timer');
                        $timer.text(countdown);
                        
                        const countdownInterval = setInterval(function() {
                            countdown--;
                            $timer.text(countdown);
                            
                            if (countdown <= 0) {
                                clearInterval(countdownInterval);
                                window.location.href = res.data.redir;
                            }
                        }, 1000);
                    });
                } else {
                    alert('Error: ' + (res.data || 'Submission failed'));
                }
            }).fail(function() {
                alert('An error occurred. Please try again.');
            });
        }
    });
    </script>
    <?php
});

// ============================================================================
// 8. PLUGIN ACTIVATION/DEACTIVATION
// ============================================================================

register_activation_hook(__FILE__, function() {
    // Flush rewrite rules
    flush_rewrite_rules();
    
    // Create default setting if none exists
    $settings = get_posts(array('post_type' => 'mcq_setting', 'numberposts' => 1));
    if (empty($settings)) {
        $default_setting_id = wp_insert_post(array(
            'post_type' => 'mcq_setting',
            'post_title' => 'Default Redirect',
            'post_status' => 'publish'
        ));
        update_post_meta($default_setting_id, '_mcq_redirect_url', home_url());
    }
});

register_deactivation_hook(__FILE__, function() {
    flush_rewrite_rules();
});
				
			
				
					/* ডেস্কটপ ও ল্যাপটপের জন্য (1025px এর বেশি) */
@media only screen and (min-width: 1025px) {
  .elementor-menu-cart__container {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    right: auto !important;
    width: 80% !important;
    max-width: 600px !important;
    height: auto !important;
    max-height: 90vh !important;
    overflow-y: auto !important;
    z-index: 99999 !important;
  }
}

/* ট্যাবলেটের জন্য (768px থেকে 1024px) */
@media only screen and (min-width: 768px) and (max-width: 1024px) {
  .elementor-menu-cart__container {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    right: auto !important;
    width: 60% !important;
    max-width: 500px !important;
    height: auto !important;
    max-height: 90vh !important;
    overflow-y: auto !important;
    z-index: 99999 !important;
  }
}

/* মোবাইলের জন্য (767px এর কম) */
@media only screen and (max-width: 767px) {
  .elementor-menu-cart__container {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    right: auto !important;
    width: 90% !important;
    max-width: 400px !important;
    height: auto !important;
    max-height: 85vh !important;
    overflow-y: auto !important;
    z-index: 99999 !important;
  }
}