<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Help Settings Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .main-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 20px;
            padding: 30px;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #e9ecef;
        }
        .header h1 {
            color: #2c3e50;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .header p {
            color: #6c757d;
            font-size: 16px;
        }
        .setting-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }
        .setting-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
        }
        .setting-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
            margin-right: 20px;
        }
        .phone-icon { background: linear-gradient(45deg, #28a745, #20c997); }
        .whatsapp-icon { background: linear-gradient(45deg, #25d366, #128c7e); }
        .email-icon { background: linear-gradient(45deg, #dc3545, #e83e8c); }
        .hours-icon { background: linear-gradient(45deg, #ffc107, #fd7e14); }
        .message-icon { background: linear-gradient(45deg, #6f42c1, #e83e8c); }
        
        .form-control {
            border-radius: 10px;
            border: 2px solid #e9ecef;
            padding: 12px 15px;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        .btn-save {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            border-radius: 10px;
            padding: 10px 25px;
            color: white;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .loading {
            text-align: center;
            padding: 50px;
        }
        .spinner-border {
            width: 3rem;
            height: 3rem;
            color: #667eea;
        }
        .alert {
            border-radius: 10px;
            border: none;
            padding: 15px 20px;
            margin-bottom: 20px;
        }
        .back-btn {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(255, 255, 255, 0.9);
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #667eea;
            font-size: 18px;
            transition: all 0.3s ease;
        }
        .back-btn:hover {
            background: white;
            transform: scale(1.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <a href="index.php" class="back-btn">
            <i class="fas fa-arrow-left"></i>
        </a>
        
        <div class="main-container">
            <div class="header">
                <h1><i class="fas fa-headset me-3"></i>Help Settings Management</h1>
                <p>Manage support contact information and help settings</p>
            </div>

            <!-- Alert Messages -->
            <div id="alertContainer"></div>

            <!-- Loading Spinner -->
            <div class="loading" id="loadingSpinner">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading help settings...</p>
            </div>

            <!-- Settings Container -->
            <div id="settingsContainer" style="display: none;">
                <!-- Settings will be loaded here -->
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let helpSettings = [];

        // Load help settings on page load
        document.addEventListener('DOMContentLoaded', function() {
            console.log('=== PAGE LOADED ===');
            loadHelpSettings();
        });

        // Load help settings from API
        async function loadHelpSettings() {
            console.log('=== LOADING HELP SETTINGS ===');
            showLoading(true);
            
            try {
                console.log('Making GET API call to: ../api/help_settings_management.php');
                const response = await fetch('../api/help_settings_management.php', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                });
                console.log('Response received:', response);
                console.log('Response status:', response.status);
                console.log('Response ok:', response.ok);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const responseText = await response.text();
                console.log('Raw response text:', responseText);
                
                if (!responseText.trim()) {
                    throw new Error('Empty response from server');
                }
                
                const data = JSON.parse(responseText);
                console.log('Parsed JSON data:', data);
                
                if (data.success) {
                    helpSettings = data.settings;
                    console.log('Help settings loaded successfully:', helpSettings);
                    console.log('Number of settings:', helpSettings.length);
                    renderSettings();
                } else {
                    console.error('API returned error:', data.message);
                    showAlert('Error loading help settings: ' + data.message, 'danger');
                }
            } catch (error) {
                console.error('=== FETCH ERROR ===');
                console.error('Error type:', error.name);
                console.error('Error message:', error.message);
                console.error('Error stack:', error.stack);
                showAlert('Error loading help settings: ' + error.message, 'danger');
            } finally {
                console.log('Calling showLoading(false)');
                showLoading(false);
            }
        }

        // Render settings
        function renderSettings() {
            console.log('=== RENDERING SETTINGS ===');
            console.log('Settings to render:', helpSettings);
            
            const container = document.getElementById('settingsContainer');
            
            if (!container) {
                console.error('Settings container element not found!');
                return;
            }
            
            let html = '';
            
            helpSettings.forEach(setting => {
                const iconClass = getIconClass(setting.setting_key);
                const displayName = getDisplayName(setting.setting_key);
                
                html += `
                    <div class="setting-card">
                        <div class="d-flex align-items-center mb-3">
                            <div class="setting-icon ${iconClass}">
                                <i class="${getIcon(setting.setting_key)}"></i>
                            </div>
                            <div>
                                <h5 class="mb-1">${displayName}</h5>
                                <p class="text-muted mb-0">${setting.description || ''}</p>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-8">
                                <input 
                                    type="text" 
                                    class="form-control" 
                                    id="setting_${setting.id}" 
                                    value="${setting.setting_value}"
                                    placeholder="Enter ${displayName.toLowerCase()}"
                                >
                            </div>
                            <div class="col-md-4">
                                <button 
                                    class="btn btn-save w-100" 
                                    onclick="updateSetting(${setting.id})"
                                >
                                    <i class="fas fa-save me-2"></i>Update
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
            console.log('Settings rendered successfully');
        }

        // Get icon class based on setting key
        function getIconClass(settingKey) {
            switch (settingKey) {
                case 'phone_number': return 'phone-icon';
                case 'whatsapp_number': return 'whatsapp-icon';
                case 'email_address': return 'email-icon';
                case 'support_hours': return 'hours-icon';
                case 'support_message': return 'message-icon';
                default: return 'phone-icon';
            }
        }

        // Get icon based on setting key
        function getIcon(settingKey) {
            switch (settingKey) {
                case 'phone_number': return 'fas fa-phone';
                case 'whatsapp_number': return 'fab fa-whatsapp';
                case 'email_address': return 'fas fa-envelope';
                case 'support_hours': return 'fas fa-clock';
                case 'support_message': return 'fas fa-comment';
                default: return 'fas fa-cog';
            }
        }

        // Get display name based on setting key
        function getDisplayName(settingKey) {
            switch (settingKey) {
                case 'phone_number': return 'Phone Number';
                case 'whatsapp_number': return 'WhatsApp Number';
                case 'email_address': return 'Email Address';
                case 'support_hours': return 'Support Hours';
                case 'support_message': return 'Default Message';
                default: return settingKey;
            }
        }

        // Update setting
        async function updateSetting(settingId) {
            const input = document.getElementById(`setting_${settingId}`);
            const newValue = input.value.trim();
            
            if (!newValue) {
                showAlert('Please enter a value', 'warning');
                return;
            }
            
            try {
                console.log(`Updating setting ${settingId} with value: ${newValue}`);
                
                const response = await fetch('../api/help_settings_management.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'update',
                        id: settingId,
                        setting_value: newValue
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showAlert('Setting updated successfully!', 'success');
                    // Update the setting in our local array
                    const setting = helpSettings.find(s => s.id == settingId);
                    if (setting) {
                        setting.setting_value = newValue;
                    }
                } else {
                    showAlert('Error updating setting: ' + data.message, 'danger');
                }
            } catch (error) {
                console.error('Error updating setting:', error);
                showAlert('Error updating setting: ' + error.message, 'danger');
            }
        }

        // Show/hide loading
        function showLoading(show) {
            console.log('=== SHOW LOADING ===');
            console.log('Show loading:', show);
            
            const loadingSpinner = document.getElementById('loadingSpinner');
            const settingsContainer = document.getElementById('settingsContainer');
            
            console.log('Loading spinner element:', loadingSpinner);
            console.log('Settings container element:', settingsContainer);
            
            if (loadingSpinner) {
                loadingSpinner.style.display = show ? 'block' : 'none';
                console.log('Loading spinner display set to:', loadingSpinner.style.display);
            } else {
                console.error('Loading spinner element not found!');
            }
            
            if (settingsContainer) {
                settingsContainer.style.display = show ? 'none' : 'block';
                console.log('Settings container display set to:', settingsContainer.style.display);
            } else {
                console.error('Settings container element not found!');
            }
        }

        // Show alert
        function showAlert(message, type) {
            const alertContainer = document.getElementById('alertContainer');
            const alertId = 'alert-' + Date.now();
            
            alertContainer.innerHTML = `
                <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert">
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // Auto remove after 5 seconds
            setTimeout(() => {
                const alert = document.getElementById(alertId);
                if (alert) {
                    alert.remove();
                }
            }, 5000);
        }
    </script>
</body>
</html>
