<?php
/**
 * IoT Settings Page
 * Configure WiFi and global settings
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if settings table exists
    $check = $db->query("SHOW TABLES LIKE 'iot_settings'")->rowCount();
    if ($check == 0) {
        header('Location: ../database/create_iot_settings_table.php');
        exit;
    }
    
    // Handle form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        foreach ($_POST as $key => $value) {
            if (strpos($key, 'setting_') === 0) {
                $setting_key = str_replace('setting_', '', $key);
                $stmt = $db->prepare("UPDATE iot_settings SET setting_value = ? WHERE setting_key = ?");
                $stmt->execute([$value, $setting_key]);
            }
        }
        $success_message = "✅ تم حفظ الإعدادات بنجاح!";
    }
    
    // Fetch all settings
    $settings = $db->query("SELECT * FROM iot_settings ORDER BY id")->fetchAll(PDO::FETCH_ASSOC);
    $settings_map = [];
    foreach ($settings as $setting) {
        $settings_map[$setting['setting_key']] = $setting['setting_value'];
    }
    
} catch (Exception $e) {
    die("Error: " . $e->getMessage());
}
?>
<!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 - Roz Skin</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; }
        .setting-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        .setting-card:hover {
            transform: translateY(-3px);
        }
        .input-field {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        .input-field:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        .btn-save {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 15px 40px;
            border-radius: 10px;
            font-weight: bold;
            border: none;
            cursor: pointer;
            transition: transform 0.3s ease;
        }
        .btn-save:hover {
            transform: scale(1.05);
        }
        .alert {
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            animation: slideDown 0.3s ease;
        }
        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body class="p-4 md:p-8">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-2xl shadow-xl p-6 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>
                        إعدادات IoT
                    </h1>
                    <p class="text-gray-600">تكوين WiFi والإعدادات العامة للأجهزة</p>
                </div>
                <a href="iot_devices.php" class="bg-gray-200 text-gray-800 px-6 py-3 rounded-lg font-bold hover:bg-gray-300 transition-all">
                    <i class="fas fa-arrow-right ml-2"></i>
                    رجوع
                </a>
            </div>
        </div>

        <?php if (isset($success_message)): ?>
        <div class="alert bg-green-500 text-white">
            <i class="fas fa-check-circle ml-2"></i>
            <?php echo $success_message; ?>
        </div>
        <?php endif; ?>

        <form method="POST" class="space-y-6">
            <!-- WiFi Settings -->
            <div class="setting-card">
                <h2 class="text-2xl font-bold text-gray-900 mb-4">
                    <i class="fas fa-wifi text-blue-600 ml-2"></i>
                    إعدادات WiFi
                </h2>
                <p class="text-gray-600 mb-6">سيتم استخدام هذه الإعدادات في كود Arduino المُولّد</p>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-network-wired ml-2"></i>
                            اسم شبكة WiFi (SSID)
                        </label>
                        <input type="text" 
                               name="setting_wifi_ssid" 
                               value="<?php echo htmlspecialchars($settings_map['wifi_ssid'] ?? ''); ?>"
                               class="input-field"
                               placeholder="مثال: MyWiFi">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-key ml-2"></i>
                            كلمة مرور WiFi
                        </label>
                        <input type="password" 
                               name="setting_wifi_password" 
                               value="<?php echo htmlspecialchars($settings_map['wifi_password'] ?? ''); ?>"
                               class="input-field"
                               placeholder="••••••••">
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-info-circle ml-1"></i>
                            سيتم تضمينها في الكود المُولّد
                        </p>
                    </div>
                </div>
            </div>

            <!-- Server Settings -->
            <div class="setting-card">
                <h2 class="text-2xl font-bold text-gray-900 mb-4">
                    <i class="fas fa-server text-green-600 ml-2"></i>
                    إعدادات السيرفر
                </h2>
                
                <div class="bg-blue-50 border-r-4 border-blue-500 p-4 rounded-lg mb-4">
                    <h3 class="font-bold text-blue-900 mb-2">
                        <i class="fas fa-info-circle ml-2"></i>
                        كيف تحصل على IP السيرفر؟
                    </h3>
                    <div class="text-sm text-blue-800 space-y-2">
                        <p><strong>Windows:</strong> افتح CMD واكتب <code class="bg-blue-100 px-2 py-1 rounded">ipconfig</code></p>
                        <p><strong>Mac/Linux:</strong> افتح Terminal واكتب <code class="bg-blue-100 px-2 py-1 rounded">ifconfig</code></p>
                        <p><strong>ابحث عن:</strong> IPv4 Address مثل <code class="bg-blue-100 px-2 py-1 rounded">192.168.1.100</code></p>
                        <p class="text-red-700 font-bold">⚠️ لا تستخدم localhost أو 127.0.0.1</p>
                    </div>
                </div>
                
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-link ml-2"></i>
                            عنوان API الكامل
                        </label>
                        <input type="text" 
                               name="setting_server_url" 
                               value="<?php echo htmlspecialchars($settings_map['server_url'] ?? ''); ?>"
                               class="input-field font-mono text-sm"
                               placeholder="http://192.168.1.100/KL/backend/api/esp_control.php">
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-lightbulb ml-1"></i>
                            مثال: http://192.168.1.100/KL/backend/api/esp_control.php
                        </p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-door-open ml-2"></i>
                            منفذ السيرفر (Port)
                        </label>
                        <select name="setting_server_port" class="input-field">
                            <option value="80" <?php echo ($settings_map['server_port'] ?? '80') == '80' ? 'selected' : ''; ?>>80 (HTTP - افتراضي)</option>
                            <option value="443" <?php echo ($settings_map['server_port'] ?? '') == '443' ? 'selected' : ''; ?>>443 (HTTPS - آمن)</option>
                            <option value="8080" <?php echo ($settings_map['server_port'] ?? '') == '8080' ? 'selected' : ''; ?>>8080 (بديل)</option>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">
                            Port 80 للـ HTTP العادي (الأكثر شيوعاً)
                        </p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-clock ml-2"></i>
                            فترة الاستعلام (ميلي ثانية)
                        </label>
                        <input type="number" 
                               name="setting_poll_interval" 
                               value="<?php echo htmlspecialchars($settings_map['poll_interval'] ?? '3000'); ?>"
                               class="input-field"
                               min="1000"
                               max="60000"
                               step="1000">
                        <p class="text-xs text-gray-500 mt-1">
                            كل كم ثانية يتصل الجهاز بالسيرفر؟ (افتراضي: 3000 = 3 ثواني)
                        </p>
                    </div>
                </div>
            </div>

            <!-- Hardware Settings -->
            <div class="setting-card">
                <h2 class="text-2xl font-bold text-gray-900 mb-4">
                    <i class="fas fa-microchip text-purple-600 ml-2"></i>
                    إعدادات الهاردوير
                </h2>
                
                <div class="bg-purple-50 border-r-4 border-purple-500 p-4 rounded-lg mb-4">
                    <h3 class="font-bold text-purple-900 mb-2">
                        <i class="fas fa-map-pin ml-2"></i>
                        دليل Pins السريع
                    </h3>
                    <div class="grid grid-cols-2 gap-2 text-xs text-purple-800">
                        <div><strong>D0</strong> = GPIO16</div>
                        <div><strong>D1</strong> = GPIO5 ⭐ (Relay)</div>
                        <div><strong>D2</strong> = GPIO4</div>
                        <div><strong>D3</strong> = GPIO0</div>
                        <div><strong>D4</strong> = GPIO2 💡 (LED مدمج)</div>
                        <div><strong>D5</strong> = GPIO14</div>
                        <div><strong>D6</strong> = GPIO12</div>
                        <div><strong>D7</strong> = GPIO13</div>
                        <div><strong>D8</strong> = GPIO15</div>
                    </div>
                </div>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-plug ml-2"></i>
                            Relay Pin (GPIO)
                        </label>
                        <select name="setting_relay_pin" class="input-field">
                            <?php
                            $pins = [
                                '5' => 'GPIO5 (D1) - موصى به',
                                '4' => 'GPIO4 (D2)',
                                '14' => 'GPIO14 (D5)',
                                '12' => 'GPIO12 (D6)',
                                '13' => 'GPIO13 (D7)',
                                '15' => 'GPIO15 (D8)'
                            ];
                            foreach ($pins as $value => $label) {
                                $selected = ($settings_map['relay_pin'] ?? '5') == $value ? 'selected' : '';
                                echo "<option value='$value' $selected>$label</option>";
                            }
                            ?>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-info-circle ml-1"></i>
                            Pin للتحكم في الريلاي أو الجهاز الخارجي
                        </p>
                    </div>
                    
                    <div>
                        <label class="block text-sm font-bold text-gray-700 mb-2">
                            <i class="fas fa-lightbulb ml-2"></i>
                            LED الاختبار (Built-in)
                        </label>
                        <select name="setting_test_led_pin" class="input-field">
                            <option value="2" <?php echo ($settings_map['test_led_pin'] ?? '2') == '2' ? 'selected' : ''; ?>>GPIO2 (D4) - LED مدمج ⭐</option>
                            <option value="16" <?php echo ($settings_map['test_led_pin'] ?? '') == '16' ? 'selected' : ''; ?>>GPIO16 (D0)</option>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">
                            <i class="fas fa-info-circle ml-1"></i>
                            LED للإشارة البصرية (يومض عند الاتصال)
                        </p>
                    </div>
                </div>
                
                <div class="mt-4">
                    <label class="block text-sm font-bold text-gray-700 mb-2">
                        <i class="fas fa-terminal ml-2"></i>
                        Serial Monitor Baud Rate
                    </label>
                    <select name="setting_serial_baud" class="input-field">
                        <option value="9600" <?php echo ($settings_map['serial_baud'] ?? '') == '9600' ? 'selected' : ''; ?>>9600</option>
                        <option value="115200" <?php echo ($settings_map['serial_baud'] ?? '115200') == '115200' ? 'selected' : ''; ?>>115200 (موصى به)</option>
                    </select>
                    <p class="text-xs text-gray-500 mt-1">
                        استخدم نفس القيمة في Arduino IDE Serial Monitor
                    </p>
                </div>
            </div>

            <!-- Save Button -->
            <div class="text-center">
                <button type="submit" class="btn-save">
                    <i class="fas fa-save ml-2"></i>
                    حفظ الإعدادات
                </button>
            </div>
        </form>

        <!-- Info Box -->
        <div class="bg-blue-50 border-r-4 border-blue-500 rounded-lg p-6 mt-6">
            <h3 class="text-lg font-bold text-blue-900 mb-2">
                <i class="fas fa-info-circle ml-2"></i>
                ملاحظات مهمة
            </h3>
            <ul class="list-disc list-inside space-y-2 text-blue-800">
                <li>سيتم استخدام هذه الإعدادات تلقائياً عند نسخ كود Arduino</li>
                <li>تأكد من استخدام IP السيرفر الصحيح (ليس localhost)</li>
                <li>يمكنك تغيير الإعدادات في أي وقت</li>
                <li>الإعدادات تُطبق على جميع الأجهزة الجديدة</li>
                <li><strong>Port 80:</strong> للـ HTTP العادي (لا يحتاج تشفير)</li>
                <li><strong>LED الاختبار:</strong> سيومض أثناء الاتصال بـ WiFi ويضيء عند نجاح الاتصال</li>
            </ul>
        </div>
    </div>
</body>
</html>
