<?php
/**
 * IoT Devices Management - إدارة الأجهزة
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Get all devices
    $devices_query = "SELECT * FROM iot_devices ORDER BY device_id";
    $devices_stmt = $db->query($devices_query);
    $devices = $devices_stmt->fetchAll(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); }
        .device-card { background: linear-gradient(135deg, #f3f4f6 0%, #ffffff 100%); border-radius: 15px; padding: 20px; margin-bottom: 15px; border: 2px solid #e5e7eb; transition: all 0.3s; }
        .device-card:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,0.1); border-color: #667eea; }
        .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-danger { background: linear-gradient(135deg, #ef4444, #dc2626); 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); }
        .modal { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.7); backdrop-filter: blur(5px); z-index: 1000; align-items: center; justify-content: center; }
        .modal.active { display: flex; }
        .modal-content { background: white; border-radius: 20px; max-width: 600px; width: 100%; padding: 30px; animation: slideUp 0.3s; }
        @keyframes slideUp { from { opacity: 0; transform: translateY(50px); } to { opacity: 1; transform: translateY(0); } }
        .status-badge { padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: bold; }
        .status-online { background: #10b981; color: white; }
        .status-offline { background: #ef4444; color: white; }
    </style>
</head>
<body>
    <div class="max-w-6xl 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-microchip text-purple-600 ml-2"></i>
                        إدارة الأجهزة
                    </h1>
                    <p class="text-gray-600">إضافة وتعديل وحذف أجهزة IoT</p>
                </div>
                <div class="flex gap-3">
                    <a href="index.php" class="btn bg-gray-200 text-gray-800">
                        <i class="fas fa-arrow-right ml-2"></i>
                        رجوع
                    </a>
                    <button onclick="openAddDeviceModal()" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة جهاز
                    </button>
                </div>
            </div>
        </div>

        <!-- Devices List -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-6">
                <i class="fas fa-list ml-2"></i>
                الأجهزة المسجلة
            </h2>

            <?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="openAddDeviceModal()" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة جهاز الآن
                    </button>
                </div>
            <?php else: ?>
                <div class="space-y-4">
                    <?php foreach ($devices as $device): ?>
                        <div class="device-card">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-4 flex-1">
                                    <div class="text-4xl">
                                        <i class="fas fa-microchip text-purple-600"></i>
                                    </div>
                                    <div class="flex-1">
                                        <div class="flex items-center gap-3 mb-2">
                                            <h3 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($device['device_name']); ?></h3>
                                            <span class="status-badge <?php echo (isset($device['status']) && $device['status'] === 'online') ? 'status-online' : 'status-offline'; ?>">
                                                <?php echo (isset($device['status']) && $device['status'] === 'online') ? 'متصل' : 'غير متصل'; ?>
                                            </span>
                                        </div>
                                        <div class="flex gap-4 text-sm text-gray-600">
                                            <span><i class="fas fa-tag ml-1"></i> <?php echo $device['device_id']; ?></span>
                                            <span><i class="fas fa-network-wired ml-1"></i> <?php echo htmlspecialchars($device['ip_address']); ?></span>
                                            <span><i class="fas fa-ethernet ml-1"></i> Port: <?php echo $device['port'] ?? 80; ?></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex gap-2">
                                    <a href="pins.php?device_id=<?php echo $device['device_id']; ?>" 
                                       class="btn bg-blue-600 text-white text-sm">
                                        <i class="fas fa-sliders-h ml-1"></i>
                                        البينات
                                    </a>
                                    <button onclick="editDevice(<?php echo htmlspecialchars(json_encode($device)); ?>)" 
                                            class="btn bg-green-600 text-white text-sm">
                                        <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">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Add/Edit Device Modal -->
    <div id="deviceModal" class="modal">
        <div class="modal-content">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-2xl font-bold text-gray-900" id="modalTitle">إضافة جهاز جديد</h3>
                <button onclick="closeDeviceModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>

            <form id="deviceForm" class="space-y-4">
                <input type="hidden" id="old_device_id" name="old_device_id">

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">معرف الجهاز (Device ID) *</label>
                    <input type="text" name="device_id" id="device_id" required class="input-field" 
                           placeholder="مثال: ESP01">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">اسم الجهاز *</label>
                    <input type="text" name="device_name" id="device_name" required class="input-field" 
                           placeholder="مثال: جهاز غرفة النوم">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">عنوان IP *</label>
                    <input type="text" name="ip_address" id="ip_address" required class="input-field" 
                           placeholder="مثال: 192.168.1.100">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">المنفذ (Port) *</label>
                    <input type="number" name="port" id="port" required class="input-field" 
                           value="80" placeholder="80">
                </div>

                <div>
                    <label class="block text-sm font-bold text-gray-700 mb-2">الحالة</label>
                    <select name="status" id="status" class="input-field">
                        <option value="online">متصل (Online)</option>
                        <option value="offline">غير متصل (Offline)</option>
                    </select>
                </div>

                <div class="flex gap-3 pt-4">
                    <button type="submit" class="flex-1 btn btn-success py-3">
                        <i class="fas fa-save ml-2"></i>
                        <span id="submitText">حفظ الجهاز</span>
                    </button>
                    <button type="button" onclick="closeDeviceModal()" class="flex-1 bg-gray-200 text-gray-800 py-3 rounded-lg font-bold">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
    let editMode = false;

    function openAddDeviceModal() {
        editMode = false;
        document.getElementById('modalTitle').textContent = 'إضافة جهاز جديد';
        document.getElementById('submitText').textContent = 'حفظ الجهاز';
        document.getElementById('deviceForm').reset();
        document.getElementById('old_device_id').value = '';
        document.getElementById('deviceModal').classList.add('active');
    }

    function closeDeviceModal() {
        document.getElementById('deviceModal').classList.remove('active');
    }

    function editDevice(device) {
        editMode = true;
        document.getElementById('modalTitle').textContent = 'تعديل الجهاز';
        document.getElementById('submitText').textContent = 'تحديث الجهاز';
        document.getElementById('old_device_id').value = device.device_id;
        document.getElementById('device_id').value = device.device_id;
        document.getElementById('device_name').value = device.device_name;
        document.getElementById('ip_address').value = device.ip_address;
        document.getElementById('port').value = device.port;
        document.getElementById('status').value = device.status;
        document.getElementById('deviceModal').classList.add('active');
    }

    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/json' },
                body: JSON.stringify({ 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);
        }
    }

    document.getElementById('deviceForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);

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

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