<?php
/**
 * IoT Devices Management Dashboard
 * Complete control panel rebuilt from scratch
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        die('<div style="padding:20px;background:#ef4444;color:white;font-family:Arial;">
            ❌ فشل الاتصال بقاعدة البيانات<br>
            <a href="../database/run_iot_setup.php" style="color:white;text-decoration:underline;">
            اضغط هنا لإنشاء الجداول
            </a>
            </div>');
    }
    
    // Check if tables exist
    $check_table = $db->query("SHOW TABLES LIKE 'iot_devices'");
    if ($check_table->rowCount() == 0) {
        die('<div style="padding:20px;background:#f59e0b;color:white;font-family:Arial;text-align:center;">
            ⚠️ جداول IoT غير موجودة في قاعدة البيانات<br><br>
            <a href="../database/run_iot_setup.php" 
               style="display:inline-block;background:white;color:#f59e0b;padding:15px 30px;
                      text-decoration:none;border-radius:8px;font-weight:bold;margin-top:10px;">
            🚀 إنشاء الجداول الآن
            </a>
            </div>');
    }

    // Fetch statistics
    $stats_query = "SELECT 
        COUNT(*) as total_devices,
        SUM(CASE WHEN is_online = 1 THEN 1 ELSE 0 END) as online_devices,
        SUM(CASE WHEN is_online = 0 THEN 1 ELSE 0 END) as offline_devices,
        SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_devices
        FROM iot_devices";
    $stats = $db->query($stats_query)->fetch(PDO::FETCH_ASSOC);

    $commands_query = "SELECT 
        COUNT(*) as pending_commands,
        SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_commands
        FROM iot_commands WHERE DATE(created_at) = CURDATE()";
    $cmd_stats = $db->query($commands_query)->fetch(PDO::FETCH_ASSOC);

    // Fetch all devices
    $devices_query = "SELECT d.*, 
        (SELECT COUNT(*) FROM iot_commands WHERE device_id = d.device_id AND status = 'pending') as pending_commands
        FROM iot_devices d ORDER BY d.is_online DESC, d.last_seen DESC";
        
} catch (Exception $e) {
    die('<div style="padding:20px;background:#ef4444;color:white;font-family:Arial;">
        ❌ خطأ: ' . htmlspecialchars($e->getMessage()) . '<br><br>
        <a href="../database/run_iot_setup.php" style="color:white;text-decoration:underline;">
        اضغط هنا لإنشاء الجداول
        </a>
        </div>');
}
$devices = $db->query($devices_query)->fetchAll(PDO::FETCH_ASSOC);

// Fetch recent commands
$recent_commands_query = "SELECT c.*, d.device_name 
    FROM iot_commands c
    LEFT JOIN iot_devices d ON c.device_id = d.device_id
    ORDER BY c.created_at DESC LIMIT 30";
$recent_commands = $db->query($recent_commands_query)->fetchAll(PDO::FETCH_ASSOC);

// Fetch recent logs
$recent_logs_query = "SELECT l.*, d.device_name 
    FROM iot_logs l
    LEFT JOIN iot_devices d ON l.device_id = d.device_id
    WHERE l.log_type IN ('error', 'warning')
    ORDER BY l.created_at DESC LIMIT 10";
$recent_logs = $db->query($recent_logs_query)->fetchAll(PDO::FETCH_ASSOC);

// Fetch IoT settings
$settings_map = [];
try {
    $settings_query = $db->query("SELECT setting_key, setting_value FROM iot_settings");
    while ($row = $settings_query->fetch(PDO::FETCH_ASSOC)) {
        $settings_map[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    // Settings table doesn't exist yet
    $settings_map = [
        'wifi_ssid' => 'YOUR_WIFI_SSID',
        'wifi_password' => 'YOUR_WIFI_PASSWORD',
        'server_url' => 'http://YOUR_SERVER_IP/KL/backend/api/esp_control.php',
        'server_port' => '80',
        'poll_interval' => '3000',
        'relay_pin' => '5',
        'test_led_pin' => '2',
        'serial_baud' => '115200'
    ];
}
?>
<!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; }
        
        .status-online {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            animation: pulse-green 2s infinite;
        }
        
        .status-offline {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }
        
        @keyframes pulse-green {
            0%, 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); }
            50% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); }
        }
        
        .device-card {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .device-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
        }
        
        .device-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #667eea, #764ba2);
        }
        
        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
        }
        
        .modal {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0,0,0,0.6);
            backdrop-filter: blur(5px);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal.active { display: flex; }
        
        .modal-content {
            background: white;
            border-radius: 20px;
            max-width: 600px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
            animation: slideUp 0.3s ease;
        }
        
        @keyframes slideUp {
            from { opacity: 0; transform: translateY(50px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            cursor: pointer;
            border: none;
        }
        
        .btn:hover { transform: scale(1.05); }
        
        .btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
        .btn-success { background: linear-gradient(135deg, #10b981, #059669); color: white; }
        .btn-danger { background: linear-gradient(135deg, #ef4444, #dc2626); color: white; }
        .btn-warning { background: linear-gradient(135deg, #f59e0b, #d97706); color: white; }
        .btn-info { background: linear-gradient(135deg, #3b82f6, #2563eb); color: white; }
        
        .badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-sent { background: #dbeafe; color: #1e40af; }
        .badge-executed { background: #d1fae5; color: #065f46; }
        .badge-failed { background: #fee2e2; color: #991b1b; }
        .badge-cancelled { background: #f3f4f6; color: #374151; }
        
        .tab-button {
            padding: 12px 24px;
            border: none;
            background: transparent;
            color: #6b7280;
            font-weight: 600;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }
        
        .tab-button.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }
        
        .tab-content { display: none; }
        .tab-content.active { display: block; }
    </style>
</head>
<body class="p-4 md:p-8">
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="bg-white rounded-2xl shadow-xl p-6 mb-6">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h1 class="text-3xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-microchip text-purple-600 ml-2"></i>
                        إدارة أجهزة IoT
                    </h1>
                    <p class="text-gray-600">التحكم الكامل في أجهزة ESP8266/ESP32 وإنترنت الأشياء</p>
                </div>
                <div class="flex gap-3">
                    <button onclick="location.href='iot_settings.php'" class="btn bg-gradient-to-r from-teal-500 to-teal-600 text-white" title="الإعدادات">
                        <i class="fas fa-cog ml-2"></i>
                        <span class="hidden md:inline">إعدادات</span>
                    </button>
                    <button onclick="location.reload()" class="btn btn-info" title="تحديث">
                        <i class="fas fa-sync-alt ml-2"></i>
                        <span class="hidden md:inline">تحديث</span>
                    </button>
                    <button onclick="openModal('addDeviceModal')" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة جهاز
                    </button>
                </div>
            </div>
        </div>

        <!-- Statistics -->
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600 mb-1">إجمالي الأجهزة</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo $stats['total_devices']; ?></p>
                    </div>
                    <div class="bg-purple-100 p-4 rounded-xl">
                        <i class="fas fa-microchip text-purple-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600 mb-1">أجهزة متصلة</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $stats['online_devices']; ?></p>
                    </div>
                    <div class="bg-green-100 p-4 rounded-xl">
                        <i class="fas fa-wifi text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600 mb-1">أجهزة غير متصلة</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $stats['offline_devices']; ?></p>
                    </div>
                    <div class="bg-red-100 p-4 rounded-xl">
                        <i class="fas fa-exclamation-triangle text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="stat-card">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600 mb-1">أوامر اليوم</p>
                        <p class="text-3xl font-bold text-orange-600"><?php echo $cmd_stats['pending_commands']; ?></p>
                    </div>
                    <div class="bg-orange-100 p-4 rounded-xl">
                        <i class="fas fa-clock text-orange-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="bg-white rounded-2xl shadow-xl overflow-hidden">
            <div class="border-b border-gray-200 px-6">
                <div class="flex gap-2 overflow-x-auto">
                    <button class="tab-button active" onclick="switchTab('devices')">
                        <i class="fas fa-list ml-2"></i>الأجهزة
                    </button>
                    <button class="tab-button" onclick="switchTab('commands')">
                        <i class="fas fa-terminal ml-2"></i>الأوامر
                    </button>
                    <button class="tab-button" onclick="switchTab('logs')">
                        <i class="fas fa-file-alt ml-2"></i>السجلات
                    </button>
                    <button class="tab-button" onclick="switchTab('guide')">
                        <i class="fas fa-book ml-2"></i>دليل ESP8266
                    </button>
                </div>
            </div>

            <!-- Devices Tab -->
            <div id="devices-tab" class="tab-content active p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <?php foreach ($devices as $device): ?>
                        <?php
                        $pin_config = json_decode($device['pin_config'], true);
                        $is_online = $device['is_online'];
                        $last_seen = $device['last_seen'];
                        $time_diff = $last_seen ? time() - strtotime($last_seen) : null;
                        ?>
                        <div class="device-card bg-white rounded-xl border-2 border-gray-200 p-6">
                            <div class="flex items-start justify-between mb-4">
                                <div class="flex-1">
                                    <h3 class="text-lg font-bold text-gray-900 mb-1"><?php echo htmlspecialchars($device['device_name']); ?></h3>
                                    <p class="text-sm text-gray-500 font-mono"><?php echo htmlspecialchars($device['device_id']); ?></p>
                                </div>
                                <span class="px-3 py-1 rounded-full text-white text-xs font-bold <?php echo $is_online ? 'status-online' : 'status-offline'; ?>">
                                    <?php echo $is_online ? '● متصل' : '○ غير متصل'; ?>
                                </span>
                            </div>

                            <div class="space-y-2 mb-4 text-sm">
                                <div class="flex items-center text-gray-600">
                                    <i class="fas fa-map-marker-alt w-5 text-blue-500"></i>
                                    <span><?php echo $device['location'] ?: 'غير محدد'; ?></span>
                                </div>
                                <div class="flex items-center text-gray-600">
                                    <i class="fas fa-microchip w-5 text-purple-500"></i>
                                    <span><?php echo strtoupper($device['device_type']); ?></span>
                                </div>
                                <?php if ($device['ip_address']): ?>
                                <div class="flex items-center text-gray-600">
                                    <i class="fas fa-network-wired w-5 text-teal-500"></i>
                                    <span class="font-mono text-xs"><?php echo $device['ip_address']; ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if ($last_seen): ?>
                                <div class="flex items-center text-gray-600">
                                    <i class="fas fa-clock w-5 text-green-500"></i>
                                    <span>
                                        <?php 
                                        if ($time_diff < 60) echo 'الآن';
                                        elseif ($time_diff < 3600) echo floor($time_diff / 60) . ' دقيقة';
                                        elseif ($time_diff < 86400) echo floor($time_diff / 3600) . ' ساعة';
                                        else echo date('Y-m-d H:i', strtotime($last_seen));
                                        ?>
                                    </span>
                                </div>
                                <?php endif; ?>
                                <?php if ($device['pending_commands'] > 0): ?>
                                <div class="flex items-center text-orange-600 font-bold">
                                    <i class="fas fa-exclamation-circle w-5"></i>
                                    <span><?php echo $device['pending_commands']; ?> أمر معلق</span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <div class="grid grid-cols-3 gap-2 mb-3">
                                <button onclick="sendQuickCommand('<?php echo $device['device_id']; ?>', 'turn_on')" 
                                        class="btn btn-success text-sm py-2" title="تشغيل">
                                    <i class="fas fa-power-off"></i>
                                </button>
                                <button onclick="sendQuickCommand('<?php echo $device['device_id']; ?>', 'turn_off')" 
                                        class="btn btn-danger text-sm py-2" title="إيقاف">
                                    <i class="fas fa-stop"></i>
                                </button>
                                <button onclick="sendQuickCommand('<?php echo $device['device_id']; ?>', 'toggle')" 
                                        class="btn btn-warning text-sm py-2" title="تبديل">
                                    <i class="fas fa-exchange-alt"></i>
                                </button>
                            </div>
                            
                            <div class="grid grid-cols-5 gap-2">
                                <button onclick="location.href='manage_pins.php?device_id=<?php echo $device['device_id']; ?>'" 
                                        class="btn bg-gradient-to-r from-teal-500 to-teal-600 text-white text-sm py-2" title="إدارة Pins">
                                    <i class="fas fa-sliders-h"></i>
                                </button>
                                <button onclick="copyArduinoCode('<?php echo $device['device_id']; ?>')" 
                                        class="btn btn-primary text-sm py-2" title="نسخ كود Arduino">
                                    <i class="fas fa-code"></i>
                                </button>
                                <button onclick="openCustomCommand('<?php echo $device['device_id']; ?>')" 
                                        class="btn btn-info text-sm py-2" title="أمر مخصص">
                                    <i class="fas fa-terminal"></i>
                                </button>
                                <button onclick="editDevice(<?php echo htmlspecialchars(json_encode($device)); ?>)" 
                                        class="btn btn-info text-sm py-2" title="تعديل">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteDevice('<?php echo $device['device_id']; ?>', '<?php echo htmlspecialchars($device['device_name']); ?>')" 
                                        class="btn btn-danger text-sm py-2" title="حذف">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <?php if (empty($devices)): ?>
                    <div class="text-center py-16">
                        <i class="fas fa-microchip text-gray-300 text-6xl mb-4"></i>
                        <p class="text-gray-500 text-lg mb-4">لا توجد أجهزة مسجلة</p>
                        <button onclick="openModal('addDeviceModal')" class="btn btn-primary">
                            <i class="fas fa-plus ml-2"></i>
                            إضافة جهاز الآن
                        </button>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Commands Tab -->
            <div id="commands-tab" class="tab-content p-6">
                <div class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">الجهاز</th>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">الأمر</th>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">الأولوية</th>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">الحالة</th>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">وقت الإنشاء</th>
                                <th class="px-6 py-3 text-right text-xs font-bold text-gray-700 uppercase">التنفيذ</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($recent_commands as $cmd): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 text-sm text-gray-900">
                                        <?php echo htmlspecialchars($cmd['device_name'] ?: $cmd['device_id']); ?>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="px-3 py-1 bg-purple-100 text-purple-800 rounded-full text-xs font-bold">
                                            <?php echo htmlspecialchars($cmd['action']); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm">
                                        <span class="font-bold text-gray-700"><?php echo $cmd['priority']; ?></span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <?php
                                        $status_map = [
                                            'pending' => ['معلق', 'badge-pending'],
                                            'sent' => ['تم الإرسال', 'badge-sent'],
                                            'executed' => ['تم التنفيذ', 'badge-executed'],
                                            'failed' => ['فشل', 'badge-failed'],
                                            'cancelled' => ['ملغي', 'badge-cancelled']
                                        ];
                                        $status_info = $status_map[$cmd['status']] ?? [$cmd['status'], 'badge-pending'];
                                        ?>
                                        <span class="badge <?php echo $status_info[1]; ?>">
                                            <?php echo $status_info[0]; ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500">
                                        <?php echo date('Y-m-d H:i:s', strtotime($cmd['created_at'])); ?>
                                    </td>
                                    <td class="px-6 py-4 text-sm text-gray-500">
                                        <?php echo $cmd['executed_at'] ? date('H:i:s', strtotime($cmd['executed_at'])) : '-'; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>

                    <?php if (empty($recent_commands)): ?>
                        <div class="text-center py-12">
                            <i class="fas fa-inbox text-gray-300 text-5xl mb-3"></i>
                            <p class="text-gray-500">لا توجد أوامر في السجل</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Logs Tab -->
            <div id="logs-tab" class="tab-content p-6">
                <div class="space-y-3">
                    <?php foreach ($recent_logs as $log): ?>
                        <div class="bg-gray-50 rounded-lg p-4 border-r-4 <?php echo $log['log_type'] === 'error' ? 'border-red-500' : 'border-yellow-500'; ?>">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-2">
                                        <span class="font-bold text-gray-900"><?php echo htmlspecialchars($log['device_name']); ?></span>
                                        <span class="badge <?php echo $log['log_type'] === 'error' ? 'badge-failed' : 'badge-pending'; ?>">
                                            <?php echo $log['log_type'] === 'error' ? 'خطأ' : 'تحذير'; ?>
                                        </span>
                                    </div>
                                    <p class="text-sm text-gray-700"><?php echo htmlspecialchars($log['message']); ?></p>
                                </div>
                                <span class="text-xs text-gray-500">
                                    <?php echo date('H:i:s', strtotime($log['created_at'])); ?>
                                </span>
                            </div>
                        </div>
                    <?php endforeach; ?>

                    <?php if (empty($recent_logs)): ?>
                        <div class="text-center py-12">
                            <i class="fas fa-check-circle text-green-300 text-5xl mb-3"></i>
                            <p class="text-gray-500">لا توجد أخطاء أو تحذيرات</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Guide Tab -->
            <div id="guide-tab" class="tab-content p-6">
                <div class="prose max-w-none">
                    <h2 class="text-2xl font-bold text-gray-900 mb-4">
                        <i class="fas fa-book text-purple-600 ml-2"></i>
                        دليل استخدام ESP8266
                    </h2>
                    
                    <div class="bg-gradient-to-r from-teal-50 to-blue-50 border-r-4 border-teal-500 p-6 rounded-lg mb-6">
                        <div class="flex items-center justify-between mb-3">
                            <h3 class="text-lg font-bold text-teal-900">⚡ طريقة سريعة (مع الإعدادات)</h3>
                            <button onclick="location.href='iot_settings.php'" class="bg-teal-600 text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-teal-700">
                                <i class="fas fa-cog ml-1"></i> إعدادات WiFi
                            </button>
                        </div>
                        <ol class="list-decimal list-inside space-y-2 text-gray-700">
                            <li><strong>اذهب للإعدادات</strong> واحفظ معلومات WiFi والسيرفر</li>
                            <li>أضف جهاز جديد</li>
                            <li>انسخ الكود (سيكون جاهز للرفع مباشرة!)</li>
                            <li>افتح Arduino IDE والصق الكود</li>
                            <li>حمّل على ESP8266 مباشرة ✨</li>
                        </ol>
                    </div>
                    
                    <div class="bg-blue-50 border-r-4 border-blue-500 p-6 rounded-lg mb-6">
                        <h3 class="text-lg font-bold text-blue-900 mb-2">📝 الطريقة العادية</h3>
                        <ol class="list-decimal list-inside space-y-2 text-gray-700">
                            <li>قم بإضافة جهاز جديد من خلال زر "إضافة جهاز"</li>
                            <li>انسخ كود Arduino من خلال زر "نسخ الكود"</li>
                            <li>افتح Arduino IDE والصق الكود</li>
                            <li>عدّل معلومات WiFi (SSID و Password)</li>
                            <li>عدّل عنوان السيرفر (Server URL)</li>
                            <li>حمّل الكود على ESP8266</li>
                            <li>راقب الجهاز من لوحة التحكم</li>
                        </ol>
                    </div>

                    <div class="bg-green-50 border-r-4 border-green-500 p-6 rounded-lg mb-6">
                        <h3 class="text-lg font-bold text-green-900 mb-2">✅ المكتبات المطلوبة</h3>
                        <ul class="list-disc list-inside space-y-1 text-gray-700">
                            <li><strong>ESP8266WiFi</strong> - مدمجة مع ESP8266 Board ✅</li>
                            <li><strong>ESP8266HTTPClient</strong> - مدمجة مع ESP8266 Board ✅</li>
                        </ul>
                        <div class="bg-blue-100 border border-blue-300 rounded p-3 mt-3">
                            <p class="text-sm text-blue-900">
                                <strong>🎉 لا يحتاج مكتبات خارجية!</strong><br>
                                الكود المُولّد يستخدم نسخة مبسطة بدون ArduinoJson
                            </p>
                        </div>
                    </div>

                    <div class="bg-purple-50 border-r-4 border-purple-500 p-6 rounded-lg">
                        <h3 class="text-lg font-bold text-purple-900 mb-2">الأوامر المتاحة</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                            <div>
                                <strong>turn_on</strong> - تشغيل الريلاي
                            </div>
                            <div>
                                <strong>turn_off</strong> - إيقاف الريلاي
                            </div>
                            <div>
                                <strong>toggle</strong> - تبديل الحالة
                            </div>
                            <div>
                                <strong>pulse</strong> - نبضة بمدة محددة
                            </div>
                            <div>
                                <strong>get_status</strong> - قراءة الحالة
                            </div>
                            <div>
                                <strong>custom</strong> - أوامر مخصصة
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Device Modal -->
    <div id="addDeviceModal" class="modal">
        <div class="modal-content p-8">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-2xl font-bold text-gray-900">إضافة جهاز جديد</h3>
                <button onclick="closeModal('addDeviceModal')" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            <form id="addDeviceForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">معرف الجهاز (Device ID) *</label>
                    <input type="text" name="device_id" required 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none"
                           placeholder="ESP01">
                    <p class="text-xs text-gray-500 mt-1">يجب أن يكون فريداً ولا يحتوي على مسافات</p>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم الجهاز *</label>
                    <input type="text" name="device_name" required 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none"
                           placeholder="Living Room Light">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">نوع الجهاز</label>
                    <select name="device_type" 
                            class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                        <option value="esp8266">ESP8266</option>
                        <option value="esp32">ESP32</option>
                        <option value="arduino">Arduino</option>
                        <option value="raspberry_pi">Raspberry Pi</option>
                        <option value="other">أخرى</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الموقع</label>
                    <input type="text" name="location" 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none"
                           placeholder="Living Room">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الوصف</label>
                    <textarea name="description" rows="3" 
                              class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none"
                              placeholder="وصف مختصر للجهاز"></textarea>
                </div>
                <div class="flex gap-3 pt-4">
                    <button type="submit" class="flex-1 btn btn-primary py-3">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة الجهاز
                    </button>
                    <button type="button" onclick="closeModal('addDeviceModal')" 
                            class="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-bold hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Edit Device Modal -->
    <div id="editDeviceModal" class="modal">
        <div class="modal-content p-8">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-2xl font-bold text-gray-900">تعديل الجهاز</h3>
                <button onclick="closeModal('editDeviceModal')" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            <form id="editDeviceForm" class="space-y-4">
                <input type="hidden" id="edit_device_id" name="device_id">
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم الجهاز</label>
                    <input type="text" id="edit_device_name" name="device_name" required 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">نوع الجهاز</label>
                    <select id="edit_device_type" name="device_type" 
                            class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                        <option value="esp8266">ESP8266</option>
                        <option value="esp32">ESP32</option>
                        <option value="arduino">Arduino</option>
                        <option value="raspberry_pi">Raspberry Pi</option>
                        <option value="other">أخرى</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الموقع</label>
                    <input type="text" id="edit_location" name="location" 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الوصف</label>
                    <textarea id="edit_description" name="description" rows="3" 
                              class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none"></textarea>
                </div>
                <div class="flex gap-3 pt-4">
                    <button type="submit" class="flex-1 btn btn-info py-3">
                        <i class="fas fa-save ml-2"></i>
                        حفظ التغييرات
                    </button>
                    <button type="button" onclick="closeModal('editDeviceModal')" 
                            class="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-bold hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Custom Command Modal -->
    <div id="customCommandModal" class="modal">
        <div class="modal-content p-8">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-2xl font-bold text-gray-900">إرسال أمر مخصص</h3>
                <button onclick="closeModal('customCommandModal')" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            <form id="customCommandForm" class="space-y-4">
                <input type="hidden" id="custom_device_id">
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">نوع الأمر</label>
                    <select id="custom_action" 
                            class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                        <option value="pulse">نبضة (Pulse)</option>
                        <option value="get_status">قراءة الحالة</option>
                        <option value="blink">وميض (Blink)</option>
                        <option value="custom">أمر مخصص</option>
                    </select>
                </div>
                <div id="pulseOptions" class="hidden">
                    <label class="block text-sm font-bold text-gray-700 mb-2">مدة النبضة (ميلي ثانية)</label>
                    <input type="number" id="pulse_duration" value="1000" min="100" max="10000" step="100" 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                </div>
                <div id="customActionInput" class="hidden">
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم الأمر</label>
                    <input type="text" id="custom_action_name" placeholder="مثال: read_sensor" 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                </div>
                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الأولوية (1-10)</label>
                    <input type="number" id="custom_priority" value="5" min="1" max="10" 
                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:border-purple-500 focus:outline-none">
                </div>
                <div class="flex gap-3 pt-4">
                    <button type="submit" class="flex-1 btn btn-info py-3">
                        <i class="fas fa-paper-plane ml-2"></i>
                        إرسال الأمر
                    </button>
                    <button type="button" onclick="closeModal('customCommandModal')" 
                            class="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-bold hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    // IoT Settings from PHP
    const iotSettings = {
        wifiSsid: <?php echo json_encode($settings_map['wifi_ssid'] ?? 'YOUR_WIFI_SSID'); ?>,
        wifiPassword: <?php echo json_encode($settings_map['wifi_password'] ?? 'YOUR_WIFI_PASSWORD'); ?>,
        serverUrl: <?php echo json_encode($settings_map['server_url'] ?? 'http://YOUR_SERVER_IP/KL/backend/api/esp_control.php'); ?>,
        serverPort: <?php echo json_encode($settings_map['server_port'] ?? '80'); ?>,
        pollInterval: <?php echo json_encode($settings_map['poll_interval'] ?? '3000'); ?>,
        relayPin: <?php echo json_encode($settings_map['relay_pin'] ?? '5'); ?>,
        testLedPin: <?php echo json_encode($settings_map['test_led_pin'] ?? '2'); ?>,
        serialBaud: <?php echo json_encode($settings_map['serial_baud'] ?? '115200'); ?>
    };
    
    // Modal Management
    function openModal(modalId) {
        document.getElementById(modalId).classList.add('active');
    }
    
    function closeModal(modalId) {
        document.getElementById(modalId).classList.remove('active');
    }
    
    // Tab Management
    function switchTab(tabName) {
        // Hide all tabs
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('active');
        });
        
        // Show selected tab
        document.getElementById(tabName + '-tab').classList.add('active');
        event.target.classList.add('active');
    }
    
    // Custom Command Action Change
    document.getElementById('custom_action').addEventListener('change', function() {
        const pulseOptions = document.getElementById('pulseOptions');
        const customInput = document.getElementById('customActionInput');
        
        if (this.value === 'pulse') {
            pulseOptions.classList.remove('hidden');
            customInput.classList.add('hidden');
        } else if (this.value === 'custom') {
            pulseOptions.classList.add('hidden');
            customInput.classList.remove('hidden');
        } else {
            pulseOptions.classList.add('hidden');
            customInput.classList.add('hidden');
        }
    });
    
    // Add Device Form
    document.getElementById('addDeviceForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        formData.append('pin_config', JSON.stringify({relay_pin: 5, led_pin: 2}));
        
        try {
            const response = await fetch('../api/iot/devices.php', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            
            if (result.success) {
                alert('✅ تم إضافة الجهاز بنجاح!');
                location.reload();
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    });
    
    // Edit Device
    function editDevice(device) {
        document.getElementById('edit_device_id').value = device.device_id;
        document.getElementById('edit_device_name').value = device.device_name;
        document.getElementById('edit_device_type').value = device.device_type;
        document.getElementById('edit_location').value = device.location || '';
        document.getElementById('edit_description').value = device.description || '';
        openModal('editDeviceModal');
    }
    
    // Edit Device Form
    document.getElementById('editDeviceForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);
        
        try {
            const response = await fetch('../api/iot/devices.php', {
                method: 'PUT',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams(data)
            });
            const result = await response.json();
            
            if (result.success) {
                alert('✅ تم تحديث الجهاز بنجاح!');
                location.reload();
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    });
    
    // Delete Device
    async function deleteDevice(deviceId, deviceName) {
        if (!confirm(`هل أنت متأكد من حذف الجهاز "${deviceName}"?\n\nسيتم حذف جميع الأوامر والسجلات المرتبطة به.`)) {
            return;
        }
        
        try {
            const response = await fetch('../api/iot/devices.php', {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `device_id=${deviceId}`
            });
            const result = await response.json();
            
            if (result.success) {
                alert('✅ تم حذف الجهاز بنجاح!');
                location.reload();
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    }
    
    // Send Quick Command
    async function sendQuickCommand(deviceId, action) {
        try {
            const formData = new FormData();
            formData.append('device_id', deviceId);
            formData.append('action', action);
            
            const response = await fetch('../api/iot/commands.php', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            
            if (result.success) {
                // Show success notification
                const notification = document.createElement('div');
                notification.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
                notification.innerHTML = `<i class="fas fa-check-circle ml-2"></i>تم إرسال الأمر بنجاح`;
                document.body.appendChild(notification);
                setTimeout(() => notification.remove(), 3000);
                
                // Reload after 1 second
                setTimeout(() => location.reload(), 1000);
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    }
    
    // Open Custom Command Modal
    function openCustomCommand(deviceId) {
        document.getElementById('custom_device_id').value = deviceId;
        openModal('customCommandModal');
    }
    
    // Custom Command Form
    document.getElementById('customCommandForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const deviceId = document.getElementById('custom_device_id').value;
        let action = document.getElementById('custom_action').value;
        const priority = document.getElementById('custom_priority').value;
        let payload = null;
        
        if (action === 'pulse') {
            const duration = document.getElementById('pulse_duration').value;
            payload = JSON.stringify({duration: parseInt(duration)});
        } else if (action === 'custom') {
            action = document.getElementById('custom_action_name').value;
            if (!action) {
                alert('⚠️ يرجى إدخال اسم الأمر');
                return;
            }
        }
        
        try {
            const formData = new FormData();
            formData.append('device_id', deviceId);
            formData.append('action', action);
            formData.append('priority', priority);
            if (payload) formData.append('payload', payload);
            
            const response = await fetch('../api/iot/commands.php', {
                method: 'POST',
                body: formData
            });
            const result = await response.json();
            
            if (result.success) {
                alert('✅ تم إرسال الأمر بنجاح!');
                closeModal('customCommandModal');
                setTimeout(() => location.reload(), 1000);
            } else {
                alert('❌ خطأ: ' + (result.error || 'Unknown error'));
            }
        } catch (error) {
            alert('❌ خطأ في الاتصال: ' + error.message);
        }
    });
    
    // Copy Arduino Code
    function copyArduinoCode(deviceId) {
        const code = `/*
 * ESP8266 IoT Control Code - Simplified Version
 * Device ID: ${deviceId}
 * Generated by IoT Dashboard
 * Auto-configured with saved settings ✨
 * 
 * NO EXTERNAL LIBRARIES REQUIRED!
 * READY TO UPLOAD! Just select your board and port in Arduino IDE
 */

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

// ============================================
// WiFi Configuration (Auto-filled)
// ============================================
const char* ssid = "${iotSettings.wifiSsid}";
const char* password = "${iotSettings.wifiPassword}";

// ============================================
// Server Configuration (Auto-filled)
// ============================================
const char* serverUrl = "${iotSettings.serverUrl}";
const int serverPort = ${iotSettings.serverPort};
const char* deviceId = "${deviceId}";

// ============================================
// Pin Configuration (Auto-filled)
// ============================================
const int RELAY_PIN = ${iotSettings.relayPin};        // GPIO${iotSettings.relayPin} - Main control pin
const int TEST_LED_PIN = ${iotSettings.testLedPin};   // GPIO${iotSettings.testLedPin} - Built-in LED for status

// ============================================
// Polling Configuration (Auto-filled)
// ============================================
const unsigned long POLL_INTERVAL = ${iotSettings.pollInterval};  // milliseconds

// ============================================
// Serial Monitor Configuration
// ============================================
const unsigned long SERIAL_BAUD = ${iotSettings.serialBaud};  // Set same in Arduino IDE Serial Monitor
unsigned long lastPollTime = 0;

// State Variables
bool relayState = false;
int currentCommandId = 0;

void setup() {
  // Initialize Serial Monitor
  Serial.begin(SERIAL_BAUD);
  delay(100);
  Serial.println();
  Serial.println("========================================");
  Serial.println("  ESP8266 IoT Control System");
  Serial.println("  Device ID: ${deviceId}");
  Serial.println("========================================");
  
  // Initialize Pins
  pinMode(RELAY_PIN, OUTPUT);
  pinMode(TEST_LED_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  digitalWrite(TEST_LED_PIN, HIGH);  // LED OFF (inverted logic)
  
  Serial.print("Relay Pin: GPIO");
  Serial.println(RELAY_PIN);
  Serial.print("Test LED Pin: GPIO");
  Serial.println(TEST_LED_PIN);
  
  // Connect to WiFi
  connectToWiFi();
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    connectToWiFi();
  }
  
  if (millis() - lastPollTime >= POLL_INTERVAL) {
    lastPollTime = millis();
    checkForCommands();
  }
  
  delay(100);
}

void connectToWiFi() {
  Serial.println();
  Serial.println("----------------------------------------");
  Serial.print("Connecting to WiFi: ");
  Serial.println(ssid);
  Serial.println("----------------------------------------");
  
  WiFi.begin(ssid, password);
  
  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 30) {
    delay(500);
    Serial.print(".");
    // Blink test LED while connecting
    digitalWrite(TEST_LED_PIN, !digitalRead(TEST_LED_PIN));
    attempts++;
  }
  
  Serial.println();
  
  if (WiFi.status() == WL_CONNECTED) {
    // Turn ON test LED (inverted logic: LOW = ON)
    digitalWrite(TEST_LED_PIN, LOW);
    Serial.println("✓ WiFi Connected!");
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());
    Serial.print("Server: ");
    Serial.println(serverUrl);
    Serial.println("----------------------------------------");
    Serial.println("System Ready! Waiting for commands...");
    Serial.println("========================================");
  } else {
    Serial.println("✗ WiFi Connection Failed!");
    Serial.println("Check SSID and Password");
    // Blink test LED rapidly to indicate error
    for(int i=0; i<10; i++) {
      digitalWrite(TEST_LED_PIN, !digitalRead(TEST_LED_PIN));
      delay(100);
    }
  }
}

void checkForCommands() {
  if (WiFi.status() != WL_CONNECTED) return;
  
  WiFiClient client;
  HTTPClient http;
  
  String url = String(serverUrl) + "?device_id=" + deviceId;
  http.begin(client, url);
  
  int httpCode = http.GET();
  
  if (httpCode == HTTP_CODE_OK) {
    String payload = http.getString();
    
    // Simple parsing without ArduinoJson
    if (payload.indexOf("\\"action\\":\\"turn_on\\"") > 0) {
      Serial.println("Command: turn_on");
      executeCommand("turn_on");
    } else if (payload.indexOf("\\"action\\":\\"turn_off\\"") > 0) {
      Serial.println("Command: turn_off");
      executeCommand("turn_off");
    } else if (payload.indexOf("\\"action\\":\\"toggle\\"") > 0) {
      Serial.println("Command: toggle");
      executeCommand("toggle");
    } else if (payload.indexOf("\\"action\\":\\"test_led\\"") > 0) {
      Serial.println("Command: test_led");
      executeCommand("test_led");
    } else if (payload.indexOf("\\"action\\":\\"pulse\\"") > 0) {
      Serial.println("Command: pulse");
      executeCommand("pulse");
    }
  }
  
  http.end();
}

void executeCommand(String action) {
  Serial.print("Executing: ");
  Serial.println(action);
  
  if (action == "turn_on") {
    digitalWrite(RELAY_PIN, HIGH);
    relayState = true;
    Serial.println("✓ Relay ON");
    
  } else if (action == "turn_off") {
    digitalWrite(RELAY_PIN, LOW);
    relayState = false;
    Serial.println("✓ Relay OFF");
    
  } else if (action == "toggle") {
    relayState = !relayState;
    digitalWrite(RELAY_PIN, relayState ? HIGH : LOW);
    Serial.print("✓ Relay ");
    Serial.println(relayState ? "ON" : "OFF");
    
  } else if (action == "pulse") {
    Serial.println("✓ Pulse: 1000ms");
    digitalWrite(RELAY_PIN, HIGH);
    delay(1000);
    digitalWrite(RELAY_PIN, LOW);
    
  } else if (action == "test_led") {
    Serial.println("✓ Testing LED...");
    for(int i=0; i<3; i++) {
      digitalWrite(TEST_LED_PIN, LOW);  // ON
      delay(200);
      digitalWrite(TEST_LED_PIN, HIGH); // OFF
      delay(200);
    }
    digitalWrite(TEST_LED_PIN, LOW); // Keep ON
  }
}
`;
        
        navigator.clipboard.writeText(code).then(() => {
            const hasSettings = iotSettings.wifiSsid !== 'YOUR_WIFI_SSID';
            const message = hasSettings 
                ? '✅ تم نسخ الكود بنجاح!\\n\\n✨ نسخة مبسطة - بدون مكتبات خارجية!\\n\\nالخطوات في Arduino IDE:\\n1. الصق الكود (Ctrl+V)\\n2. اختر Board: NodeMCU 1.0\\n3. اختر Port: COM3 (أو حسب جهازك)\\n4. اضغط Upload ⬆️\\n5. افتح Serial Monitor (Ctrl+Shift+M)\\n6. اختر Baud Rate: ' + iotSettings.serialBaud + '\\n\\n✅ لا يحتاج ArduinoJson!\\n✅ WiFi والإعدادات مُضمّنة تلقائياً'
                : '✅ تم نسخ الكود بنجاح!\\n\\n⚠️ تنبيه: لم تقم بتعيين إعدادات WiFi\\n\\nالخطوات:\\n1. افتح Arduino IDE\\n2. الصق الكود\\n3. عدّل معلومات WiFi\\n4. عدّل عنوان السيرفر\\n5. اختر Board: NodeMCU 1.0\\n6. اختر Port\\n7. حمّل على ESP8266\\n\\n💡 نصيحة: اذهب للإعدادات لحفظ WiFi\\n✅ لا يحتاج مكتبات خارجية!';
            alert(message);
        }).catch(err => {
            console.error('Failed to copy:', err);
            alert('❌ فشل النسخ. حاول مرة أخرى.');
        });
    }
    
    // Close modals on outside click
    document.querySelectorAll('.modal').forEach(modal => {
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.classList.remove('active');
            }
        });
    });
    
    // Auto refresh every 30 seconds
    setInterval(() => {
        location.reload();
    }, 30000);
    
    console.log('🚀 IoT Dashboard loaded successfully!');
    </script>
</body>
</html>