(function($) { 'use strict'; $(document).ready(function() { var $searchInput = $('#mls-clone-search'); var $cloneBtn = $('#mls-clone-btn'); var $status = $('#mls-clone-status'); if (!$searchInput.length) { return; } $cloneBtn.on('click', function() { var mlsId = $searchInput.val().trim(); if (!mlsId) { $status.text('Please enter an MLS ID').css('color', '#dc3545'); return; } $status.text('Searching...').css('color', '#666'); $cloneBtn.prop('disabled', true); // First search for the listing $.ajax({ url: mlsManualProperty.ajaxUrl, type: 'POST', data: { action: 'mls_search_for_clone', nonce: mlsManualProperty.nonce, mls_id: mlsId }, success: function(response) { if (response.success) { // Found - confirm and clone var listing = response.data; var confirmMsg = 'Found listing:\n\n' + 'MLS #: ' + listing.listing_id + '\n' + 'Address: ' + listing.address + ', ' + listing.city + '\n' + 'Price: $' + Number(listing.price).toLocaleString() + '\n\n' + 'Clone this listing?'; if (confirm(confirmMsg)) { cloneListing(listing.listing_key); } else { $status.text('').css('color', ''); $cloneBtn.prop('disabled', false); } } else { $status.text(response.data || 'Listing not found').css('color', '#dc3545'); $cloneBtn.prop('disabled', false); } }, error: function() { $status.text('Error searching for listing').css('color', '#dc3545'); $cloneBtn.prop('disabled', false); } }); }); // Allow Enter key to trigger search $searchInput.on('keypress', function(e) { if (e.which === 13) { e.preventDefault(); $cloneBtn.click(); } }); function cloneListing(listingKey) { $status.text('Cloning listing and downloading images...').css('color', '#666'); // Get post ID from URL or hidden field var postId = $('#post_ID').val() || getUrlParam('post'); $.ajax({ url: mlsManualProperty.ajaxUrl, type: 'POST', data: { action: 'mls_clone_listing', nonce: mlsManualProperty.nonce, listing_key: listingKey, post_id: postId }, success: function(response) { if (response.success) { $status.html('Success! ' + response.data.images_imported + ' images imported. Redirecting to edit page...'); // Redirect to the edit page of the cloned post (not reload, which creates a new auto-draft) setTimeout(function() { window.location.href = 'post.php?post=' + postId + '&action=edit'; }, 1500); } else { $status.text(response.data || 'Clone failed').css('color', '#dc3545'); $cloneBtn.prop('disabled', false); } }, error: function() { $status.text('Error cloning listing').css('color', '#dc3545'); $cloneBtn.prop('disabled', false); } }); } function getUrlParam(name) { var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href); return results ? results[1] : null; } }); })(jQuery);