<?php defined('ABSPATH') || die('Cheatin\' uh?'); ?>

<?php
$product_id=187;
function restore_original_product_data($product_id) {
    $product = wc_get_product($product_id);
    if (!$product) return;

    $original_title = $product->get_meta('_original_title', true);
    $original_description = $product->get_meta('_original_description', true);

    if (!empty($original_title)) {
        $product->set_name($original_title);
    }
    if (!empty($original_description)) {
        $product->set_description($original_description);
    }

    $product->save();
}

?>

<div style="width:100%;display:flex;align-items:center;justify-content:center;">
    <div class="optimize-wrapper">
        <div class="">
            <div class="settings-panel">
                <div>Fine tune AI optimization</div>
                <div class="form-group">
                    <label>Optimization Mode</label>
                    <select id="modeSelect">
                        <option value="all">Optimize All Products</option>
                        <option value="category">Optimize by Category</option>
                        <option value="single">Optimize One Product</option>
                    </select>
                </div>

                <div class="form-group hidden" id="productSelectGroup">
                    <label>Select Product</label>
                    <select id="productSelect">
                        <option value="">Loading products...</option>
                    </select>
                </div>

                <div class="form-group hidden" id="categorySelectGroup">
                    <label>Select Category</label>
                    <select id="categorySelect">
                        <option value="">Loading categories...</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Tone or Audience</label>
                    <select id="toneSelect">
                        <option value="">Select</option>
                        <option value="Sporty">Sporty</option>
                        <option value="Luxurious">Luxurious</option>
                        <option value="Minimalist">Minimalist</option>
                        <option value="SEO Friendly">SEO Friendly</option>
                        <option value="Professional">Professional</option>
                        <option value="Playful">Playful</option>
                        <option value="custom">Custom</option>
                    </select>
                    <input type="text" id="customTone" class="hidden" placeholder="Enter custom tone...">
                </div>

                <label><input type="checkbox" id="autoSave"> Auto-save to WooCommerce</label>
                 <div class="form-group checkbox-group">
                </div>
            </div>

            <div class="ai-feed-optimizer">
                <h5>🧠 AI Product Feed Optimizer</h5>
                <p class="subtext">Use AI to automatically optimize your WooCommerce product data with improved titles, descriptions, and tone.</p>
                <button id="bulkOptimizeBtn">Generate Suggestions</button>
                <div id="aiLoading" class="loading hidden">Loading suggestions<span class="dots"></span></div>

                <div id="aiResults" class="ai-results hidden">
                    <h4></h4>
                    <div class="variants"></div>
                </div>
            </div>
            <div class="skip-optimization">
                <span>Skip optimization and finish feed</span>
                <button class="skip-opt-finish">Finish</button>
            </div>
        </div>
    </div>
</div>

<style>
    .optimize-wrapper{
        box-shadow:0 4px 30px rgba(0, 0, 0, 0.1);
        border-radius:1vw;
        padding:1vw;
        width:50vw;
        margin-top:4vw;
    }    
    .settings-panel{
        background: #f5f8fa;
        border-radius: 1vw;
        padding: 1vw 2vw;
        box-shadow: inset 0 0 8px #e1e8ed;
        font-size:1.4vw;
        font-weight:600;
    }
    .form-group {
        margin-bottom: 1vw;
        margin-top:1vw;
    }
    .settings-panel label{
        font-size:1vw;
        font-weight:500;
    }
    .ai-feed-optimizer {
        margin: 2rem auto;
        background: #fff;
        padding: 1vw;
        border-radius: 1vw;
        background: rgba(0, 128, 255, 0.05);
        border-left: 5px solid #0073aa;
    }
    .ai-feed-optimizer h5 {
        font-size: 1.2vw;
        font-weight:600;
        margin-bottom: 0.5rem;
        color: #0073aa;
    }
    button {
        padding: 0.5vw 2vw;
        font-size: 1vw;
        background: #b5eedf;
        color: black;
        border: none;
        border-radius: 2vw;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }
    button:hover {
        background: #a4e7d7;
        transform: translateY(-1px);
    }
    .subtext {
        font-size: 0.8vw;
        margin-bottom: 1.5vw;
        font-weight:500;
    }
    label {
        font-weight: 600;
        display: block;
        margin-bottom: 0.4rem;
    }   
    #modeSelect{
        font-size:0.9vw;
    }
    #productSelect{
        font-size:0.9vw;
    }
    #categorySelect{
        font-size:0.9vw;
    }
    #toneSelect{
        font-size:0.9vw;
    }

    input[type="text"], select {
        width: 100%;
        font-size:1vw;
        border: 1px solid #ccc;
        border-radius: 0.5vw;
        transition: border-color 0.3s, box-shadow 0.3s;
    }
    input[type="text"], option{
        font-size:0.9vw;
    }
    input[type="text"]:focus, select:focus {
        border-color: #66d5ba;
        box-shadow: 0 0 0 3px rgba(181, 238, 223, 0.4);
        outline: none;
    }

    .checkbox-group label {
        display: flex;
        align-items: center;
        font-weight: 500;
    }
    .hidden {
        display: none;
    }
    .ai-results {
        margin-top: 2rem;
        gap: 1vw;
        background-color:white;
        border:1px solid #e0e0e0;
        padding:1vw;
        border-radius:6px;
    }
    .variants {
        display: flex;
        flex-wrap:wrap;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap:1vw;
    }
    .variant {
        background: #f9f9f9;
        border: 1px solid #eee;
        padding: 1vw;
        border-radius:1vw;
        transition: transform 0.2s;
        width:20vw;
        padding:1vw;
    }
    .variant:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    }
    .variant h4 {
        font-size: 1vw;
        margin-bottom: 1vw;
    }
    .variant .title {
        font-weight: bold;
        margin-bottom: 0vw;
    }
    .variant .desc {
        font-size: 0.9vw;
        color: #333;
        margin-bottom: 0.5vw;
    }
    .variant .metrics {
        font-size: 0.9vw;
        color: #555;
        display: flex;
        justify-content: space-between;
        margin-bottom: 0.5vw;
    }
    .variant button {
        background: #1abc9c;
        color: white;
        font-weight: 600;
        border-radius: 2vw;
    }
    .variant button:hover {
        background: #218838;
    }
    .loading {
        font-size: 1vw;
        font-weight: 500;
        padding: 1vw;
        color: #333;
    }
    .dots::after {
        content: '';
        display: inline-block;
        width: 1vw;
        text-align: left;
        animation: dots 1.2s steps(3, end) infinite;
    }

    @keyframes dots {
        0% { content: ''; }
        33% { content: '.'; }
        66% { content: '..'; }
        100% { content: '...'; }
    }

    .product-list {
        display: flex;
        flex-wrap: wrap;
        gap: 1vw;
    }
    .success-message{
        width:100%;
        margin:0;
        margin-top:1vw;
    }
    .notice.updated{
        width:100%;
        margin:0;
        margin-top:1vw;
    }
    #startOptimizationBtn{
        width:10vw;
        padding:0.5vw;
        border-radius:0.5vw;
        font-size:0.8vw;
        padding:0.5vw 2vw;
    }
    #customTone{
        margin-top:1vw;
    }

    .notice.info{
        width:100%;
        margin:0;
        margin-top:1vw;
    }
    .selected-info{
        border-radius:1vw;
        font-size:1vw;
    }
    .skip-optimization{
        display:flex;
        flex-direction:column;
        font-weight:600;
        gap:0.3vw;
        padding-bottom:1vw;
        border-left: 5px solid #b5eedf;
        background: rgba(0, 128, 255, 0.05);
        padding:1vw;
        border-radius: 1vw;
        font-size:1vw;
    }
    .skip-opt-finish{
       background:  #2271b1;
       color:#fff;
       border-radius:0.5vw;
       width:10vw;
       font-size:1vw;
    }
    .skip-opt-finish:hover{
        background:  #2271b1;
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    }

</style>


<script>
(function ($) {

    // Toggle custom tone input
    $("#toneSelect").on("change", function () {
        $("#customTone").toggleClass("hidden", $(this).val() !== "custom");
    });

    // Toggle product/category select fields based on mode
    $("#modeSelect").on("change", function () {
        const mode = $(this).val();
        $("#productSelectGroup").toggleClass("hidden", mode !== "single");
        $("#categorySelectGroup").toggleClass("hidden", mode !== "category");

        if (mode === "single") {
            loadProducts();
        } else if (mode === "category") {
            loadCategories();
        }
    });

    function loadCategories() {
        $("#categorySelect").html('<option>Loading categories...</option>');
        $.post(sqQuery.ajaxurl, {
            prod_nonce: sqQuery.nonce,
            action: 'get_woo_categories',
        }).done(function(response) {
             const options = response.data.map(cat =>
                `<option value="${cat.id}">${cat.name}</option>`
            );
            $("#categorySelect").html(`<option value="">Select Category</option>` + options.join(''));
        });
    }

    function loadProducts() {
        $("#productSelect").html('<option>Loading products...</option>');
        $.post(sqQuery.ajaxurl, {
            prod_nonce: sqQuery.nonce,
            action: 'get_woo_products',
        }).done(function(response) {
             const options = response.data.map(cat =>
                `<option value="${cat.id}">${cat.name}</option>`
            );
            $("#productSelect").html(`<option value="">Select Product</option>` + options.join(''));
        });
    }

    //Select tone and generate sugestions
    function getSelectedTone() {
        const tone = $('#toneSelect').val();
        if (tone === 'custom') {
            return $('#customTone').val().trim();
        }
        return tone;
    }
    function loadAiPreview() {
        $("#aiLoading").removeClass("hidden");
        $("#aiResults").addClass("hidden");

        const tone = getSelectedTone();
        const mode = $("#modeSelect").val();
        let productId = null;
        let categoryId = null;

        if (mode === 'single') {
            productId = $("#productSelect").val();
        } else if (mode === 'category') {
            categoryId = $("#categorySelect").val();
        }
        
        $.post(sqQuery.ajaxurl, {
            prod_nonce: sqQuery.nonce,
            action: 'prod_get_ai_preview_results',
            tone: tone,
            product_id: productId,
            category_id: categoryId,
        }).done(function(response) {
             $("#aiLoading").addClass("hidden");
            if (response.success) { 
                const data = response.data;
                const container = $("#aiResults").removeClass("hidden");
                container.find("h3").text(`🎯 Suggestions for: ${data.original_title}`);
                const variantsWrapper = container.find(".variants").empty();

                data.variants.forEach((v, i) => {
                    const variantHtml = `
                    <div class="variant">
                        <h4>Variant ${i + 1}</h4>
                        <p class="title">${v.title}</p>
                        <p class="desc">${v.description}</p>
                        <div class="metrics">

                        </div>
                        <button class="select-variant" data-variant-index="${i}">Select</button>
                    </div>`;
                    variantsWrapper.append(variantHtml);})
                    variantsWrapper.find('.select-variant').click(function() {
                    const index = $(this).data('variant-index');
                    const variant = data.variants[index];
                    onSelectVariant(variant,index);
            });
            }
            else {
                console.error('Error from server:', response.data);
            }
        });
    }

    $("#bulkOptimizeBtn").click(loadAiPreview);

    let selectedVariant = null;
    function onSelectVariant(variant,index) {
        selectedVariant = variant;
        const results = document.getElementById('aiResults');
        let infoMsg = results.querySelector('.selected-info');
        if (!infoMsg) {
            infoMsg = document.createElement('div');
            infoMsg.className = 'selected-info';
            infoMsg.style.marginTop = '1rem';
            infoMsg.style.padding = '0.8rem';
            infoMsg.style.background = '#b5eedf';
            infoMsg.style.borderRadius = '8px';
            results.appendChild(infoMsg);
        }
        infoMsg.textContent = `You selected variant #${index + 1} - "${variant.title}". This optimization flavor will be applied to other products when batch optimizing.`;

        let startBtn = document.getElementById('startOptimizationBtn');
            if (!startBtn) {
                startBtn = document.createElement('button');
                startBtn.id = 'startOptimizationBtn';
                startBtn.className = 'button button-primary';
                startBtn.style.marginTop = '0.5rem';
                startBtn.textContent = 'Start Optimization';
                startBtn.onclick = function () {
                    startBatchOptimization();
                };
                results.appendChild(startBtn);
            } else {
                startBtn.classList.remove('hidden');
            }
        }

        let optimizationFinished = false;
        function startOptimizingAnimation($btn) {
            let dotCount = 0;
            const maxDots = 3;
            $btn.prop("disabled", true);

            const intervalId = setInterval(() => {
                dotCount = (dotCount + 1) % (maxDots + 1);
                const dots = '.'.repeat(dotCount);
                $btn.text(`Optimizing${dots}`);
            }, 500);

            return intervalId;
        }

        function stopOptimizingAnimation($btn, intervalId) {
            clearInterval(intervalId);
            $btn.text("Finish").prop("disabled", false);
        }

        function startBatchOptimization() {
            if (optimizationFinished) return;

            $(".skip-optimization").hide();
            const tone = getSelectedTone();
            const mode = $('#modeSelect').val();
            const productId = $('#productSelect').val();
            const categoryId = $('#categorySelect').val();
            const autoSave = $('#autoSave').is(':checked') ? 1 : 0;
            const $btn = $("#startOptimizationBtn");
            const animId = startOptimizingAnimation($btn);
            const $startMsg = $('<div class="notice info"></div>').text("🔄 Optimization started. This may take a while...");
            $("#aiResults").append($startMsg);

            const $progressContainer = $(`
                <div id="progressContainer" style="margin-top:15px; width:100%;">
                    <div id="progressBar" style="height:20px; width:0%; background-color:#0073aa; border-radius:5px; transition:width 0.4s;"></div>
                    <div id="progressText" style="margin-top:5px; font-weight:500;">Initializing...</div>
                </div>
            `);
            $("#aiResults").append($progressContainer);

            let fProgress = 0;
            const fakeAnim = setInterval(() => {
                if (fProgress < 15) {
                    fProgress += 3;
                    $("#progressBar").css("width", fProgress + "%");
                    $("#progressText").text(`Starting optimization... (${fProgress}%)`);
                }
            }, 800);

            // Poll actual backend progress
           let progressInterval = setInterval(() => {
            $.post(sqQuery.ajaxurl, { action: 'get_ai_optimization_progress' }, function (res) {
                if (res.success && res.data.total > 0) {
                const { optimized, total, percent, status } = res.data;

                // update progress bar UI
                $("#progressBar").css("width", percent + "%");
                $("#progressText").text(`Optimized ${optimized}/${total} products (${percent}%)`);

                // if still running
                if (status === 'in_progress') {
                    $("#aiResults .notice.info").text("🔄 Optimization in progress...");
                }

                // if finished
                if (status === 'done') {
                    clearInterval(progressInterval);

                    $("#progressBar").css("width", "100%");
                    $("#progressText").text("🎉 Optimization complete (100%)");
                    $("#aiResults .notice.info").fadeOut(400, function() {
                        $(this).remove();
                    });
                    const $doneMsg = $('<div class="notice updated"></div>')
                        .text("🎉 All products optimized!");
                    $("#aiResults").append($doneMsg);

                    // Update button state
                    $("#startOptimizationBtn")
                        .prop("disabled", false)
                        .text("Finish")
                        .addClass("finish-optimization-feed");
                }
                }
            });
            }, 2000);

            
            $.post(sqQuery.ajaxurl, {
                prod_nonce: sqQuery.nonce,
                action: 'prod_batch_optimization',
                tone: tone,
                mode: mode,
                product_id: productId,
                category_id: categoryId,
                auto_save: autoSave
            }).done(function(response) {
                optimizationFinished = true;

                clearInterval(progressInterval);
                clearInterval(fakeAnim);
                clearInterval(animId);
                $("#aiResults .notice.info").fadeOut(400, function() {
                    $(this).remove();
                });
                $("#progressBar").css("width", "100%");
                $("#progressText").text("🎉 Optimization complete (100%)");

                $btn.prop("disabled", false).text("Finish").addClass("finish-optimization-feed");
                $btn.off("click").on("click", function() {
                    finishOptimizationFeed();
                });

               // const $doneMsg = $('<div class="notice updated"></div>').text("🎉 All products optimized!");
                $("#aiResults").append($doneMsg);

                $startMsg.fadeOut(600, function() { $(this).remove(); });
            });

        }


    $(".skip-opt-finish").click(finishOptimizationFeed);
    function finishOptimizationFeed(){
         $.post(sqQuery.ajaxurl, {
                prod_nonce: sqQuery.nonce,
                action:"prod_finish_optimization_feed"
            }).done(function() {
                  window.location.href = ajaxurl.replace('admin-ajax.php', 'admin.php?page=manage_feeds');}
            )
    }

}(jQuery));
</script>
