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

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

// جلب قوالب الأجهزة
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';
$search = isset($_GET['search']) ? $_GET['search'] : '';

$query = "SELECT * FROM iot_device_templates WHERE 1=1";

if ($category_filter) {
    $query .= " AND category = :category";
}

if ($search) {
    $query .= " AND (device_name LIKE :search OR description LIKE :search)";
}

$query .= " ORDER BY category, device_name";

$stmt = $conn->prepare($query);

if ($category_filter) {
    $stmt->bindParam(':category', $category_filter);
}

if ($search) {
    $search_param = "%{$search}%";
    $stmt->bindParam(':search', $search_param);
}

$stmt->execute();
$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">
        <!-- Header -->
        <div class="card">
            <div class="flex items-center justify-between flex-wrap gap-4">
                <div>
                    <h1 class="text-4xl font-bold text-gray-900 mb-2">
                        <i class="fas fa-microchip text-purple-600 ml-3"></i>
                        قوالب الأجهزة
                    </h1>
                    <p class="text-gray-600">إدارة القوالب الجاهزة للأجهزة الذكية</p>
                </div>
                <div class="flex gap-3 flex-wrap">
                    <button onclick="showAddModal()" class="btn btn-primary">
                        <i class="fas fa-plus ml-2"></i>
                        إضافة قالب جديد
                    </button>
                    <a href="../index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-right ml-2"></i>
                        العودة
                    </a>
                </div>
            </div>
        </div>

        <!-- الفلترة والبحث -->
        <div class="card">
            <h2 class="text-2xl font-bold text-gray-900 mb-4">
                <i class="fas fa-search text-purple-600 ml-2"></i>
                بحث وفلترة
            </h2>
            <form method="GET" class="flex flex-wrap gap-4">
            <div class="flex-1 min-w-[200px]">
                <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>" 
                       placeholder="بحث بالاسم أو الوصف..." 
                       class="form-input w-full">
            </div>
            
            <select name="category" class="form-select">
                <option value="">جميع الفئات</option>
                <option value="lighting" <?php echo $category_filter === 'lighting' ? 'selected' : ''; ?>>💡 إضاءة</option>
                <option value="control" <?php echo $category_filter === 'control' ? 'selected' : ''; ?>>🎛️ تحكم</option>
                <option value="security" <?php echo $category_filter === 'security' ? 'selected' : ''; ?>>🔒 أمان</option>
                <option value="entertainment" <?php echo $category_filter === 'entertainment' ? 'selected' : ''; ?>>🎬 ترفيه</option>
                <option value="climate" <?php echo $category_filter === 'climate' ? 'selected' : ''; ?>>❄️ مناخ</option>
                <option value="sensors" <?php echo $category_filter === 'sensors' ? 'selected' : ''; ?>>📡 حساسات</option>
                <option value="other" <?php echo $category_filter === 'other' ? 'selected' : ''; ?>>📦 أخرى</option>
            </select>

            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i>
                بحث
            </button>
            
            <a href="devices.php" class="btn btn-secondary">
                <i class="fas fa-redo"></i>
                إعادة تعيين
            </a>
            </form>
        </div>

        <!-- القوالب -->
        <?php
    $category_names = [
        'lighting' => '💡 إضاءة',
        'control' => '🎛️ تحكم',
        'security' => '🔒 أمان',
        'entertainment' => '🎬 ترفيه',
        'climate' => '❄️ مناخ',
        'sensors' => '📡 حساسات',
        'other' => '📦 أخرى'
    ];
    
        foreach ($templates_by_category as $category => $category_templates):
        ?>
        <div class="card">
        <h2 class="text-xl font-bold text-gray-800 mb-4">
            <?php echo $category_names[$category] ?? $category; ?>
            <span class="text-sm text-gray-500">(<?php echo count($category_templates); ?>)</span>
        </h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <?php foreach ($category_templates as $template): ?>
            <div class="border rounded-lg p-4 hover:shadow-md transition-shadow <?php echo !$template['is_active'] ? 'opacity-50' : ''; ?>">
                <div class="flex justify-between items-start mb-3">
                    <div class="flex-1">
                        <h3 class="font-bold text-gray-800"><?php echo htmlspecialchars($template['device_name']); ?></h3>
                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($template['device_type']); ?></p>
                    </div>
                    <?php if (!$template['is_active']): ?>
                        <span class="badge badge-red">معطل</span>
                    <?php endif; ?>
                </div>
                
                <?php if ($template['description']): ?>
                <p class="text-sm text-gray-700 mb-3"><?php echo htmlspecialchars($template['description']); ?></p>
                <?php endif; ?>
                
                <div class="flex justify-between items-center pt-3 border-t">
                    <div>
                        <p class="text-sm text-gray-600">السعر الافتراضي</p>
                        <p class="font-bold text-green-600"><?php echo number_format($template['default_price'], 2); ?> ج.م</p>
                        <?php if ($template['installation_cost'] > 0): ?>
                        <p class="text-xs text-gray-500">+ <?php echo number_format($template['installation_cost'], 2); ?> ج.م تركيب</p>
                        <?php endif; ?>
                    </div>
                    <div class="flex gap-2">
                        <button onclick="editTemplate(<?php echo $template['id']; ?>)" 
                                class="btn-icon btn-icon-green" title="تعديل">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button onclick="toggleTemplate(<?php echo $template['id']; ?>, <?php echo $template['is_active'] ? 'false' : 'true'; ?>)" 
                                class="btn-icon <?php echo $template['is_active'] ? 'btn-icon-orange' : 'btn-icon-blue'; ?>" 
                                title="<?php echo $template['is_active'] ? 'تعطيل' : 'تفعيل'; ?>">
                            <i class="fas fa-<?php echo $template['is_active'] ? 'ban' : 'check'; ?>"></i>
                        </button>
                        <button onclick="deleteTemplate(<?php echo $template['id']; ?>)" 
                                class="btn-icon btn-icon-red" title="حذف">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if (empty($templates)): ?>
        <div class="card text-center py-12">
            <i class="fas fa-microchip text-6xl text-gray-300 mb-4"></i>
            <p class="text-xl text-gray-600">لا توجد قوالب</p>
        </div>
        <?php endif; ?>
    </div>

<script>
function showAddModal() {
    alert('ميزة إضافة قالب جديد قيد التطوير');
}

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

function toggleTemplate(id, activate) {
    const action = activate ? 'تفعيل' : 'تعطيل';
    if (confirm(`هل أنت متأكد من ${action} هذا القالب؟`)) {
        alert('ميزة التفعيل/التعطيل قيد التطوير');
    }
}

function deleteTemplate(id) {
    if (confirm('هل أنت متأكد من حذف هذا القالب؟')) {
        alert('ميزة الحذف قيد التطوير');
    }
}
</script>
    </div>
</body>
</html>
