<?php
error_log("=== WEBHOOK SETTINGS PAGE LOADED ===");
error_log("Request method: " . $_SERVER['REQUEST_METHOD']);
error_log("Current time: " . date('Y-m-d H:i:s'));

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once '../webhook_service.php';

// Require admin login with settings permission
requirePermission('settings', 'view');

$currentPage = 'settings';
$subPage = 'webhooks';

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("=== WEBHOOK FORM SUBMISSION DETECTED ===");
    error_log("POST data: " . print_r($_POST, true));
    error_log("Session data: " . print_r($_SESSION, true));
    try {
        // Validate CSRF token
        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['webhook_csrf_token']) {
            error_log("CSRF token validation failed");
            throw new Exception('Invalid form submission. Please try again.');
        }
        
        error_log("CSRF token validation passed");
        $pdo = getDBConnection();
        
        if (isset($_POST['update_webhook_config'])) {
            error_log("Processing webhook config update");
            // Update webhook configuration settings only
            $webhookEnabled = $_POST['webhook_enabled'] ?? 'false';
            $webhookUrl = trim($_POST['webhook_url'] ?? '');
            $webhookRetryCount = intval($_POST['webhook_retry_count'] ?? 3);
            $webhookTimeout = intval($_POST['webhook_timeout'] ?? 30);
            
            // Validate inputs
            if ($webhookEnabled === 'true' && empty($webhookUrl)) {
                throw new Exception('Webhook URL is required when webhooks are enabled');
            }
            
            if ($webhookRetryCount < 0 || $webhookRetryCount > 10) {
                throw new Exception('Retry count must be between 0 and 10');
            }
            
            if ($webhookTimeout < 5 || $webhookTimeout > 120) {
                throw new Exception('Timeout must be between 5 and 120 seconds');
            }
            
            // Update only webhook configuration settings
            $configSettings = [
                'webhook_enabled' => $webhookEnabled,
                'webhook_url' => $webhookUrl,
                'webhook_retry_count' => $webhookRetryCount,
                'webhook_timeout' => $webhookTimeout
            ];
            
            foreach ($configSettings as $key => $value) {
                // First try to update existing setting
                $stmt = $pdo->prepare("
                    UPDATE admin_settings 
                    SET setting_value = ?, updated_at = NOW(), updated_by = ? 
                    WHERE setting_key = ?
                ");
                
                $result = $stmt->execute([$value, $_SESSION['admin_user']['username'] ?? 'admin', $key]);
                $rowsAffected = $stmt->rowCount();
                
                // If no rows were affected, the setting doesn't exist, so insert it
                if ($rowsAffected === 0) {
                    $description = match($key) {
                        'webhook_enabled' => 'Enable/disable webhook notifications',
                        'webhook_url' => 'Webhook endpoint URL for registration updates',
                        'webhook_retry_count' => 'Number of retry attempts for failed webhook calls',
                        'webhook_timeout' => 'Timeout in seconds for webhook requests',
                        default => 'Webhook setting'
                    };
                    
                    $insertStmt = $pdo->prepare("
                        INSERT INTO admin_settings (setting_key, setting_value, setting_type, description, updated_at, updated_by) 
                        VALUES (?, ?, 'string', ?, NOW(), ?)
                    ");
                    
                    $result = $insertStmt->execute([$key, $value, $description, $_SESSION['admin_user']['username'] ?? 'admin']);
                }
                
                error_log("Webhook setting update - Key: $key, Value: $value, Result: " . ($result ? 'SUCCESS' : 'FAILED'));
            }
            
            // Store success message in session and redirect to prevent form resubmission
            $_SESSION['webhook_message'] = 'Webhook configuration updated successfully';
            error_log("Webhook config update completed successfully");
            header('Location: webhook-settings.php');
            exit();
            
        } elseif (isset($_POST['update_event_config'])) {
            // Update event configuration settings only
            $webhookEvents = $_POST['webhook_events'] ?? [];
            
            // Validate that at least one event is selected if webhooks are enabled
            $currentWebhookEnabled = getWebhookSetting('webhook_enabled');
            if ($currentWebhookEnabled === 'true' && empty($webhookEvents)) {
                throw new Exception('At least one event must be selected when webhooks are enabled');
            }
            
            // Convert events array to JSON
            $webhookEventsJson = json_encode($webhookEvents);
            
            // Update only webhook events setting
            $stmt = $pdo->prepare("
                UPDATE admin_settings 
                SET setting_value = ?, updated_at = NOW(), updated_by = ? 
                WHERE setting_key = 'webhook_events'
            ");
            
            $result = $stmt->execute([$webhookEventsJson, $_SESSION['admin_user']['username'] ?? 'admin']);
            $rowsAffected = $stmt->rowCount();
            
            // If no rows were affected, the setting doesn't exist, so insert it
            if ($rowsAffected === 0) {
                $insertStmt = $pdo->prepare("
                    INSERT INTO admin_settings (setting_key, setting_value, setting_type, description, updated_at, updated_by) 
                    VALUES ('webhook_events', ?, 'string', 'Events to send via webhook', NOW(), ?)
                ");
                
                $result = $insertStmt->execute([$webhookEventsJson, $_SESSION['admin_user']['username'] ?? 'admin']);
            }
            
            error_log("Webhook events update - Result: " . ($result ? 'SUCCESS' : 'FAILED'));
            
            // Store success message in session and redirect to prevent form resubmission
            $_SESSION['webhook_message'] = 'Event configuration updated successfully';
            header('Location: webhook-settings.php');
            exit();
            
        } elseif (isset($_POST['test_webhook'])) {
            // Test webhook functionality
            $webhookService = new WebhookService($pdo);
            $testResult = $webhookService->testWebhook();
            
            if ($testResult['success']) {
                $_SESSION['webhook_message'] = 'Test webhook sent successfully! Webhook ID: ' . $testResult['webhook_id'];
            } else {
                $_SESSION['webhook_error'] = 'Test webhook failed: ' . $testResult['message'];
            }
            
            // Redirect to prevent form resubmission
            header('Location: webhook-settings.php');
            exit();
        }
        
    } catch (Exception $e) {
        error_log("Webhook settings error: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        $_SESSION['webhook_error'] = $e->getMessage();
        header('Location: webhook-settings.php');
        exit();
    }
}

// Get messages from session and clear them
if (isset($_SESSION['webhook_message'])) {
    $message = $_SESSION['webhook_message'];
    unset($_SESSION['webhook_message']);
}

if (isset($_SESSION['webhook_error'])) {
    $error = $_SESSION['webhook_error'];
    unset($_SESSION['webhook_error']);
}

// Generate CSRF token
if (!isset($_SESSION['webhook_csrf_token'])) {
    $_SESSION['webhook_csrf_token'] = bin2hex(random_bytes(32));
}

// Get current webhook settings
try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("
        SELECT setting_key, setting_value 
        FROM admin_settings 
        WHERE setting_key IN ('webhook_enabled', 'webhook_url', 'webhook_events', 'webhook_retry_count', 'webhook_timeout')
    ");
    $stmt->execute();
    $webhookSettings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Get webhook stats
    $webhookService = new WebhookService($pdo);
    $webhookStats = $webhookService->getWebhookStats();
    
} catch (Exception $e) {
    $error = 'Failed to load webhook settings: ' . $e->getMessage();
    $webhookSettings = [];
    $webhookStats = [];
}

// Helper function to get setting value
function getWebhookSetting($key, $default = '') {
    global $webhookSettings;
    return $webhookSettings[$key] ?? $default;
}

// Get enabled events
$enabledEvents = json_decode(getWebhookSetting('webhook_events', '[]'), true);
if (!is_array($enabledEvents)) {
    $enabledEvents = [];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webhook Settings - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header">
            <div>
                <h1><i class="fas fa-link"></i> Webhook Settings</h1>
                <p>Configure webhook endpoints to receive real-time registration updates</p>
            </div>
            <div class="page-actions">
                <a href="webhook-logs.php" class="btn btn-secondary">
                    <i class="fas fa-list-alt"></i> View Webhook Logs
                </a>
            </div>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-success mb-4"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-error mb-4"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>

        <!-- Webhook Statistics -->
        <?php if (!empty($webhookStats)): ?>
        <div class="stats-grid">
            <div class="stat-card">
                <h3><i class="fas fa-chart-bar"></i> Total Webhooks</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['total_webhooks'] ?? 0); ?></p>
                        <p class="stat-label">Total Sent</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-check-circle"></i> Successful</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['successful'] ?? 0); ?></p>
                        <p class="stat-label">Delivered</p>
                    </div>
                    <div class="stat-right-align">
                        <p class="stat-revenue"><?php echo $webhookStats['total_webhooks'] > 0 ? round(($webhookStats['successful'] / $webhookStats['total_webhooks']) * 100, 1) : 0; ?>%</p>
                        <p class="stat-label">Success Rate</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-exclamation-triangle"></i> Failed</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['failed'] ?? 0); ?></p>
                        <p class="stat-label">Client Errors</p>
                    </div>
                </div>
            </div>
            
            <div class="stat-card">
                <h3><i class="fas fa-times-circle"></i> Server Errors</h3>
                <div class="stat-layout">
                    <div>
                        <p class="stat-number"><?php echo number_format($webhookStats['server_errors'] ?? 0); ?></p>
                        <p class="stat-label">Retry Needed</p>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Settings Grid -->
        <div class="settings-grid">
            <!-- Webhook Configuration -->
            <div class="settings-card">
                <h3><i class="fas fa-cog"></i> Webhook Configuration</h3>
                <p style="margin: 0 0 20px 0; color: #64748b; font-size: 14px;">
                    Configure your webhook endpoint and authentication settings
                </p>
                
                <form method="POST" class="settings-form" onsubmit="console.log('Webhook config form submitting...'); return true;">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['webhook_csrf_token']); ?>">
                    <input type="hidden" name="debug_timestamp" value="<?php echo time(); ?>">
                    <div class="setting-row">
                        <div class="setting-info">
                            <h4><i class="fas fa-toggle-on"></i> Enable Webhooks</h4>
                            <p>Turn webhook notifications on or off</p>
                        </div>
                        <div class="setting-control">
                            <select name="webhook_enabled" class="form-control" style="width: 200px;">
                                <option value="false" <?php echo getWebhookSetting('webhook_enabled') === 'false' ? 'selected' : ''; ?>>Disabled</option>
                                <option value="true" <?php echo getWebhookSetting('webhook_enabled') === 'true' ? 'selected' : ''; ?>>Enabled</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="setting-row">
                        <div class="setting-info">
                            <h4><i class="fas fa-globe"></i> Webhook URL</h4>
                            <p>The endpoint URL where webhook data will be sent</p>
                        </div>
                        <div class="setting-control">
                            <input type="url" name="webhook_url" 
                                   value="<?php echo htmlspecialchars(getWebhookSetting('webhook_url')); ?>" 
                                   class="form-control" placeholder="https://your-domain.com/webhook" style="width: 400px;">
                        </div>
                    </div>
                    
                    <div class="setting-row">
                        <div class="setting-info">
                            <h4><i class="fas fa-redo"></i> Retry Configuration</h4>
                            <p>Configure retry attempts and timeout for failed webhook calls</p>
                        </div>
                        <div class="setting-control">
                            <div style="display: flex; gap: 16px;">
                                <div>
                                    <label style="display: block; margin-bottom: 4px; font-size: 12px; color: #64748b;"><i class="fas fa-sync"></i> Retry Count</label>
                                    <input type="number" name="webhook_retry_count" 
                                           value="<?php echo htmlspecialchars(getWebhookSetting('webhook_retry_count', '3')); ?>" 
                                           class="form-control" min="0" max="10" style="width: 100px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 4px; font-size: 12px; color: #64748b;"><i class="fas fa-clock"></i> Timeout (seconds)</label>
                                    <input type="number" name="webhook_timeout" 
                                           value="<?php echo htmlspecialchars(getWebhookSetting('webhook_timeout', '30')); ?>" 
                                           class="form-control" min="5" max="120" style="width: 100px;">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" name="update_webhook_config" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Webhook Configuration
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Event Configuration -->
            <div class="settings-card">
                <h3><i class="fas fa-broadcast-tower"></i> Event Configuration</h3>
                <p style="margin: 0 0 20px 0; color: #64748b; font-size: 14px;">
                    Select which events should trigger webhook notifications
                </p>
                
                <form method="POST" class="settings-form">
                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['webhook_csrf_token']); ?>">
                    <div class="webhook-events-grid">
                        <label class="event-checkbox">
                            <input type="checkbox" name="webhook_events[]" value="registration_created" 
                                   <?php echo in_array('registration_created', $enabledEvents) ? 'checked' : ''; ?>>
                            <div class="event-info">
                                <strong><i class="fas fa-user-plus"></i> Registration Created</strong>
                                <span>New registration submitted</span>
                            </div>
                        </label>
                        
                        <label class="event-checkbox">
                            <input type="checkbox" name="webhook_events[]" value="payment_status_changed" 
                                   <?php echo in_array('payment_status_changed', $enabledEvents) ? 'checked' : ''; ?>>
                            <div class="event-info">
                                <strong><i class="fas fa-credit-card"></i> Payment Status Changed</strong>
                                <span>Payment status updated</span>
                            </div>
                        </label>
                        
                        <label class="event-checkbox">
                            <input type="checkbox" name="webhook_events[]" value="registration_updated" 
                                   <?php echo in_array('registration_updated', $enabledEvents) ? 'checked' : ''; ?>>
                            <div class="event-info">
                                <strong><i class="fas fa-edit"></i> Registration Updated</strong>
                                <span>Registration details modified</span>
                            </div>
                        </label>
                        
                        <label class="event-checkbox">
                            <input type="checkbox" name="webhook_events[]" value="delegate_added" 
                                   <?php echo in_array('delegate_added', $enabledEvents) ? 'checked' : ''; ?>>
                            <div class="event-info">
                                <strong><i class="fas fa-user-friends"></i> Delegate Added</strong>
                                <span>New delegate added</span>
                            </div>
                        </label>
                        
                        <label class="event-checkbox">
                            <input type="checkbox" name="webhook_events[]" value="registration_cancelled" 
                                   <?php echo in_array('registration_cancelled', $enabledEvents) ? 'checked' : ''; ?>>
                            <div class="event-info">
                                <strong><i class="fas fa-ban"></i> Registration Cancelled</strong>
                                <span>Registration cancelled</span>
                            </div>
                        </label>
                    </div>
                    
                    <div class="form-actions">
                        <button type="submit" name="update_event_config" class="btn btn-primary">
                            <i class="fas fa-save"></i> Update Event Settings
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- Test Webhook -->
            <div class="settings-card">
                <h3><i class="fas fa-flask"></i> Test Webhook</h3>
                <p style="margin: 0 0 20px 0; color: #64748b; font-size: 14px;">
                    Test your webhook configuration by sending a test payload
                </p>
                
                <?php if (getWebhookSetting('webhook_enabled') === 'true' && !empty(getWebhookSetting('webhook_url'))): ?>
                    <div class="setting-row">
                        <div class="setting-info">
                            <h4><i class="fas fa-link"></i> Current Endpoint</h4>
                            <p>Webhook URL: <code style="background: #f1f5f9; padding: 4px 8px; border-radius: 4px; font-size: 12px;"><?php echo htmlspecialchars(getWebhookSetting('webhook_url')); ?></code></p>
                        </div>
                        <div class="setting-control">
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['webhook_csrf_token']); ?>">
                                <button type="submit" name="test_webhook" class="btn btn-secondary">
                                    <i class="fas fa-paper-plane"></i> Send Test Webhook
                                </button>
                            </form>
                        </div>
                    </div>
                <?php else: ?>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Enable webhooks and configure a webhook URL to test the functionality.
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Documentation -->
            <div class="settings-card">
                <h3><i class="fas fa-book"></i> Webhook Documentation</h3>
                <p style="margin: 0 0 20px 0; color: #64748b; font-size: 14px;">
                    Technical details about webhook implementation and authentication
                </p>
                
                <div class="info-box">
                    <h4><i class="fas fa-box"></i> Payload Format</h4>
                    <p>All webhooks send data in the following JSON format:</p>
                    <pre style="background: #f8fafc; padding: 16px; border-radius: 8px; border: 1px solid #e2e8f0; font-size: 12px; overflow-x: auto;"><code>{
  "event": "event_type",
  "timestamp": "2025-01-27T10:30:00+00:00",
  "data": { ... },
  "webhook_id": "wh_unique_id"
}</code></pre>
                    
                    <h4><i class="fas fa-broadcast-tower"></i> Response Codes</h4>
                    <p>Your webhook endpoint should return HTTP 200-299 for successful processing. Any other status code will trigger retry attempts.</p>
                    
                    <h4><i class="fas fa-info-circle"></i> Security Note</h4>
                    <p>This webhook system pushes data to external endpoints. Ensure your webhook URL is secure and only accessible to trusted systems. Consider implementing additional security measures on your webhook endpoint if needed.</p>
                </div>
            </div>
        </div>
    </div>

    <style>
        .webhook-events-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 16px;
            margin: 20px 0;
        }
        
        .event-checkbox {
            display: flex;
            align-items: flex-start;
            gap: 12px;
            padding: 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: #f8fafc;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .event-checkbox:hover {
            background: #f1f5f9;
            border-color: #cbd5e1;
        }
        
        .event-checkbox input[type="checkbox"] {
            margin: 0;
            margin-top: 2px;
        }
        
        .event-info {
            flex: 1;
        }
        
        .event-info strong {
            display: block;
            margin-bottom: 4px;
            color: #1e293b;
        }
        
        .event-info strong i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .event-info span {
            font-size: 12px;
            color: #64748b;
        }
        
        .info-box {
            background: #f0f9ff;
            border: 1px solid #0ea5e9;
            border-radius: 8px;
            padding: 20px;
        }
        
        .info-box h4 {
            margin: 0 0 12px 0;
            color: #0c4a6e;
            font-size: 14px;
        }
        
        .info-box h4 i {
            margin-right: 8px;
            color: #0ea5e9;
        }
        
        .info-box p {
            margin: 0 0 16px 0;
            color: #0c4a6e;
            font-size: 13px;
        }
        
        .info-box p:last-child {
            margin-bottom: 0;
        }
        
        .info-box code {
            background: #e0f2fe;
            color: #0c4a6e;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .stat-card h3 i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .setting-info h4 i {
            margin-right: 8px;
            color: #64748b;
        }
        
        .page-header h1 i {
            margin-right: 12px;
            color: #2563eb;
        }
    </style>

    <?php include 'includes/footer.php'; ?>
    
    <script>
        // TEMPORARILY DISABLED FOR DEBUGGING
        // Prevent form resubmission and provide better form handling
        document.addEventListener('DOMContentLoaded', function() {
            console.log('Webhook settings JavaScript loaded');
            return; // Exit early to disable all form handling
            
            // DISABLED CODE BELOW
            const forms = document.querySelectorAll('form');
            let hasUnsavedChanges = false;
            const warnOnUnsaved = false; // Disabled to avoid blocking legitimate form submissions
            
            // Check if we're coming from a successful form submission
            const isFormSubmitted = sessionStorage.getItem('webhook_form_submitted');
            if (isFormSubmitted) {
                hasUnsavedChanges = false;
                sessionStorage.removeItem('webhook_form_submitted');
            }
            
            forms.forEach(form => {
                // Track form changes
                const formInputs = form.querySelectorAll('input, select, textarea');
                formInputs.forEach(input => {
                    input.addEventListener('change', function() {
                        hasUnsavedChanges = true;
                    });
                    
                    input.addEventListener('input', function() {
                        hasUnsavedChanges = true;
                    });
                });
                
                form.addEventListener('submit', function(e) {
                    const submitBtn = form.querySelector('button[type="submit"]');
                    if (submitBtn) {
                        submitBtn.disabled = true;
                        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
                    }
                    
                    // Prevent double submission
                    if (form.dataset.submitted === 'true') {
                        e.preventDefault();
                        return false;
                    }
                    
                    form.dataset.submitted = 'true';
                    
                    // Mark that changes are being saved (not unsaved)
                    hasUnsavedChanges = false;
                    
                    // Set session storage to indicate form was submitted
                    sessionStorage.setItem('webhook_form_submitted', 'true');
                    
                    // Show form-specific loading state
                    const formCard = form.closest('.settings-card');
                    if (formCard) {
                        formCard.style.opacity = '0.7';
                        formCard.style.pointerEvents = 'none';
                    }
                });
            });
            
            // Warn user only if explicitly enabled
            window.addEventListener('beforeunload', function(e) {
                if (warnOnUnsaved && hasUnsavedChanges) {
                    e.preventDefault();
                    e.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
                    return e.returnValue;
                }
            });
            
            // Add form validation feedback
            const webhookUrlInput = document.querySelector('input[name="webhook_url"]');
            const webhookEnabledSelect = document.querySelector('select[name="webhook_enabled"]');
            const eventCheckboxes = document.querySelectorAll('input[name="webhook_events[]"]');
            
            if (webhookUrlInput && webhookEnabledSelect) {
                function validateWebhookConfig() {
                    const isEnabled = webhookEnabledSelect.value === 'true';
                    const hasUrl = webhookUrlInput.value.trim() !== '';
                    
                    if (isEnabled && !hasUrl) {
                        webhookUrlInput.style.borderColor = '#ef4444';
                        webhookUrlInput.title = 'Webhook URL is required when webhooks are enabled';
                    } else {
                        webhookUrlInput.style.borderColor = '';
                        webhookUrlInput.title = '';
                    }
                }
                
                webhookEnabledSelect.addEventListener('change', validateWebhookConfig);
                webhookUrlInput.addEventListener('input', validateWebhookConfig);
                
                // Initial validation
                validateWebhookConfig();
            }
            
            // Event validation
            if (eventCheckboxes.length > 0) {
                function validateEvents() {
                    const checkedEvents = Array.from(eventCheckboxes).filter(cb => cb.checked);
                    const isEnabled = webhookEnabledSelect?.value === 'true';
                    
                    eventCheckboxes.forEach(checkbox => {
                        if (isEnabled && checkedEvents.length === 0) {
                            checkbox.style.borderColor = '#ef4444';
                        } else {
                            checkbox.style.borderColor = '';
                        }
                    });
                }
                
                eventCheckboxes.forEach(checkbox => {
                    checkbox.addEventListener('change', validateEvents);
                });
                
                // Initial validation
                validateEvents();
            }
            
            // Reset unsaved changes flag when page loads (after successful submission)
            if (window.location.search === '' && !document.querySelector('form[data-submitted="true"]')) {
                hasUnsavedChanges = false;
            }
            
            // Check if we're coming from a successful form submission
            if (window.location.search === '' && (document.querySelector('.alert-success') || document.querySelector('.alert-error'))) {
                hasUnsavedChanges = false;
                
                // Remove the submitted state from forms
                forms.forEach(form => {
                    form.removeAttribute('data-submitted');
                });
            }
        });
    </script>
</body>
</html>
