<?php
/**
 * IoT Settings - إعدادات النظام
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get current settings
    $settings_query = "SELECT * FROM iot_settings LIMIT 1";
    $settings_stmt = $db->query($settings_query);
    $settings = $settings_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$settings) {
        // Create default settings
        $default_query = "INSERT INTO iot_settings (api_key, auto_discovery, log_level, max_devices) 
                         VALUES ('', 1, 'info', 10)";
        $db->exec($default_query);
        
        $settings_stmt = $db->query($settings_query);
        $settings = $settings_stmt->fetch(PDO::FETCH_ASSOC);
    }
    
} catch (Exception $e) {
    die('<div style="padding:20px;background:#ef4444;color:white;">❌ خطأ: ' . htmlspecialchars($e->getMessage()) . '</div>');
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إعدادات IoT</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * { font-family: 'Tajawal', sans-serif; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .card { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
        .btn { padding: 12px 24px; border-radius: 10px; font-weight: 600; transition: all 0.3s; cursor: pointer; border: none; text-decoration: none; display: inline-block; }
        .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
        .btn-success { background: linear-gradient(135deg, #10b981, #059669); color: white; }
        .btn:hover { transform: scale(1.05); }
        .input-field { width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 10px; transition: all 0.3s; }
        .input-field:focus { outline: none; border-color: #667eea; box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); }
        .toggle-switch { position: relative; display: inline-block; width: 60px; height: 34px; }
        .toggle-switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; inset: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
        .slider:before { position: absolute; content: ""; height: 26px; width: 26px; right: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .slider { background-color: #10b981; }
        input:checked + .slider:before { transform: translateX(-26px); }
    </style>
</head>
<body>
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="card mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-cog text-purple-600 ml-2"></i>
                        إعدادات النظام
                    </h1>
                    <p class="text-gray-600">تخصيص إعدادات IoT</p>
                </div>
                <a href="index.php" class="btn bg-gray-200 text-gray-800">
                    <i class="fas fa-arrow-right ml-2"></i>
                    رجوع
                </a>
            </div>
        </div>

        <!-- Settings Form -->
        <div class="card">
            <form id="settingsForm" class="space-y-6">
                <!-- API Key -->
                <div>
                    <label class="block text-lg font-bold text-gray-900 mb-3">
                        <i class="fas fa-key ml-2"></i>
                        مفتاح API
                    </label>
                    <input type="text" name="api_key" id="api_key" 
                           value="<?php echo htmlspecialchars($settings['api_key'] ?? ''); ?>"
                           class="input-field" 
                           placeholder="أدخل مفتاح API للأمان">
                    <p class="text-sm text-gray-600 mt-2">
                        <i class="fas fa-info-circle ml-1"></i>
                        يُستخدم لتأمين الاتصال بين الأجهزة والسيرفر
                    </p>
                </div>

                <!-- Auto Discovery -->
                <div class="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div>
                        <label class="block text-lg font-bold text-gray-900 mb-1">
                            <i class="fas fa-search ml-2"></i>
                            الاكتشاف التلقائي للأجهزة
                        </label>
                        <p class="text-sm text-gray-600">
                            البحث عن أجهزة جديدة تلقائياً على الشبكة
                        </p>
                    </div>
                    <label class="toggle-switch">
                        <input type="checkbox" name="auto_discovery" id="auto_discovery" 
                               <?php echo ($settings['auto_discovery'] ?? 1) ? 'checked' : ''; ?>>
                        <span class="slider"></span>
                    </label>
                </div>

                <!-- Log Level -->
                <div>
                    <label class="block text-lg font-bold text-gray-900 mb-3">
                        <i class="fas fa-file-alt ml-2"></i>
                        مستوى السجلات
                    </label>
                    <select name="log_level" id="log_level" class="input-field">
                        <option value="debug" <?php echo ($settings['log_level'] ?? '') === 'debug' ? 'selected' : ''; ?>>
                            Debug (تفصيلي جداً)
                        </option>
                        <option value="info" <?php echo ($settings['log_level'] ?? 'info') === 'info' ? 'selected' : ''; ?>>
                            Info (معلومات عامة)
                        </option>
                        <option value="warning" <?php echo ($settings['log_level'] ?? '') === 'warning' ? 'selected' : ''; ?>>
                            Warning (تحذيرات فقط)
                        </option>
                        <option value="error" <?php echo ($settings['log_level'] ?? '') === 'error' ? 'selected' : ''; ?>>
                            Error (أخطاء فقط)
                        </option>
                    </select>
                </div>

                <!-- Max Devices -->
                <div>
                    <label class="block text-lg font-bold text-gray-900 mb-3">
                        <i class="fas fa-microchip ml-2"></i>
                        الحد الأقصى للأجهزة
                    </label>
                    <input type="number" name="max_devices" id="max_devices" 
                           value="<?php echo htmlspecialchars($settings['max_devices'] ?? 10); ?>"
                           min="1" max="100"
                           class="input-field">
                    <p class="text-sm text-gray-600 mt-2">
                        <i class="fas fa-info-circle ml-1"></i>
                        عدد الأجهزة المسموح بها في النظام
                    </p>
                </div>

                <!-- Submit Button -->
                <div class="pt-4">
                    <button type="submit" class="w-full btn btn-success py-4 text-lg">
                        <i class="fas fa-save ml-2"></i>
                        حفظ الإعدادات
                    </button>
                </div>
            </form>
        </div>

        <!-- System Info -->
        <div class="card mt-6">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">
                <i class="fas fa-info-circle ml-2"></i>
                معلومات النظام
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="p-4 bg-blue-50 rounded-lg">
                    <p class="text-sm text-gray-600 mb-1">إصدار النظام</p>
                    <p class="text-xl font-bold text-gray-900">v1.0.0</p>
                </div>
                <div class="p-4 bg-green-50 rounded-lg">
                    <p class="text-sm text-gray-600 mb-1">حالة قاعدة البيانات</p>
                    <p class="text-xl font-bold text-green-600">
                        <i class="fas fa-check-circle ml-1"></i>
                        متصلة
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
    document.getElementById('settingsForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const data = {
            api_key: formData.get('api_key'),
            auto_discovery: formData.get('auto_discovery') ? 1 : 0,
            log_level: formData.get('log_level'),
            max_devices: parseInt(formData.get('max_devices'))
        };

        try {
            const response = await fetch('../../api/iot/settings.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();

            if (result.success) {
                alert('✅ تم حفظ الإعدادات بنجاح!');
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    });
    </script>
</body>
</html>
