<!-- Content Header (Page header) -->
<section class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1><i class="fas fa-cogs mr-2"></i>Настройки сайта</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="/admin">Админ</a></li>
                    <li class="breadcrumb-item active">Настройки</li>
                </ol>
            </div>
        </div>
    </div>
</section>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Site Information Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Основная информация</h3>
            </div>
            <form id="site-settings-form">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="site-title">Название сайта</label>
                                <input type="text" class="form-control" id="site-title" name="siteTitle" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="site-tagline">Слоган</label>
                                <input type="text" class="form-control" id="site-tagline" name="siteTagline">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="site-description">Описание сайта</label>
                        <textarea class="form-control" id="site-description" name="siteDescription" rows="3"></textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="company-name">Название компании</label>
                                <input type="text" class="form-control" id="company-name" name="companyName" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="company-email">Email компании</label>
                                <input type="email" class="form-control" id="company-email" name="companyEmail" required>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="company-phone">Телефон</label>
                                <input type="tel" class="form-control" id="company-phone" name="companyPhone">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="company-address">Адрес</label>
                                <input type="text" class="form-control" id="company-address" name="companyAddress">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i>Сохранить
                    </button>
                </div>
            </form>
        </div>

        <!-- SEO Settings Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">SEO настройки</h3>
            </div>
            <form id="seo-settings-form">
                <div class="card-body">
                    <div class="form-group">
                        <label for="meta-keywords">Ключевые слова</label>
                        <input type="text" class="form-control" id="meta-keywords" name="metaKeywords" 
                               placeholder="ключевое слово 1, ключевое слово 2, ...">
                        <small class="form-text text-muted">Разделяйте ключевые слова запятыми</small>
                    </div>

                    <div class="form-group">
                        <label for="meta-description">Meta Description</label>
                        <textarea class="form-control" id="meta-description" name="metaDescription" 
                                  rows="3" maxlength="160"></textarea>
                        <small class="form-text text-muted">Рекомендуемая длина: до 160 символов</small>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="google-analytics">Google Analytics ID</label>
                                <input type="text" class="form-control" id="google-analytics" name="googleAnalytics" 
                                       placeholder="G-XXXXXXXXXX">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="google-tag-manager">Google Tag Manager ID</label>
                                <input type="text" class="form-control" id="google-tag-manager" name="googleTagManager" 
                                       placeholder="GTM-XXXXXXX">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i>Сохранить SEO
                    </button>
                </div>
            </form>
        </div>

        <!-- Social Media Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Социальные сети</h3>
            </div>
            <form id="social-settings-form">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="facebook-url"><i class="fab fa-facebook mr-1"></i>Facebook</label>
                                <input type="url" class="form-control" id="facebook-url" name="facebookUrl" 
                                       placeholder="https://facebook.com/your-page">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="twitter-url"><i class="fab fa-twitter mr-1"></i>Twitter</label>
                                <input type="url" class="form-control" id="twitter-url" name="twitterUrl" 
                                       placeholder="https://twitter.com/your-account">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="linkedin-url"><i class="fab fa-linkedin mr-1"></i>LinkedIn</label>
                                <input type="url" class="form-control" id="linkedin-url" name="linkedinUrl" 
                                       placeholder="https://linkedin.com/company/your-company">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="instagram-url"><i class="fab fa-instagram mr-1"></i>Instagram</label>
                                <input type="url" class="form-control" id="instagram-url" name="instagramUrl" 
                                       placeholder="https://instagram.com/your-account">
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="youtube-url"><i class="fab fa-youtube mr-1"></i>YouTube</label>
                                <input type="url" class="form-control" id="youtube-url" name="youtubeUrl" 
                                       placeholder="https://youtube.com/channel/your-channel">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="github-url"><i class="fab fa-github mr-1"></i>GitHub</label>
                                <input type="url" class="form-control" id="github-url" name="githubUrl" 
                                       placeholder="https://github.com/your-account">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save mr-1"></i>Сохранить соцсети
                    </button>
                </div>
            </form>
        </div>

        <!-- Maintenance Mode Card -->
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Режим обслуживания</h3>
            </div>
            <div class="card-body">
                <div class="form-group">
                    <div class="custom-control custom-switch">
                        <input type="checkbox" class="custom-control-input" id="maintenance-mode">
                        <label class="custom-control-label" for="maintenance-mode">
                            Включить режим обслуживания
                        </label>
                    </div>
                    <small class="form-text text-muted">
                        В режиме обслуживания сайт будет недоступен для обычных пользователей
                    </small>
                </div>

                <div class="form-group">
                    <label for="maintenance-message">Сообщение для пользователей</label>
                    <textarea class="form-control" id="maintenance-message" rows="3" 
                              placeholder="Сайт временно недоступен из-за технических работ..."></textarea>
                </div>

                <button type="button" class="btn btn-warning" onclick="toggleMaintenanceMode()">
                    <i class="fas fa-tools mr-1"></i>Применить настройки
                </button>
            </div>
        </div>
    </div>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        loadSettings();
        
        // Setup form submissions
        document.getElementById('site-settings-form').addEventListener('submit', saveSiteSettings);
        document.getElementById('seo-settings-form').addEventListener('submit', saveSeoSettings);
        document.getElementById('social-settings-form').addEventListener('submit', saveSocialSettings);
    });

    async function loadSettings() {
        try {
            const response = await fetch('/api/admin/settings');
            const data = await response.json();
            
            if (data.success) {
                const settings = data.settings;
                
                // Site settings
                document.getElementById('site-title').value = settings.siteTitle || '';
                document.getElementById('site-tagline').value = settings.siteTagline || '';
                document.getElementById('site-description').value = settings.siteDescription || '';
                document.getElementById('company-name').value = settings.companyName || '';
                document.getElementById('company-email').value = settings.companyEmail || '';
                document.getElementById('company-phone').value = settings.companyPhone || '';
                document.getElementById('company-address').value = settings.companyAddress || '';
                
                // SEO settings
                document.getElementById('meta-keywords').value = settings.metaKeywords || '';
                document.getElementById('meta-description').value = settings.metaDescription || '';
                document.getElementById('google-analytics').value = settings.googleAnalytics || '';
                document.getElementById('google-tag-manager').value = settings.googleTagManager || '';
                
                // Social media
                document.getElementById('facebook-url').value = settings.facebookUrl || '';
                document.getElementById('twitter-url').value = settings.twitterUrl || '';
                document.getElementById('linkedin-url').value = settings.linkedinUrl || '';
                document.getElementById('instagram-url').value = settings.instagramUrl || '';
                document.getElementById('youtube-url').value = settings.youtubeUrl || '';
                document.getElementById('github-url').value = settings.githubUrl || '';
                
                // Maintenance mode
                document.getElementById('maintenance-mode').checked = settings.maintenanceMode || false;
                document.getElementById('maintenance-message').value = settings.maintenanceMessage || '';
            }
        } catch (error) {
            console.error('Error loading settings:', error);
            alert('Ошибка загрузки настроек: ' + error.message);
        }
    }

    async function saveSiteSettings(event) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const settings = {
            siteTitle: formData.get('siteTitle'),
            siteTagline: formData.get('siteTagline'),
            siteDescription: formData.get('siteDescription'),
            companyName: formData.get('companyName'),
            companyEmail: formData.get('companyEmail'),
            companyPhone: formData.get('companyPhone'),
            companyAddress: formData.get('companyAddress')
        };

        await saveSettings(settings, 'Основные настройки сохранены');
    }

    async function saveSeoSettings(event) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const settings = {
            metaKeywords: formData.get('metaKeywords'),
            metaDescription: formData.get('metaDescription'),
            googleAnalytics: formData.get('googleAnalytics'),
            googleTagManager: formData.get('googleTagManager')
        };

        await saveSettings(settings, 'SEO настройки сохранены');
    }

    async function saveSocialSettings(event) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const settings = {
            facebookUrl: formData.get('facebookUrl'),
            twitterUrl: formData.get('twitterUrl'),
            linkedinUrl: formData.get('linkedinUrl'),
            instagramUrl: formData.get('instagramUrl'),
            youtubeUrl: formData.get('youtubeUrl'),
            githubUrl: formData.get('githubUrl')
        };

        await saveSettings(settings, 'Настройки соцсетей сохранены');
    }

    async function saveSettings(settings, successMessage) {
        try {
            const response = await fetch('/api/admin/settings', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(settings)
            });

            const data = await response.json();

            if (data.success) {
                alert(successMessage);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            console.error('Error saving settings:', error);
            alert('Ошибка сохранения настроек: ' + error.message);
        }
    }

    async function toggleMaintenanceMode() {
        const isEnabled = document.getElementById('maintenance-mode').checked;
        const message = document.getElementById('maintenance-message').value;
        
        const settings = {
            maintenanceMode: isEnabled,
            maintenanceMessage: message
        };

        await saveSettings(settings, 
            isEnabled ? 'Режим обслуживания включен' : 'Режим обслуживания отключен'
        );
    }
</script>