﻿<?php
session_start();
require_once '../../config/database.php';

$database = new Database();
$conn = $database->getConnection();

$room_id = isset($_GET['room_id']) ? intval($_GET['room_id']) : 0;

if ($room_id <= 0) {
    header('Location: index.php');
    exit;
}

// جلب معلومات الغرفة والمشروع
$query = "SELECT r.*, p.customer_name, p.id as project_id 
          FROM iot_project_rooms r
          JOIN iot_projects p ON r.project_id = p.id
          WHERE r.id = :room_id";
$stmt = $conn->prepare($query);
$stmt->bindParam(':room_id', $room_id);
$stmt->execute();
$room = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$room) {
    header('Location: index.php');
    exit;
}

// جلب الأجهزة المضافة
$devices_query = "SELECT * FROM iot_project_devices WHERE room_id = :room_id ORDER BY device_type, device_name";
$devices_stmt = $conn->prepare($devices_query);
$devices_stmt->bindParam(':room_id', $room_id);
$devices_stmt->execute();
$devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);

// جلب قوالب الأجهزة
$templates_query = "SELECT * FROM iot_device_templates WHERE is_active = 1 ORDER BY category, device_name";
$templates_stmt = $conn->query($templates_query);
$templates = $templates_stmt->fetchAll(PDO::FETCH_ASSOC);

// تجميع القوالب حسب الفئة
$templates_by_category = [];
foreach ($templates as $template) {
    $templates_by_category[$template['category']][] = $template;
}

?>
<!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">
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
    <div class="container">
        <div class="main-content">
    <div class="content-header">
        <div>
            <h1 class="text-3xl font-bold text-gray-800">🔌 إدارة الأجهزة</h1>
            <p class="text-gray-600 mt-2">
                <strong><?php echo htmlspecialchars($room['room_name']); ?></strong>
                - مشروع: <?php echo htmlspecialchars($room['customer_name']); ?>
            </p>
        </div>
        <div class="flex gap-3">
            <a href="rooms.php?project_id=<?php echo $room['project_id']; ?>" class="btn btn-secondary">
                <i class="fas fa-arrow-right"></i>
                العودة للغرف
            </a>
            <a href="view.php?id=<?php echo $room['project_id']; ?>" class="btn btn-secondary">
                <i class="fas fa-eye"></i>
                عرض المشروع
            </a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- نموذج إضافة جهاز -->
        <div class="lg:col-span-1">
            <div class="card sticky top-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-plus-circle text-green-500"></i>
                    إضافة جهاز جديد
                </h2>

                <form id="addDeviceForm" class="space-y-4">
                    <input type="hidden" name="room_id" value="<?php echo $room_id; ?>">
                    
                    <!-- اختيار من القوالب -->
                    <div>
                        <label class="form-label">اختيار من القوالب الجاهزة</label>
                        <select id="deviceTemplate" class="form-select">
                            <option value="">اختر جهاز (اختياري)</option>
                            <?php foreach ($templates_by_category as $category => $category_templates): ?>
                                <?php
                                $category_names = [
                                    'lighting' => '💡 إضاءة',
                                    'control' => '🎛️ تحكم',
                                    'security' => '🔒 أمان',
                                    'entertainment' => '🎬 ترفيه',
                                    'climate' => '❄️ مناخ',
                                    'sensors' => '📡 حساسات',
                                    'other' => '📦 أخرى'
                                ];
                                ?>
                                <optgroup label="<?php echo $category_names[$category] ?? $category; ?>">
                                    <?php foreach ($category_templates as $template): ?>
                                        <option value="<?php echo $template['id']; ?>"
                                                data-name="<?php echo htmlspecialchars($template['device_name']); ?>"
                                                data-type="<?php echo htmlspecialchars($template['device_type']); ?>"
                                                data-price="<?php echo $template['default_price']; ?>"
                                                data-installation="<?php echo $template['installation_cost']; ?>"
                                                data-description="<?php echo htmlspecialchars($template['description']); ?>">
                                            <?php echo htmlspecialchars($template['device_name']); ?>
                                            (<?php echo number_format($template['default_price'], 0); ?> ج.م)
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div id="templateDescription" class="hidden p-3 bg-blue-50 rounded-lg text-sm text-blue-800">
                        <i class="fas fa-info-circle"></i>
                        <span id="descriptionText"></span>
                    </div>

                    <div>
                        <label class="form-label required">اسم الجهاز</label>
                        <input type="text" name="device_name" id="deviceName" required 
                               class="form-input" placeholder="مثال: مصباح LED ذكي">
                    </div>

                    <div>
                        <label class="form-label">نوع الجهاز</label>
                        <input type="text" name="device_type" id="deviceType" 
                               class="form-input" placeholder="مثال: smart_bulb">
                    </div>

                    <div>
                        <label class="form-label">الموديل</label>
                        <input type="text" name="device_model" 
                               class="form-input" placeholder="مثال: Philips Hue">
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="form-label required">الكمية</label>
                            <input type="number" name="quantity" id="quantity" value="1" min="1" required 
                                   class="form-input" onchange="calculateTotal()">
                        </div>

                        <div>
                            <label class="form-label required">سعر الوحدة</label>
                            <input type="number" name="unit_price" id="unitPrice" step="0.01" required 
                                   class="form-input" placeholder="150.00" onchange="calculateTotal()">
                        </div>
                    </div>

                    <div>
                        <label class="form-label">تكلفة التركيب</label>
                        <input type="number" name="installation_cost" id="installationCost" step="0.01" value="0" 
                               class="form-input" placeholder="20.00" onchange="calculateTotal()">
                    </div>

                    <div class="p-4 bg-green-50 rounded-lg">
                        <div class="flex justify-between items-center">
                            <span class="text-gray-700 font-bold">الإجمالي:</span>
                            <span id="totalPrice" class="text-2xl font-bold text-green-600">0.00 ج.م</span>
                        </div>
                        <p class="text-xs text-gray-600 mt-1">
                            (الكمية × السعر) + تكلفة التركيب
                        </p>
                    </div>

                    <div>
                        <label class="form-label">ملاحظات</label>
                        <textarea name="notes" rows="2" class="form-input" 
                                  placeholder="أي ملاحظات خاصة بالجهاز..."></textarea>
                    </div>

                    <button type="submit" class="btn btn-primary w-full">
                        <i class="fas fa-plus"></i>
                        إضافة الجهاز
                    </button>
                </form>
            </div>
        </div>

        <!-- قائمة الأجهزة -->
        <div class="lg:col-span-2">
            <div class="card">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-list text-blue-500"></i>
                        الأجهزة المضافة (<?php echo count($devices); ?>)
                    </h2>
                    <?php if (!empty($devices)): ?>
                        <div class="text-left">
                            <?php
                            $total_cost = array_sum(array_column($devices, 'total_price'));
                            ?>
                            <p class="text-sm text-gray-600">إجمالي التكلفة</p>
                            <p class="text-2xl font-bold text-green-600">
                                <?php echo number_format($total_cost, 2); ?> ج.م
                            </p>
                        </div>
                    <?php endif; ?>
                </div>

                <?php if (empty($devices)): ?>
                    <div class="text-center py-12 text-gray-500">
                        <i class="fas fa-microchip text-6xl mb-4 opacity-50"></i>
                        <p class="text-lg">لم يتم إضافة أي أجهزة بعد</p>
                        <p class="text-sm mt-2">استخدم النموذج على اليسار لإضافة جهاز جديد</p>
                    </div>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-4 py-3 text-right">الجهاز</th>
                                    <th class="px-4 py-3 text-center">الكمية</th>
                                    <th class="px-4 py-3 text-center">سعر الوحدة</th>
                                    <th class="px-4 py-3 text-center">التركيب</th>
                                    <th class="px-4 py-3 text-center">الإجمالي</th>
                                    <th class="px-4 py-3 text-center">الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($devices as $device): ?>
                                    <tr class="border-t hover:bg-gray-50">
                                        <td class="px-4 py-3">
                                            <p class="font-bold"><?php echo htmlspecialchars($device['device_name']); ?></p>
                                            <?php if ($device['device_model']): ?>
                                                <p class="text-sm text-gray-600"><?php echo htmlspecialchars($device['device_model']); ?></p>
                                            <?php endif; ?>
                                            <?php if ($device['device_type']): ?>
                                                <span class="text-xs text-gray-500"><?php echo htmlspecialchars($device['device_type']); ?></span>
                                            <?php endif; ?>
                                            <?php if ($device['notes']): ?>
                                                <p class="text-xs text-yellow-600 mt-1">
                                                    <i class="fas fa-sticky-note"></i>
                                                    <?php echo htmlspecialchars($device['notes']); ?>
                                                </p>
                                            <?php endif; ?>
                                        </td>
                                        <td class="px-4 py-3 text-center">
                                            <span class="badge badge-blue"><?php echo $device['quantity']; ?></span>
                                        </td>
                                        <td class="px-4 py-3 text-center">
                                            <?php echo number_format($device['unit_price'], 2); ?> ج.م
                                        </td>
                                        <td class="px-4 py-3 text-center">
                                            <?php echo number_format($device['installation_cost'], 2); ?> ج.م
                                        </td>
                                        <td class="px-4 py-3 text-center">
                                            <span class="font-bold text-green-600">
                                                <?php echo number_format($device['total_price'], 2); ?> ج.م
                                            </span>
                                        </td>
                                        <td class="px-4 py-3 text-center">
                                            <div class="flex gap-2 justify-center">
                                                <button onclick="editDevice(<?php echo $device['id']; ?>)" 
                                                        class="btn-icon btn-icon-green" title="تعديل">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button onclick="deleteDevice(<?php echo $device['id']; ?>)" 
                                                        class="btn-icon btn-icon-red" title="حذف">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="mt-6 pt-6 border-t flex gap-3">
                        <a href="view.php?id=<?php echo $room['project_id']; ?>" class="btn btn-primary">
                            <i class="fas fa-check"></i>
                            إنهاء وعرض المشروع
                        </a>
                        <a href="rooms.php?project_id=<?php echo $room['project_id']; ?>" class="btn btn-secondary">
                            <i class="fas fa-door-open"></i>
                            إضافة غرفة أخرى
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        </div>
    </div>

<script>
// تطبيق القالب
document.getElementById('deviceTemplate').addEventListener('change', function() {
    const selected = this.options[this.selectedIndex];
    if (selected.value) {
        document.getElementById('deviceName').value = selected.dataset.name;
        document.getElementById('deviceType').value = selected.dataset.type;
        document.getElementById('unitPrice').value = selected.dataset.price;
        document.getElementById('installationCost').value = selected.dataset.installation;
        
        // عرض الوصف
        const desc = selected.dataset.description;
        if (desc) {
            document.getElementById('descriptionText').textContent = desc;
            document.getElementById('templateDescription').classList.remove('hidden');
        }
        
        calculateTotal();
    } else {
        document.getElementById('templateDescription').classList.add('hidden');
    }
});

// حساب الإجمالي
function calculateTotal() {
    const quantity = parseFloat(document.getElementById('quantity').value) || 0;
    const unitPrice = parseFloat(document.getElementById('unitPrice').value) || 0;
    const installation = parseFloat(document.getElementById('installationCost').value) || 0;
    
    const total = (quantity * unitPrice) + installation;
    document.getElementById('totalPrice').textContent = total.toFixed(2) + ' ج.م';
}

// إضافة جهاز
document.getElementById('addDeviceForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    
    // حساب الإجمالي
    const quantity = parseFloat(formData.get('quantity'));
    const unitPrice = parseFloat(formData.get('unit_price'));
    const installation = parseFloat(formData.get('installation_cost'));
    const totalPrice = (quantity * unitPrice) + installation;
    
    formData.append('total_price', totalPrice);
    
    fetch('api/add-device.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('تم إضافة الجهاز بنجاح');
            location.reload();
        } else {
            alert('حدث خطأ: ' + data.message);
        }
    })
    .catch(error => {
        alert('حدث خطأ في الاتصال');
        console.error('Error:', error);
    });
});

// حذف جهاز
function deleteDevice(id) {
    if (confirm('هل أنت متأكد من حذف هذا الجهاز؟')) {
        fetch('api/delete-device.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ id: id })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('تم حذف الجهاز بنجاح');
                location.reload();
            } else {
                alert('حدث خطأ: ' + data.message);
            }
        })
        .catch(error => {
            alert('حدث خطأ في الاتصال');
            console.error('Error:', error);
        });
    }
}

function editDevice(id) {
    alert('ميزة التعديل قيد التطوير');
}

// حساب الإجمالي عند تحميل الصفحة
calculateTotal();
</script>

<style>
.form-label.required::after {
    content: ' *';
    color: #ef4444;
}
</style>

</body>
</html>
