/** * Zoho CRM Admin JavaScript * * @package HVACCommunityEvents */ jQuery(document).ready(function($) { // ===================================================== // Password visibility toggle // ===================================================== $('#toggle-secret').on('click', function() { var passwordField = $('#zoho_client_secret'); var toggleBtn = $(this); if (passwordField.attr('type') === 'password') { passwordField.attr('type', 'text'); toggleBtn.text('Hide'); } else { passwordField.attr('type', 'password'); toggleBtn.text('Show'); } }); // ===================================================== // Copy redirect URI to clipboard // ===================================================== $('#copy-redirect-uri').on('click', function() { var redirectUri = hvacZoho.redirectUri || ''; if (!redirectUri) { alert('Redirect URI not available'); return; } navigator.clipboard.writeText(redirectUri).then(function() { $('#copy-redirect-uri').text('Copied!').prop('disabled', true); setTimeout(function() { $('#copy-redirect-uri').text('Copy').prop('disabled', false); }, 2000); }).catch(function() { // Fallback for older browsers var tempInput = $(''); $('body').append(tempInput); tempInput.val(redirectUri).select(); document.execCommand('copy'); tempInput.remove(); $('#copy-redirect-uri').text('Copied!').prop('disabled', true); setTimeout(function() { $('#copy-redirect-uri').text('Copy').prop('disabled', false); }, 2000); }); }); // ===================================================== // Flush rewrite rules // ===================================================== $('#flush-rewrite-rules').on('click', function() { var button = $(this); button.prop('disabled', true).text('Flushing...'); $.post(hvacZoho.ajaxUrl, { action: 'hvac_zoho_flush_rewrite_rules' }, function(response) { if (response.success) { button.text('Flushed!').css('color', '#46b450'); setTimeout(function() { location.reload(); }, 1000); } else { button.text('Error').css('color', '#dc3232'); setTimeout(function() { button.prop('disabled', false).text('Flush Rules').css('color', ''); }, 2000); } }); }); // ===================================================== // Credentials form submission // ===================================================== $('#zoho-credentials-form').on('submit', function(e) { e.preventDefault(); var formData = { action: 'hvac_zoho_save_credentials', zoho_client_id: $('#zoho_client_id').val(), zoho_client_secret: $('#zoho_client_secret').val(), nonce: $('input[name="hvac_zoho_nonce"]').val() }; $('#save-credentials').prop('disabled', true).text('Saving...'); $.post(hvacZoho.ajaxUrl, formData, function(response) { if (response.success) { window.location.href = window.location.href.split('?')[0] + '?page=hvac-zoho-sync&credentials_saved=1'; } else { alert('Error saving credentials: ' + response.data.message); $('#save-credentials').prop('disabled', false).text('Save Credentials'); } }); }); // ===================================================== // OAuth authorization handler // ===================================================== $('#start-oauth').on('click', function() { var clientId = $('#zoho_client_id').val(); var clientSecret = $('#zoho_client_secret').val(); if (!clientId || !clientSecret) { alert('Please save your credentials first before starting OAuth authorization.'); return; } // Use server-generated OAuth URL with CSRF state parameter var oauthUrl = hvacZoho.oauthUrl || ''; if (!oauthUrl) { alert('OAuth URL not available. Please save your credentials first and refresh the page.'); return; } // Open OAuth URL in the same window to handle callback properly window.location.href = oauthUrl; }); // ===================================================== // Test connection // ===================================================== $('#test-connection').on('click', function() { var $button = $(this); var $status = $('#connection-status'); $button.prop('disabled', true).text('Testing...'); $status.html(''); $.ajax({ url: hvacZoho.ajaxUrl, method: 'POST', data: { action: 'hvac_zoho_test_connection', nonce: hvacZoho.nonce }, success: function(response) { if (response.success) { var successHtml = '
'; successHtml += '

' + response.data.message + '

'; // Show credential details if (response.data.client_id) { successHtml += '

Client ID: ' + response.data.client_id + '

'; } if (response.data.client_secret_exists) { successHtml += '

Client Secret: ✓ Loaded

'; } if (response.data.refresh_token_exists) { successHtml += '

Refresh Token: ✓ Found

'; } else { successHtml += '

Refresh Token: ❌ Missing (OAuth required)

'; } // Show debug info if available if (response.data.debug) { successHtml += '
'; successHtml += 'Debug Information'; successHtml += '
';
                        successHtml += JSON.stringify(response.data.debug, null, 2);
                        successHtml += '
'; } successHtml += '
'; $status.html(successHtml); } else { // Debug: Log the response to see what we're getting console.log('Error response:', response); console.log('Message:', response.data.message); console.log('Has auth_url:', !!response.data.auth_url); // Handle OAuth authorization case specially if (response.data.message === 'OAuth Authorization Required' && response.data.auth_url) { var authHtml = '
'; authHtml += '

🔐 OAuth Authorization Required

'; authHtml += '

' + response.data.details + '

'; if (response.data.next_steps) { authHtml += '
    '; response.data.next_steps.forEach(function(step) { authHtml += '
  1. ' + step + '
  2. '; }); authHtml += '
'; } authHtml += '

🚀 Authorize with Zoho CRM

'; // Show credential status if (response.data.credentials_status) { authHtml += '

Current Status:

'; authHtml += ''; } authHtml += '

After authorization, come back and test the connection again.

'; authHtml += '
'; $status.html(authHtml); return; } else { console.log('OAuth conditions not met:'); console.log('Message matches:', response.data.message === 'OAuth Authorization Required'); console.log('Auth URL exists:', !!response.data.auth_url); } // Create detailed error display for other errors var errorHtml = '
'; errorHtml += '

' + response.data.message + ': ' + response.data.error + '

'; // Add error code if available if (response.data.code) { errorHtml += '

Error Code: ' + response.data.code + '

'; } // Add details if available if (response.data.details) { errorHtml += '

Details: ' + response.data.details + '

'; } // Add debugging info errorHtml += '
'; errorHtml += '

Debug Information:

'; errorHtml += '

Check the PHP error log for more details.

'; errorHtml += '

Log location: wp-content/plugins/hvac-community-events/logs/zoho-debug.log

'; // Add raw response data if available if (response.data.raw) { errorHtml += '
'; errorHtml += 'Raw Response Data (click to expand)'; errorHtml += '
' + 
                                     JSON.stringify(JSON.parse(response.data.raw), null, 2) + 
                                     '
'; errorHtml += '
'; } // Add file/line info if available (for exceptions) if (response.data.file) { errorHtml += '

File: ' + response.data.file + '

'; } // Add trace if available if (response.data.trace) { errorHtml += '
'; errorHtml += 'Stack Trace (click to expand)'; errorHtml += '
' + 
                                     response.data.trace + 
                                     '
'; errorHtml += '
'; } errorHtml += '
'; // Close debug info errorHtml += '
'; // Close notice $status.html(errorHtml); } }, error: function(xhr, status, error) { var errorHtml = '
'; errorHtml += '

AJAX Error: Connection test failed

'; errorHtml += '

Status: ' + status + '

'; errorHtml += '

Error: ' + error + '

'; errorHtml += '
'; $status.html(errorHtml); }, complete: function() { $button.prop('disabled', false).text('Test Connection'); } }); }); // Sync data $('.sync-button').on('click', function() { var $button = $(this); var type = $button.data('type'); var $status = $('#' + type + '-status'); $button.prop('disabled', true).text('Syncing...'); $status.html('

Syncing ' + type + '...

'); $.ajax({ url: hvacZoho.ajaxUrl, method: 'POST', data: { action: 'hvac_zoho_sync_data', type: type, nonce: hvacZoho.nonce }, success: function(response) { if (response.success) { var result = response.data; var html = '
'; if (result.staging_mode) { html += '

🔧 STAGING MODE - Simulation Results

'; html += '

' + result.message + '

'; } else { html += '

Sync completed successfully!

'; } html += ''; if (result.test_data && result.test_data.length > 0) { html += '
' + 'View test data (first 5 records)' + '
' +
                            JSON.stringify(result.test_data.slice(0, 5), null, 2) +
                            '
' + '
'; } html += '
'; $status.html(html); } else { $status.html('

' + response.data.message + ': ' + response.data.error + '

'); } }, error: function() { $status.html('

Sync failed

'); }, complete: function() { $button.prop('disabled', false).text('Sync ' + type.charAt(0).toUpperCase() + type.slice(1)); } }); }); // Save settings $('#zoho-settings-form').on('submit', function(e) { e.preventDefault(); var $form = $(this); var $button = $form.find('button[type="submit"]'); $button.prop('disabled', true).text('Saving...'); $.ajax({ url: hvacZoho.ajaxUrl, method: 'POST', data: { action: 'hvac_zoho_save_settings', nonce: hvacZoho.nonce, auto_sync: $form.find('input[name="auto_sync"]').is(':checked') ? '1' : '0', sync_frequency: $form.find('select[name="sync_frequency"]').val() }, success: function(response) { if (response.success) { // Use toast notification instead of alert if (window.HVACToast) { HVACToast.success('Settings saved successfully!'); } else { alert('Settings saved successfully!'); } } else { // Use toast notification instead of alert if (window.HVACToast) { HVACToast.error('Error saving settings: ' + response.data.message); } else { alert('Error saving settings: ' + response.data.message); } } }, error: function() { // Use toast notification instead of alert if (window.HVACToast) { HVACToast.error('Error saving settings'); } else { alert('Error saving settings'); } }, complete: function() { $button.prop('disabled', false).text('Save Settings'); } }); }); });