<?php 

/**
 * AJAX handler for version switching
 */
function scrollsequence_switch_version_ajax() {
    // Security checks
    check_ajax_referer('scrollsequence_switch_version', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }
    
    $new_version = isset($_POST['version']) ? sanitize_text_field(wp_unslash($_POST['version'])) : '';
    
    if (!in_array($new_version, ['v1', 'v2'])) {
        wp_send_json_error('Invalid version');
        return;
    }
    
    update_option('scrollsequence_active_version', $new_version);
    

    // Set a transient to flush on next admin page load
    set_transient('scrollsequence_flush_rewrite_rules', 1, 60);

    // --- Tracking logic using Freemius SDK ---
    if (freemius_scrollsequence()->is_registered() && freemius_scrollsequence()->is_tracking_allowed()) {
      
      $siteid = freemius_scrollsequence()->get_site()->id;
      
      // Prepare tracking data as POST body
      $tracking_data = [
          'siteid'    => $siteid, 
          'event'      => 'switch_version',
          'newversion' => $new_version,
      ];

      // Send POST request with JSON body
      wp_remote_post(SCROLLSEQUENCE_API_URL.'/events', [
          'timeout'   => 30,
          'blocking'  => false,
          'headers'   => [
              'Content-Type'  => 'application/json',
          ],
          'body'      => wp_json_encode($tracking_data),
      ]);
      
    }    
    // success response
    wp_send_json_success(['version' => $new_version]);
}
add_action('wp_ajax_scrollsequence_switch_version', 'scrollsequence_switch_version_ajax');


function scrollsequence_switch_version_render($current_version) {
    // Only show to admins
    if (!current_user_can('manage_options')) {
        return '';
    }
    
    $nonce = wp_create_nonce('scrollsequence_switch_version');
    
    ob_start();
    ?> 
<style>
.ssqv-dropdown {
  display: inline-block;
  position: relative;
}

.ssqv-dropdown-content {
  display: none;
  position: absolute;
  top: 18px;
  left: 0;
  z-index: 99999;
  background-color: #f9f9f9;
  min-width: 130px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
}

.ssqv-dropdown:hover .ssqv-dropdown-content {
  display: block;
}

.ssqv-item {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  margin-bottom: 8px;
  cursor: pointer;
}

.ssqv-item:hover {
  opacity: 0.7;
}

.ssqv-item.ssqv-active {
  cursor: default;
}

.ssqv-item.ssqv-active:hover {
  opacity: 1;
}

/* Hide tick for non-active items */
.ssqv-item span:last-child {
  display: none;
}
.ssqv-active span:last-child {
  display: inline;
}

/* Modal styles - WordPress-like */
.ssqv-modal-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  z-index: 100000;
  align-items: center;
  justify-content: center;
}

.ssqv-modal-overlay.ssqv-show {
  display: flex;
}

.ssqv-modal {
  background: #fff;
  max-width: 500px;
  width: 90%;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  border-radius: 3px;
}

.ssqv-modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ssqv-modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.ssqv-modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  line-height: 1;
  color: #666;
}

.ssqv-modal-close:hover {
  color: #000;
}

.ssqv-modal-body {
  padding: 24px;
}

.ssqv-modal-notice {
  background: #fff3cd;
  border-left: 4px solid #ffc107;
  padding: 12px;
  margin-bottom: 16px;
}

.ssqv-modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.ssqv-button {
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 3px;
  cursor: pointer;
  font-size: 14px;
  background: #f7f7f7;
}

.ssqv-button:hover {
  background: #fafafa;
  border-color: #999;
}

.ssqv-button-primary {
  background: #2271b1;
  border-color: #2271b1;
  color: #fff;
}

.ssqv-button-primary:hover {
  background: #135e96;
  border-color: #135e96;
}

.ssqv-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>

<div class="ssqv-dropdown">
    <span>Version <?php echo $current_version === 'v1' ? '1' : '2'; ?></span>
    <div class="ssqv-dropdown-content">
        <div 
            class="ssqv-item <?php echo $current_version === 'v1' ? 'ssqv-active' : ''; ?>" 
            onclick="ssqvSwitchVersion('v1')"
        >
            <span>Version 1</span> <span><?php echo icon_tick(); ?></span>
        </div>
        <div 
            class="ssqv-item <?php echo $current_version === 'v2' ? 'ssqv-active' : ''; ?>" 
            onclick="ssqvSwitchVersion('v2')"
        >
            <span>Version 2</span>
            <span><?php echo icon_tick(); ?></span>
        </div>
    </div>
</div>

<!-- Warning Modal for V2 -->
<div id="ssqv-modal" class="ssqv-modal-overlay">
    <div class="ssqv-modal">
        <div class="ssqv-modal-header">
            <h2 class="ssqv-modal-title">Switch to Version 2 (Beta)</h2>
            <button class="ssqv-modal-close" onclick="ssqvCloseModal()">&times;</button>
        </div>
        <div class="ssqv-modal-body">
            <div class="ssqv-modal-notice">
                <strong>⚠️ Warning:</strong> Version 2 is currently in beta and may be unstable.
            </div>
            <p><strong>Important:</strong></p>
            <ul>
                <li>Version 2 is still under development and may contain bugs</li>
                <li>All scrollsequences created in Version 1 will be temporarily disabled</li>
                <li>You can switch back to Version 1 at any time to restore your content</li>
                <li>Your <strong>Version 1 data will remain safe and unchanged</strong></li>
            </ul>
            <p>Do you want to continue?</p>
        </div>
        <div class="ssqv-modal-footer">
            <button class="ssqv-button" onclick="ssqvCloseModal()">Cancel</button>
            <button class="ssqv-button ssqv-button-primary" id="ssqv-confirm-btn" onclick="ssqvConfirmSwitch()">
                Switch to Version 2
            </button>
        </div>
    </div>
</div>

<script>
(function() {
    var pendingVersion = null;
    var isProcessing = false;
    
    window.ssqvSwitchVersion = function(version) {
        if (isProcessing) return;
        
        var currentVersion = '<?php echo esc_js($current_version); ?>';
        
        // Don't switch if already on this version
        if (version === currentVersion) {
            return;
        }
        
        // Direct switch to v1
        if (version === 'v1') {
            ssqvPerformSwitch('v1');
        } 
        // Show warning modal for v2
        else if (version === 'v2') {
            pendingVersion = 'v2';
            ssqvOpenModal();
        }
    };
    
    window.ssqvOpenModal = function() {
        document.getElementById('ssqv-modal').classList.add('ssqv-show');
    };
    
    window.ssqvCloseModal = function() {
        if (!isProcessing) {
            document.getElementById('ssqv-modal').classList.remove('ssqv-show');
            pendingVersion = null;
        }
    };
    
    window.ssqvConfirmSwitch = function() {
        if (pendingVersion === 'v2') {
            ssqvPerformSwitch('v2');
        }
    };
    
    function ssqvPerformSwitch(version) {
        if (isProcessing) return;
        
        isProcessing = true;
        var confirmBtn = document.getElementById('ssqv-confirm-btn');
        if (confirmBtn) {
            confirmBtn.disabled = true;
            confirmBtn.textContent = 'Switching...';
        }
        
        var data = new FormData();
        data.append('action', 'scrollsequence_switch_version');
        data.append('nonce', '<?php echo esc_js($nonce); ?>');
        data.append('version', version);
        
        fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
            method: 'POST',
            body: data
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(result) {
            if (result.success) {
                // Reload the page to reflect the version change
                window.location.reload();
            } else {
                alert('Error switching version: ' + (result.data || 'Unknown error'));
                isProcessing = false;
                if (confirmBtn) {
                    confirmBtn.disabled = false;
                    confirmBtn.textContent = 'Switch to Version 2';
                }
            }
        })
        .catch(function(error) {
            alert('Error switching version: ' + error.message);
            isProcessing = false;
            if (confirmBtn) {
                confirmBtn.disabled = false;
                confirmBtn.textContent = 'Switch to Version 2';
            }
        });
    }
    
    // Close modal on overlay click
    document.addEventListener('click', function(e) {
        if (e.target.id === 'ssqv-modal' && !isProcessing) {
            ssqvCloseModal();
        }
    });
})();
</script>
    <?php
    return ob_get_clean();    
}


function icon_tick(){
    return '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="green" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M20 6 9 17l-5-5"/></svg>';
}