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

<?php  if(PROD_Classes_Helpers_Tools::getOption('pp_saved_feeds')!=null){
            $feed_data = PROD_Classes_Helpers_Tools::getOption('pp_saved_feeds');
            // print_r($feed_data);
        }
?>

<div class="pp-container">
    <div id="api-key-modal" class="pp-modal">
        <div class="pp-modal-content">
            <h4>🔐 API Settings</h4>
            <p>Enter your API key from Customer app. This key is stored securely.</p>
            
            <label for="api_key_input">API Key</label>
            <input type="text" id="api_key_input" placeholder="sk-..."/>
            <div id="api-key-message"></div>
            <div class="pp-modal-actions">
                <button id="save_api_key" style="width:8vw;" class="pp-btn pp-btn-primary">Save</button>
                <button id="close_api_modal" class="pp-btn">Cancel</button>
            </div>
        </div>
    </div>

    <!-- Main Panel -->
    <!-- <div class="pp-main">
        <div class="pp-header">
        <div class="pp-header-up">
            <div class="pp-title">Manage Feeds</div>
            <div class="pp-api-settings">
                <div>API Key Settings</div>
                <button id="open-api-settings" class="pp-btn pp-btn-primary" style="width:8vw">Settings</button>
            </div>
            <div class="backup-original">
                <div>Restore original data</div>
                <button id="restoreOriginalsBtn" class="button restore-button">
                ♻️ Restore
                </button>
            </div>
        </div>
    </div> -->

        <div class="pp-main">
        <div class="pp-header">
            <div class="pp-header-up">
            <div class="pp-title">Manage Feeds</div>

            <!-- Settings Dropdown -->
            <div class="settings-dropdown">
                <button class="settings-btn">
                ⚙️ Settings ▾
                </button>
                <div class="settings-menu">
                    <button id="open-api-settings">
                        🔐 API Key Settings
                    </button>
                    <button id="restoreOriginalsBtn">
                        ♻️ Restore Original Data
                    </button>
                </div>
            </div>
            </div>
        </div>


        <div class="pp-headers">
            <div style="text-align:center;">Active</div>
            <div style="text-align:center;">Project Name & Channel</div>
            <div style="text-align:center;">Format</div>
            <div style="text-align:center;">Refresh Interval</div>
            <div style="text-align:center;">Settings/URL</div>
        </div>

        <?php
            $upload_dir = wp_upload_dir();
            $base = $upload_dir['basedir']; 
            $feed_dir = $base . '/product-perfect-feed-pro/';
            
            if (file_exists($feed_dir)) {
            $files = scandir($feed_dir);
            foreach($files as $file){
                $path = $base . '/product-perfect-feed-pro/'.$file.'.xml';
               
                if($file != "log.xml" && $file != ".xml" && strpos($file, ".xml")) {
                    $open_path = $upload_dir['baseurl'] . '/product-perfect-feed-pro/'.$file;
                    $class = str_replace(".xml", "", $file);
                    $enabled = PROD_Classes_Helpers_Tools::getOption('prod_toggle_' . $file,0);
                    echo '
                    <div class="pp-feed-row" data-file="'.$file.'">
                        <div style="text-align:center;">
                            <label class="toggle-container">
                                <input type="checkbox" class="toggle-input" id="toggle-'.$class.'" data-file="'.$file.'" '. ($enabled ? 'checked' : '') . ' />
                                <span class="toggle-slider"></span>
                            </label>
                        </div>

                        <div style="font-weight:500;font-size:0.8vw; text-align:center;width:21vw;display:flex;flex-wrap:wrap;">'.$file.' / '.$feed_data[$class]['channel'].'</div>
                        <div style="text-align:center;">xml</div>
                        <div style="text-align:center;">daily</div>
                        <div class="pp-settings">
                            <div style="font-size:1vw; font-weight:500; color:#007bff;z-index:1;">
                                <a href="'.$open_path.'" target="blank" style="text-decoration:none; color:#0073aa;">Open Feed</a>
                            </div>
                            <div class="dashicons dashicons-admin-generic open-settings-panel"></div>
                          
                            <!--Settings Panel -->
                            <div class="feed-settings-panel '.$file.'" style="z-index:99;">
                                <div class="feed-actions edit-feed-data" data-file='.$file.'>
                                    <div class="dashicons dashicons-admin-generic" style="font-size:1vw;display:flex;align-items:center;"></div>
                                    <span>Edit Feed</span>
                                </div>
                
                                <div class="feed-actions download-feed" data-file='.$file.' style="color:#007bff;">
                                    <div class="dashicons dashicons-download" style="font-size:1vw;display:flex;align-items:center;"></div>
                                    <span>Download Feed</span>
                                </div>

                                <div class="feed-actions delete-feed-data" data-file='.$file.' style="color:red;">
                                    <div class="dashicons dashicons-trash" style="font-size:1vw;display:flex;align-items:center;"></div>
                                    <span>Delete Feed</span>
                                </div>
                            </div>
                        </div>
                </div>';
                }
            }
        }
        ?>
    </div>
</div>

<style>
    body {
        background-color: #f4f4f4;
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
    }
    .restore-button {
        background-color: #007cba !important; 
        color: #fff !important;
        border: none !important;
        padding: 0.4vw 1.5vw !important;
        border-radius: 0.5vw !important;
        font-weight: 500;
        font-size: 1vw;
        width:8vw;
        cursor: pointer;
        transition: all 0.25s ease;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .restore-button:hover {
        background-color: #006ba1;        
        transform: translateY(-1px);
        box-shadow: 0 3px 6px rgba(0, 0, 0, 0.15);
    }
    .pp-container {
        background-color: #f4f4f4;
        font-family: 'Segoe UI', sans-serif;
        padding-bottom: 5vw;
    }
    .pp-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: rgba(0, 0, 0, 0.5);
        z-index: 9999;
        justify-content: center;
        align-items: center;
    }
    .pp-modal-content {
        background: white;
        padding: 1vw;
        border-radius: 1vw;
        width: 40vw;
        box-shadow: 0 8px 40px rgba(0, 0, 0, 0.3);
        font-size:1vw;
        border-left: 5px solid #0073aa;
    }
    .pp-modal-content h4{
         font-size: 1.2vw;
         font-weight:600;
    }
    .pp-modal-content p{
         font-size: 0.8vw;
         font-weight:500;
    }
    .pp-modal-content input {
        width: 100%;
        padding: 0.2vw;
        border: 1px solid #ccc;
        border-radius: 0.5vw;
        font-size: 0.9vw;
    }
    .pp-modal-actions {
        text-align: right;
        margin-top: 1vw;
    }
    .pp-btn {
        border: none;
        border-radius: 0.5vw;
        cursor: pointer;
        font-weight: 600;
        padding:0.5vw;
        width:7vw;
    }
    .pp-btn-primary {
        background-color: #0073aa;
        color: white;
        width:10vw;
        margin-top:0.2vw;
    }
    .pp-btn:hover{
        opacity:0.9;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .pp-main{
        width: 75vw;
        background: white;
        margin: 4vw auto;
        border-radius: 1vw;
        padding: 2vw;
        box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
    }
    .pp-header {
        display: flex;
        flex-direction:column;
        padding-bottom:2vw;
        align-items: center;
        border-left: 0.3vw solid #0073aa;
        border-radius:1vw;
        background: #f0f8ff;
        position: relative;
    }
    .pp-header-up{
        display:flex;
        flex-direction:column;
        width:100%;
        padding:1vw;    }
    .pp-header img {
        width: 7vw;
        height:6vw;
        height: auto;
    }
    .pp-header-text {
        flex: 1;
    }
    .pp-title {
        font-size: 1.4vw;
        font-weight: 600;
    }
    .pp-subtitle {
        font-size: 0.8vw;
        font-weight:500;
    }
    .pp-api-settings{
        margin-top:1vw;
    }
    .backup-original{
        margin-top:1vw;
    }
    .pp-headers{
        display: grid; 
        grid-template-columns: 10% 25% 20% 20% 20%; 
        font-weight:600; 
        font-size:1vw; 
        color: #444; 
        border-bottom: 2px solid #f0f0f0; 
        padding-bottom: 1vw;
        margin-top:2vw;
    }
    .pp-feed-row{
        display: grid; 
        grid-template-columns: 10% 25% 20% 20% 20%; 
        align-items:center;
        padding:1vw;
        border:1px solid #f0f0f0; 
        border-radius: 1vw; 
        margin-top: 1vw;
        font-size:1vw;
        background-color:#ffffff;
    }
    .pp-feed-row:hover {
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    }
    .pp-settings{
        position:relative;
        display:flex;
        align-items:center;
        justify-content:center;
        margin-left:3.5vw;
    }
    .open-settings-panel{
        cursor:pointer; 
        font-size:1.1vw; 
        color:grey;
        display:flex;
        align-items:center;
        margin-left:0.5vw;
        z-index:1;
    }
    .toggle {
        background-color: #ccc;
        border-radius: 50%;
        display: inline-block;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    .toggle:checked {
        background-color: #00b4fe;
    }
    .toggle-container {
        position: relative;
        display: inline-block;
        width: 3.5vw;
        height: 1.5vw;
    }
    .toggle-input {
        opacity: 0;
        width: 0;
        height: 0;
    }
    .toggle-slider {
        position: absolute;
        cursor: pointer;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #ccc;
        transition: .4s;
        border-radius: 50px;
    }
    .toggle-slider:before {
        content: "";
        position: absolute;
        height: 1vw;
        width: 1vw;
        border-radius: 50%;
        left: 0.3vw;
        bottom: 0.25vw;
        background-color: white;
        transition: .4s;
    }
    .toggle-input:checked + .toggle-slider {
        background-color:  #00b4fe;
    }
    .toggle-input:checked + .toggle-slider:before {
        transform: translateX(1.95vw);
    }   
    .feed-settings-panel {
        position:absolute;
        left:-4px;
        top:3vw;
        width:12vw;
        padding:0.5vw;
        text-align:center;
        background-color:#f5f8fa;
        box-shadow: inset 0 0 8px #e1e8ed;
        border-radius:1vw;
        display:none;
    }
    .feed-settings-panel.visible {
        display:flex;
        flex-direction:column;
    }
    .feed-actions{
        z-index:99;
        font-size:1vw;
        cursor:pointer; 
        display:flex; 
        align-items:center;
        gap:0.5vw;
        padding:0.2vw;
        border-radius:0.5vw;
    }
    .feed-actions:hover {
        background-color: #f0f0f0;
    }
    .open-settings-panel:hover {
        color: #0056b3;
    }

    v=.pp-header-up {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f4faff;
  border-radius: 12px;
  padding: 20px 25px;
  margin-bottom: 20px;
}

.pp-title {
  font-size: 22px;
  font-weight: 600;
  color: #1a2734;
}

.settings-dropdown {
  position: relative;
}

.settings-btn {
  background: #007bff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 18px;
  cursor: pointer;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
}

.settings-btn:hover {
  background: #0065d1;
}

.settings-menu {
  display: none;
  position: absolute;
  top: 3vw;
  left: 0;
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 14px rgba(0,0,0,0.1);
  overflow: hidden;
  min-width: 220px;
  z-index: 100;
}

.settings-menu button {
  width: 100%;
  border: none;
  background: white;
  padding: 12px 16px;
  text-align: left;
  font-size: 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #333;
}

.settings-menu button:hover {
  background: #f0f6ff;
}

</style>

<script>
    // (function ($){ 
    //     $('.delete-feed-data').on('click', function() {
    //         var file = $(this).data('file');
    //         var $row = $('.feed-row[data-file="' + file + '"]');
    //         $row.css('border', '1px solid red');
    //         setTimeout(function() {
    //             $row.fadeOut(500, function() {
    //                 $(this).remove();
    //             });
    //         }, 500);

    //          $.post(sqQuery.ajaxurl, {
    //             prod_nonce: sqQuery.nonce,
    //             action: "delete_feed",
    //             feed_id: file,
    //              }).done(function(response) {
    //           if(response) {
    //             //alert(response.data);
    //           } else {
    //           }
    //     });

    //     });

    //      $(".edit-feed-data").on('click',function(){
    //         var file = $(this).data('file');
    //           $.post(sqQuery.ajaxurl, {
    //             prod_nonce: sqQuery.nonce,
    //             action: "edit_feed",
    //             feed_id: file,
    //              }).done(function() {
    //                  window.location.href = ajaxurl.replace('admin-ajax.php', 'admin.php?page=new_feed&tab=field_mapping');
    //              })
    //     });

    //     const feedBaseUrl = '<?php echo esc_url( wp_upload_dir()['baseurl'] . "/product-perfect-feed-pro/" ); ?>';
    //     $(".download-feed").on('click', function() {
    //         let filename = $(this).data('file');
    //         if (!filename.endsWith('.xml')) {
    //             filename += '.xml';
    //         }
    //         const fileUrl = feedBaseUrl + filename;
    //         const a = document.createElement('a');
    //         a.href = fileUrl;
    //         a.download = filename;
    //         document.body.appendChild(a);
    //         a.click();
    //         document.body.removeChild(a);
    //     });

    //     $('.toggle-input').on('change', function(e) {
    //         const input = e.target;             
    //         const file = input.dataset.file; 
    //         const enabled = input.checked ? 1 : 0;
    //         input.disabled = true;
    //         $.post(sqQuery.ajaxurl, {
    //             prod_nonce: sqQuery.nonce,
    //             action: 'prod_save_toggle',
    //             file: file,
    //             enabled: enabled,
    //         }, function(response) {
    //             //console.log('Toggle saved:', response);
    //             input.disabled = false;
    //         });
    //     });

    //     $("#open-api-settings").on('click', function() {
    //         $("#api-key-modal").css('display', 'flex');
    //     });
    //     $("#close_api_modal").on('click' ,function() {
    //          $("#api-key-modal").css('display', 'none');
    //     });

    //     $("#save_api_key").on('click',function(){
    //         const key = $('#api_key_input').val().trim();
    //         const messageBox = $('#api-key-message');
    //         messageBox.text('').removeClass('error success');

    //         if (key.length < 5) {
    //             messageBox
    //             .text("Please enter a valid API key.")
    //             .addClass('error');
    //         return;
    //         }

    //          $.post(ajaxurl, {
    //             action: "prod_save_api_key",
    //             prod_nonce: sqQuery.nonce,
    //             apiKey:key,
    //         }, function(response) {
    //              messageBox
    //             .text("✅ API Key saved successfully!")
    //             .addClass('success');
    //             setTimeout(() => {
    //             $("#api-key-modal").fadeOut();
    //             messageBox.text('').removeClass('success');
    //         }, 1500);

    //         })
    //     })

    //     $(".open-settings-panel").on("click",function(){    
    //         alert("test");
    //     })


    (function ($){ 

        const $settingsBtn = $('.settings-btn');
        const $settingsMenu = $('.settings-menu');

        // Toggle dropdown on button click
        $settingsBtn.on('click', function (e) {
            e.stopPropagation();
            $settingsMenu.toggle();
        });

        // Close dropdown when clicking outside
        $(window).on('click', function () {
            $settingsMenu.hide();
        });

        $("#restoreOriginalsBtn").on("click", function() {
        if (!confirm("Are you sure you want to restore all original titles and descriptions? This cannot be undone.")) {
            return;
        }

        const $btn = $(this);
        $btn.prop("disabled", true).text("Restoring...");

        $.post(sqQuery.ajaxurl, {
            prod_nonce: sqQuery.nonce,
            action: 'prod_restore_originals'
        }).done(function(res) {
            if (res.success) {
            alert("✅ All products restored to their original titles and descriptions!");
            } else {
            alert("⚠️ Something went wrong: " + (res.data || "Unknown error"));
            }
        }).always(function() {
            $btn.prop("disabled", false).text("♻️ Backup");
        });
        });


        $('.open-settings-panel').on('click', function(e) {
            e.stopPropagation();
            var $panel = $(this).next();
            $('.feed-settings-panel').not($panel).hide();
            $panel.toggle();
        });

        $('.feed-settings-panel').on('click', function(e) {
            e.stopPropagation();
        });

        $(document).on('click', function() {
            $('.feed-settings-panel').hide();
        });

        $('.delete-feed-data').on('click', function() {
            console.log("delete");
            var file = $(this).data('file');
            var $row = $('.pp-feed-row[data-file="' + file + '"]');
            $row.css('border', '1px solid red');
            setTimeout(function() {
                $row.fadeOut(500, function() {
                    $(this).remove();
                });
            }, 500);

             $.post(sqQuery.ajaxurl, {
                prod_nonce: sqQuery.nonce,
                action: "delete_feed",
                feed_id: file,
                 }).done(function(response) {
              if(response) {
                //alert(response.data);
              } else {
              }
        });

        });

        $(".edit-feed-data").on('click',function(){
            var file = $(this).data('file');
              $.post(sqQuery.ajaxurl, {
                prod_nonce: sqQuery.nonce,
                action: "edit_feed",
                feed_id: file,
                 }).done(function() {
                     window.location.href = ajaxurl.replace('admin-ajax.php', 'admin.php?page=new_feed&tab=field_mapping');
                 })
        });

        const feedBaseUrl = '<?php echo esc_url( wp_upload_dir()['baseurl'] . "/product-perfect-feed-pro/" ); ?>';
        $(".download-feed").on('click', function() {
            let filename = $(this).data('file');
            if (!filename.endsWith('.xml')) {
                filename += '.xml';
            }

            const fileUrl = feedBaseUrl + filename;
            const a = document.createElement('a');
            a.href = fileUrl;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        });


        $("#open-api-settings").on('click', function() {
            $("#api-key-modal").css('display', 'flex');
        });
        $("#close_api_modal").on('click' ,function() {
             $("#api-key-modal").css('display', 'none');
        });

        $("#save_api_key").on('click',function(){
            const key = $('#api_key_input').val().trim();
            const messageBox = $('#api-key-message');
            messageBox.text('').removeClass('error success');

            if (key.length < 5) {
                messageBox
                .text("Please enter a valid API key.")
                .addClass('error');
            return;
            }

             $.post(ajaxurl, {
                action: "prod_save_api_key",
                prod_nonce: sqQuery.nonce,
                apiKey:key,
            }, function(response) {
                 messageBox
                .text("✅ API Key saved successfully!")
                .addClass('success');
                setTimeout(() => {
                $("#api-key-modal").fadeOut();
                messageBox.text('').removeClass('success');
            }, 1500);

            })
        })

    }(jQuery));

</script>