
<?php defined('ABSPATH') || die('Cheatin\' uh?'); ?>
<?php 
    global $wpdb;
    $data = @$wpdb->get_results(
        $wpdb->prepare("
            SELECT meta.meta_id, meta.post_id, meta.meta_value AS type
            FROM {$wpdb->prefix}postmeta AS meta, {$wpdb->prefix}posts AS posts
            WHERE meta.post_id = posts.id 
            AND posts.post_type LIKE '%s' 
            AND meta.meta_key='_product_attributes' AND meta.meta_value NOT LIKE \"%{}\"", 
            array('%product%')
        )
    );

    $is_brand = $is_gtin = $is_mpn = 0;
    foreach ($data as $val) {
        $arr = unserialize($val->type);
        foreach ($arr as $name) {
            if (in_array(strtolower($name['name']), ['brand'])) $is_brand = 1;
            if (in_array(strtolower($name['name']), ['gtin'])) $is_gtin = 1;
            if (in_array(strtolower($name['name']), ['mpn'])) $is_mpn = 1;
        }
    }
?>

    <div class="product-settings-wrapper">
        <div class="product-settings-header">
            <div>Product Data Settings</div>
            <div class="product-settings-intro">
                <img src="https://storage.googleapis.com/prod_perf/prod.png" alt="Guide Image">
                <p>Use this guide to format your product information for Merchant Center. Google uses this data to ensure it's matched to the right queries. Proper formatting helps create successful ads and free listings for your products.</p>
            </div>
            
            <div class="product-settings-ai">
                <h5>🧠 AI Suggestions</h5>
                <p>Let AI help you automatically fill or optimize your product attributes based on current data.</p>
                <button class="btn ai-generate-btn">Generate Suggestions</button>
                <div class="ai-output" style="display: none;height:50vh;overflow-y:scroll;">
                <div class="loading-dots" style="display:none;">Generating smart suggestions<span class="dots"></span></div>
                <ul class="ai-suggestion-list"></ul>
            </div>
        </div>
    </div>

    <div class="product-settings-content">
        <?php 
            include_once _PROD_CLASSES_DIR_ . 'ObjController.php';
            $google_sopping = PROD_Classes_ObjController::getClass('PROD_Classes_Attributes');
            $req_attributes = $google_sopping->get_req_channel_attributes();
            $get_required_for_attributes = $google_sopping->get_required_forchannel__attributes();
        ?>
        <div class="field-group">
            <div class="field-section">
                <div class="section-title success"><span>!</span>Required fields:</div>
                <p>If you don’t submit this attribute, your product won’t be able to appear in ads or free listings.</p>
                <?php foreach ($req_attributes as $row_key => $row_value): ?>
                    <div class="field-row">
                        <div class="field-label">
                            <span class="dot success"></span>
                            <?php echo $row_key; ?>
                            <strong>[<?php echo $row_value['name']; ?>]</strong>
                        </div>
                        <a class="info-link" href="<?php echo $row_value['support_link']; ?>" target="_blank">?</a>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="field-section">
                <div class="section-title warning"><span>!</span>Conditionally Required Fields:</div>
                <p>Find out more at <a href="https://support.google.com/merchants/answer/7052112?hl=en" target="_blank">Google Merchant Center Help</a></p>

                <div class="expand-fields">
                    <img class="dropdown-btn" src="https://storage.googleapis.com/prod_perf/top.png" alt="Toggle">
                    <div class="expand-label">show</div>
                </div>

                <div class="show-no-req-fields closed">
                    <div class="field-header">
                        <div>Attribute</div>
                        <div>When to Use?</div>
                        <div>Include</div>
                    </div>

                    <?php $allIncludedFields = PROD_Classes_Helpers_Tools::getOption("included_fields") ?? [];
                          $currentFeedId = PROD_Classes_Helpers_Tools::getOption("edit-feed");
                          $currentFeedId = preg_replace('/\.xml$/i', '', $currentFeedId);
                          $includedFields = $allIncludedFields[$currentFeedId]['include_fields'] ?? [];

                          $enabledAttributes = [];
                          $shippingData = [];
                        
                        foreach ($includedFields as $field) {
                            if (is_string($field)) {
                                $enabledAttributes[] = $field;
                            } elseif (is_array($field) && isset($field['shipping'])) {
                                $shippingData = $field['shipping'];
                            }
                        }
                        ?>

                        <?php foreach ($get_required_for_attributes as $key => $val): 
                            $name = $val['name'];
                            $isIncluded = in_array($name, $enabledAttributes);
                        ?>

                        <div class="field-row">
                            <div class="field-label">
                                <span class="dot warning"></span>
                                <?php echo htmlspecialchars($key); ?>
                                <strong>[<?php echo htmlspecialchars($name); ?>]</strong>
                            </div>
                            <a class="info-link" href="<?php echo htmlspecialchars($val['support_link']); ?>" target="_blank">?</a>
                            <?php if ($name !== 'shipping'): ?>
                                <div class="toggle-wrapper">
                                    <label class="switch">
                                        <input type="checkbox" name="include_fields[]" class="toggle-include" data-attribute="<?php echo htmlspecialchars($name); ?>" <?php echo $isIncluded ? 'checked' : ''; ?>>
                                        <span class="slider round"></span>
                                    </label>
                                </div>
                            <?php else: ?>
                                <div class="shipping-fields">
                                    <div class="input-group">
                                        <input type="text" name="shipping[country]" placeholder="Country" value="<?php echo htmlspecialchars($shippingData['country'] ?? ''); ?>">
                                        <input type="text" name="shipping[region]" placeholder="Region" value="<?php echo htmlspecialchars($shippingData['region'] ?? ''); ?>">
                                        <input type="text" name="shipping[price]" placeholder="Price" value="<?php echo htmlspecialchars($shippingData['price'] ?? ''); ?>">
                                        <input type="text" name="shipping[service]" placeholder="Service" value="<?php echo htmlspecialchars($shippingData['service'] ?? ''); ?>">
                                        <input type="text" name="shipping[min_handling_time]" placeholder="Min handling time" value="<?php echo htmlspecialchars($shippingData['min_handling_time'] ?? ''); ?>">
                                        <input type="text" name="shipping[max_transit_time]" placeholder="Max transit time" value="<?php echo htmlspecialchars($shippingData['max_transit_time'] ?? ''); ?>">
                                        <input type="text" name="shipping[max_handling_time]" placeholder="Max handling time" value="<?php echo htmlspecialchars($shippingData['max_handling_time'] ?? ''); ?>">
                                        <input type="text" name="shipping[min_transit_time]" placeholder="Min transit time" value="<?php echo htmlspecialchars($shippingData['min_transit_time'] ?? ''); ?>">
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <div class="button-row" style="display:none">
            <div class="btn">-Delete</div>
            <div class="btn">+Add field mapping</div>
            <div class="btn">+Add custom field</div>
        </div>
        <button  class="btn save-prod-fields" style="margin-top:1vw;">Next</button>
    </div>
</div>

<style>
    body, html {
        margin: 0;
        font-family: 'Segoe UI', sans-serif;
        background-color: #f4f4f4;
    }
    .product-settings-wrapper {
        width: 100%;
        padding: 50px 10%;
        box-sizing: border-box;
    }
    .product-settings-header {
        background: white;
        padding: 2vw;
        border-radius:1vw;
        font-size:1.4vw;
        font-weight:600;
        box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    }
    .product-settings-header p {
        font-size: 0.8vw;
        width:40vw;
        margin-top:-0.5vw;
    }
    .product-settings-intro {
        display: flex;
        gap: 1vw;
        align-items: center;
    }
    .product-settings-intro img {
        width: 8vw;
        height: 8vw;
        border-radius:1vw;
    }
    .product-settings-ai {
        margin-top: 1vw;
        background: rgba(0, 128, 255, 0.05);
        padding: 1vw;
        border-left: 0.3vw solid #0073aa;
        border-radius: 1vw;
    }
    .product-settings-ai h5 {
        font-size: 1.2vw;
        font-weight:600;
        color: #0073aa;
    }
    .product-settings-ai p {
        margin-top:-0.5vw;
    }
    .product-settings-content {
        background: white;
        margin-top: 2vw;
        padding: 1vw;
        border-radius: 1vw;
        box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    }
    .field-group {
        display: flex;
        flex-direction: column;
        gap: 4vw;
    }
    .field-section .section-title {
        display: flex;
        align-items: center;
        font-weight: 600;
        font-size: 1.2vw;
        margin-bottom: 1vw;
    }
    .field-section p{
        font-size:0.8vw;
        margin-top:-1vw;
    }
    .section-title span {
        width: 2vw;
        height: 2vw;
        border-radius: 50%;
        color: white;
        text-align: center;
        line-height: 2vw;
        margin-right: 1vw;
    }
    .section-title.success span {
        background-color: #4AC34A;
        font-size:1.2vw;
        width:1.5vw;
        height:1.5vw;
        display: flex;
        align-items: center;
        justify-content:center;
    }
    .section-title.warning span {
        background-color: #ffad75;
        font-size:1.2vw;
        width:1.5vw;
        height:1.5vw;
        display: flex;
        align-items: center;
        justify-content:center;
    }

    .field-row {
        display: flex;
        align-items: center;
        background: rgba(80, 125, 122, 0.2);
        padding: 0.5vw;
        border-radius: 0.5vw;
        margin-top: 1vw;
        font-size:1vw;
    }

    .field-label {
        width: 48%;
        display: flex;
        align-items: center;
        gap: 10px;
        font-weight: 500;
    }

    .dot {
        width: 1vw;
        height: 1vw;
        border-radius: 50%;
        display: inline-block;
    }
    .dot.success {
        background-color: #4AC34A;
    }
    .dot.warning {
        background-color: #ffad75;
    }

    .info-link {
        width: 1.7vw;
        height: 1.7vw;
        font-size:1vw;
        border-radius: 50%;
        background-color: black;
        color: white;
        text-align: center;
        font-weight: bold;
        text-decoration: none;
    }
    .expand-fields {
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 2vw;
        font-size:1vw;
        background: rgba(80, 125, 122, 0.2);
        border-radius: 0.5vw;
        padding: 0.5vw;
        margin-top:2vw;
    }
    .expand-label {
        font-weight: 700;
    }
    .dropdown-btn {
        width: 2vw;
        height: 2vw;
        transition: transform 0.3s ease;
    }
    .dropdown-btn.down {
        transform: rotate(180deg);
    }
    .show-no-req-fields.closed {
        display: none;
    }
    .field-header {
        display: flex;
        justify-content:space-between;
        padding-right:1vw;
        padding-left:1vw;
        font-weight: 500;
        font-size:1vw;
        margin-top:1vw;
    }
    .shipping-fields {
        margin-left: 2vw;
        width: 60%;
        display: flex;
        flex-direction: column;
        gap: 1vw;
    }
    .input-group {
        display: flex;
        flex-wrap: wrap;
        gap:0.5vw;
    }
    .input-group input {
        background: rgba(31, 105, 72, 0.2);
        border: none;
        font-weight: 500;
        border-radius: 4px;
    }
    .add-icon {
        font-size: 1.5rem;
        font-weight: 700;
        margin-bottom: 10px;
        cursor: pointer;
    }
    .button-row {
        margin-top: 30px;
        display: flex;
        gap: 15px;
        align-items: center;
    }
    .btn {
        padding:0.5vw 2vw;
        background-color: #b5eedf;
        border-radius: 2vw;
        font-weight: 600;
        font-size: 1vw;
        cursor: pointer;
        text-align: center;
        transition: background-color 0.3s ease;
        border: none;
        transition: all 0.3s ease;
    }
    .btn:hover {
        background-color: #a2e6d2;
        transform: translateY(-1px);
    }
    .toggle-wrapper {
        margin-left: auto;
    }
    .switch {
        right:3vw;
        position: relative;
        display: inline-block;
    }

    .switch input {
        opacity: 0;
        width: 0;
        height: 0;
    }

    .slider {
        position: absolute;
        cursor: pointer;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: 0.4s;
        border-radius:2vw;
        width: 3.5vw;
        height: 1.5vw;
    }

    .slider:before {
        position: absolute;
        content: "";
        height: 1vw;
        width: 1vw;
        left: 0.3vw;
        bottom: 0.2vw;
        background-color: white;
        transition: 0.4s;
        border-radius: 50%;
    }

    input:checked + .slider {
        background-color: #b5eedf;
    }

    input:checked + .slider:before {
        transform: translateX(2vw);
    }

    .ai-output {
        margin-top: 1vw;
        font-size:1vw;
        background: #fff;
        padding: 1vw;
        border-radius: 1vw;
        border: 1px solid #e0e0e0;
    }

    .ai-output ul {
        padding-left: 2vw;
        margin: 0;
    }

    .ai-output li {
        margin-bottom: 8px;
        text-decoration:none;
        font-size:0.8vw;
    }

    .loading-dots {
        font-weight: bold;
        font-size: 1vw;
        margin: 10px 0;
    }

    .loading-dots .dots::after {
        content: '';
        display: inline-block;
        animation: dots 1.2s steps(4, end) infinite;
        width: 1.2em;
        text-align: left;
    }

    @keyframes dots {
    0%, 20% {
        content: '';
    }
    40% {
        content: '.';
    }
    60% {
        content: '..';
    }
    80%, 100% {
        content: '...';
    }
    }

</style>


<script>
    (function ($){ 
    
        $(".save-prod-fields").click(function() {       
            let includedFields = [];
            let shippingData = {};
            let hasShippingData = false;
            
            $(".toggle-include:checked").each(function () {
                includedFields.push($(this).data("attribute"));
            });
            $(".input-group input").each(function () {
                const val = $(this).val().trim();
                const key = $(this).attr("placeholder").toLowerCase().replace(/\s+/g, "_");

                if (val !== "") {
                    hasShippingData = true;
                }
                if (val !== "") {
                    shippingData[key] = val; 
                }
            });

            if (hasShippingData) {
                includedFields.push({
                    shipping: shippingData
                });
            }
            $.post(sqQuery.ajaxurl, {
                prod_nonce: sqQuery.nonce,
                action: "save_prod_fields",
                include_fields: JSON.stringify(includedFields)
            })
            .done(function(response) {
                if(response) {
                    window.location.href = ajaxurl.replace('admin-ajax.php', 'admin.php?page=new_feed&tab=optimize_ai');
                    console.log(response.data);
                } else {
                    alert("Error saving feed");
                }
            });
        });
       
        $(".ai-generate-btn").on("click", function () {
            $(".ai-suggestion-list").html("");
            $(".ai-output").show();
            $(".loading-dots").show();
            $(this).prop('disabled', true);
            $.post(ajaxurl, {
                action: "prod_generate_ai_suggestions",
                prod_nonce: sqQuery.nonce
            }, function (response) {
                $(".loading-dots").hide();
                $(".ai-generate-btn").prop('disabled', false);
                $(".ai-suggestion-list").html('');

                if(response.success) {
                    const products = response.data.products; 
                    products.forEach(prod => {
                   // console.log(prod.title, prod.suggestions);
                });
        } else {
            console.error('Error:', response.data);
        }
            if (response.success && Array.isArray(response.data.products)) {
                response.data.products.forEach(function(product) {
                    console.log(product.title, product.suggestions);
                    $(".ai-suggestion-list").append(`<li><strong>${product.title}:</strong></li>`);
                    product.suggestions.forEach(function(suggestion) {
                        $(".ai-suggestion-list").append("<li>" + suggestion + "</li>");
                    });
                });
            } else {
                $(".ai-suggestion-list").html("<li>Failed to generate suggestions.</li>");
                console.error("AI response error:", response);
                }
                }).fail(function (xhr, status, error) {
                    $(".loading-dots").hide();
                    $(".ai-generate-btn").prop('disabled', false);
                    $(".ai-suggestion-list").html("<li>Error while contacting server.</li>");
                    console.error("AJAX failed:", error);
                });
        });



}(jQuery));
</script>