/**
 * Zoho CRM Admin JavaScript
 */
jQuery(document).ready(function($) {
    // 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 = '<div class="notice notice-success">';
                    successHtml += '<p><strong>' + response.data.message + '</strong></p>';
                    
                    // Show credential details
                    if (response.data.client_id) {
                        successHtml += '<p>Client ID: ' + response.data.client_id + '</p>';
                    }
                    if (response.data.client_secret_exists) {
                        successHtml += '<p>Client Secret: ✓ Loaded</p>';
                    }
                    if (response.data.refresh_token_exists) {
                        successHtml += '<p>Refresh Token: ✓ Found</p>';
                    } else {
                        successHtml += '<p>Refresh Token: ❌ Missing (OAuth required)</p>';
                    }
                    
                    // Show debug info if available
                    if (response.data.debug) {
                        successHtml += '<details style="margin-top: 10px;">';
                        successHtml += '<summary>Debug Information</summary>';
                        successHtml += '<pre style="background: #f0f0f0; padding: 10px; font-size: 12px;">';
                        successHtml += JSON.stringify(response.data.debug, null, 2);
                        successHtml += '</pre></details>';
                    }
                    
                    successHtml += '</div>';
                    $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 = '<div class="notice notice-warning">';
                        authHtml += '<h3>🔐 OAuth Authorization Required</h3>';
                        authHtml += '<p><strong>' + response.data.details + '</strong></p>';
                        
                        if (response.data.next_steps) {
                            authHtml += '<ol>';
                            response.data.next_steps.forEach(function(step) {
                                authHtml += '<li>' + step + '</li>';
                            });
                            authHtml += '</ol>';
                        }
                        
                        authHtml += '<p><a href="' + response.data.auth_url + '" target="_blank" class="button button-primary" style="margin: 10px 0;">🚀 Authorize with Zoho CRM</a></p>';
                        
                        // Show credential status
                        if (response.data.credentials_status) {
                            authHtml += '<p><strong>Current Status:</strong></p>';
                            authHtml += '<ul>';
                            authHtml += '<li>Client ID: ' + response.data.credentials_status.client_id + '</li>';
                            authHtml += '<li>Client Secret: ' + (response.data.credentials_status.client_secret_exists ? '✓ Loaded' : '❌ Missing') + '</li>';
                            authHtml += '<li>Refresh Token: ' + (response.data.credentials_status.refresh_token_exists ? '✓ Found' : '❌ Missing') + '</li>';
                            authHtml += '</ul>';
                        }
                        
                        authHtml += '<p><em>After authorization, come back and test the connection again.</em></p>';
                        authHtml += '</div>';
                        $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 = '<div class="notice notice-error">';
                    errorHtml += '<p><strong>' + response.data.message + ':</strong> ' + response.data.error + '</p>';
                    
                    // Add error code if available
                    if (response.data.code) {
                        errorHtml += '<p><strong>Error Code:</strong> ' + response.data.code + '</p>';
                    }
                    
                    // Add details if available
                    if (response.data.details) {
                        errorHtml += '<p><strong>Details:</strong> ' + response.data.details + '</p>';
                    }
                    
                    // Add debugging info
                    errorHtml += '<div class="hvac-zoho-debug-info">';
                    errorHtml += '<p><strong>Debug Information:</strong></p>';
                    errorHtml += '<p>Check the PHP error log for more details.</p>';
                    errorHtml += '<p>Log location: wp-content/plugins/hvac-community-events/logs/zoho-debug.log</p>';
                    
                    // Add raw response data if available
                    if (response.data.raw) {
                        errorHtml += '<details>';
                        errorHtml += '<summary>Raw Response Data (click to expand)</summary>';
                        errorHtml += '<pre style="background: #f0f0f0; padding: 10px; max-height: 300px; overflow: auto;">' + 
                                     JSON.stringify(JSON.parse(response.data.raw), null, 2) + 
                                     '</pre>';
                        errorHtml += '</details>';
                    }
                    
                    // Add file/line info if available (for exceptions)
                    if (response.data.file) {
                        errorHtml += '<p><strong>File:</strong> ' + response.data.file + '</p>';
                    }
                    
                    // Add trace if available
                    if (response.data.trace) {
                        errorHtml += '<details>';
                        errorHtml += '<summary>Stack Trace (click to expand)</summary>';
                        errorHtml += '<pre style="background: #f0f0f0; padding: 10px; max-height: 300px; overflow: auto;">' + 
                                     response.data.trace + 
                                     '</pre>';
                        errorHtml += '</details>';
                    }
                    
                    errorHtml += '</div>'; // Close debug info
                    errorHtml += '</div>'; // Close notice
                    
                    $status.html(errorHtml);
                }
            },
            error: function(xhr, status, error) {
                var errorHtml = '<div class="notice notice-error">';
                errorHtml += '<p><strong>AJAX Error:</strong> Connection test failed</p>';
                errorHtml += '<p><strong>Status:</strong> ' + status + '</p>';
                errorHtml += '<p><strong>Error:</strong> ' + error + '</p>';
                errorHtml += '</div>';
                
                $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('<p>Syncing ' + type + '...</p>');
        
        $.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 = '<div class="notice notice-success">';
                    
                    if (result.staging_mode) {
                        html += '<h4>🔧 STAGING MODE - Simulation Results</h4>';
                        html += '<p>' + result.message + '</p>';
                    } else {
                        html += '<p>Sync completed successfully!</p>';
                    }
                    
                    html += '<ul>' +
                        '<li>Total records: ' + result.total + '</li>' +
                        '<li>Synced: ' + result.synced + '</li>' +
                        '<li>Failed: ' + result.failed + '</li>' +
                        '</ul>';
                    
                    if (result.test_data && result.test_data.length > 0) {
                        html += '<details>' +
                            '<summary>View test data (first 5 records)</summary>' +
                            '<pre style="background: #f0f0f0; padding: 10px; overflow: auto;">' +
                            JSON.stringify(result.test_data.slice(0, 5), null, 2) +
                            '</pre>' +
                            '</details>';
                    }
                    
                    html += '</div>';
                    $status.html(html);
                } else {
                    $status.html('<div class="notice notice-error"><p>' + response.data.message + ': ' + response.data.error + '</p></div>');
                }
            },
            error: function() {
                $status.html('<div class="notice notice-error"><p>Sync failed</p></div>');
            },
            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');
            }
        });
    });
});