<?php
// سكريبت لحذف القوالب المكررة من قاعدة البيانات

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

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

echo "<h2>🧹 حذف القوالب المكررة</h2>";

try {
    // حذف القوالب المكررة من جدول الأجهزة - نبقي فقط أقل ID
    $query = "DELETE t1 FROM iot_device_templates t1
              INNER JOIN iot_device_templates t2 
              WHERE t1.id > t2.id 
              AND t1.device_name = t2.device_name 
              AND t1.device_type = t2.device_type 
              AND t1.category = t2.category";
    
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $deleted_devices = $stmt->rowCount();
    
    echo "<p>✅ تم حذف {$deleted_devices} قالب مكرر من قوالب الأجهزة</p>";
    
    // حذف القوالب المكررة من جدول الغرف
    $query2 = "DELETE t1 FROM iot_room_templates t1
               INNER JOIN iot_room_templates t2 
               WHERE t1.id > t2.id 
               AND t1.room_name = t2.room_name 
               AND t1.room_type = t2.room_type";
    
    $stmt2 = $conn->prepare($query2);
    $stmt2->execute();
    $deleted_rooms = $stmt2->rowCount();
    
    echo "<p>✅ تم حذف {$deleted_rooms} قالب مكرر من قوالب الغرف</p>";
    
    // عرض القوالب المتبقية
    $devices_query = "SELECT category, COUNT(*) as count FROM iot_device_templates GROUP BY category";
    $devices_stmt = $conn->query($devices_query);
    $devices_result = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<h3>📊 القوالب المتبقية:</h3>";
    echo "<h4>قوالب الأجهزة:</h4><ul>";
    foreach ($devices_result as $row) {
        echo "<li>{$row['category']}: {$row['count']} قالب</li>";
    }
    echo "</ul>";
    
    $rooms_query = "SELECT COUNT(*) as count FROM iot_room_templates";
    $rooms_stmt = $conn->query($rooms_query);
    $rooms_count = $rooms_stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
    echo "<h4>قوالب الغرف: {$rooms_count} قالب</h4>";
    
    echo "<p style='color: green; font-weight: bold;'>✅ تم تنظيف قاعدة البيانات بنجاح!</p>";
    echo "<p><a href='../admin/iot-estimation/templates/devices.php'>عرض قوالب الأجهزة</a></p>";
    echo "<p><a href='../admin/iot-estimation/templates/rooms.php'>عرض قوالب الغرف</a></p>";
    
} catch (PDOException $e) {
    echo "<p style='color: red;'>❌ خطأ: " . $e->getMessage() . "</p>";
}
?>
