<?php
/**
 * Update IoT Devices Table - Add Missing Columns
 */

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

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

echo "<!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 Devices</title>
    <style>
        * { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }
        .container { max-width: 800px; margin: 0 auto; background: white; border-radius: 20px; padding: 40px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
        .success { background: #10b981; color: white; padding: 15px; border-radius: 10px; margin: 10px 0; }
        .error { background: #ef4444; color: white; padding: 15px; border-radius: 10px; margin: 10px 0; }
        .info { background: #3b82f6; color: white; padding: 15px; border-radius: 10px; margin: 10px 0; }
        .warning { background: #f59e0b; color: white; padding: 15px; border-radius: 10px; margin: 10px 0; }
        h1 { color: #1f2937; margin-bottom: 30px; }
        .btn { display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; text-decoration: none; border-radius: 10px; margin-top: 20px; font-weight: bold; }
    </style>
</head>
<body>
<div class='container'>";

echo "<h1>🔧 تحديث جدول IoT Devices</h1>";

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('فشل الاتصال بقاعدة البيانات');
    }
    
    echo "<div class='info'>✅ تم الاتصال بقاعدة البيانات بنجاح</div>";
    
    // Check if table exists
    $check_table = $db->query("SHOW TABLES LIKE 'iot_devices'");
    if ($check_table->rowCount() == 0) {
        throw new Exception('جدول iot_devices غير موجود! قم بتشغيل run_iot_setup.php أولاً');
    }
    
    echo "<div class='info'>✅ جدول iot_devices موجود</div>";
    
    // Get current columns
    $columns_query = $db->query("SHOW COLUMNS FROM iot_devices");
    $existing_columns = $columns_query->fetchAll(PDO::FETCH_COLUMN);
    
    echo "<div class='info'>📋 الأعمدة الحالية: " . implode(', ', $existing_columns) . "</div>";
    
    $updates = [];
    
    // Add 'status' column if not exists
    if (!in_array('status', $existing_columns)) {
        $db->exec("ALTER TABLE iot_devices ADD COLUMN status ENUM('online', 'offline') DEFAULT 'offline' AFTER ip_address");
        $updates[] = "تم إضافة عمود 'status'";
        echo "<div class='success'>✅ تم إضافة عمود 'status'</div>";
    } else {
        echo "<div class='warning'>⚠️ عمود 'status' موجود بالفعل</div>";
    }
    
    // Add 'port' column if not exists
    if (!in_array('port', $existing_columns)) {
        $db->exec("ALTER TABLE iot_devices ADD COLUMN port INT DEFAULT 80 AFTER ip_address");
        $updates[] = "تم إضافة عمود 'port'";
        echo "<div class='success'>✅ تم إضافة عمود 'port'</div>";
    } else {
        echo "<div class='warning'>⚠️ عمود 'port' موجود بالفعل</div>";
    }
    
    // Update existing records to have default values
    if (!empty($updates)) {
        $db->exec("UPDATE iot_devices SET status = 'offline' WHERE status IS NULL");
        $db->exec("UPDATE iot_devices SET port = 80 WHERE port IS NULL OR port = 0");
        echo "<div class='success'>✅ تم تحديث السجلات الموجودة بالقيم الافتراضية</div>";
    }
    
    // Add index for status if needed
    try {
        $db->exec("ALTER TABLE iot_devices ADD INDEX idx_status (status)");
        echo "<div class='success'>✅ تم إضافة فهرس لعمود status</div>";
    } catch (Exception $e) {
        echo "<div class='warning'>⚠️ فهرس status موجود بالفعل</div>";
    }
    
    // Show final structure
    echo "<div class='info'><strong>📊 الهيكل النهائي للجدول:</strong></div>";
    $final_columns = $db->query("SHOW COLUMNS FROM iot_devices");
    echo "<div style='background: #f3f4f6; padding: 15px; border-radius: 10px; margin: 10px 0;'>";
    echo "<table style='width: 100%; border-collapse: collapse;'>";
    echo "<tr style='background: #e5e7eb;'><th style='padding: 8px; text-align: right;'>اسم العمود</th><th style='padding: 8px; text-align: right;'>النوع</th><th style='padding: 8px; text-align: right;'>القيمة الافتراضية</th></tr>";
    
    while ($col = $final_columns->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr style='border-bottom: 1px solid #d1d5db;'>";
        echo "<td style='padding: 8px;'>" . htmlspecialchars($col['Field']) . "</td>";
        echo "<td style='padding: 8px;'>" . htmlspecialchars($col['Type']) . "</td>";
        echo "<td style='padding: 8px;'>" . htmlspecialchars($col['Default'] ?? 'NULL') . "</td>";
        echo "</tr>";
    }
    echo "</table></div>";
    
    if (empty($updates)) {
        echo "<div class='info'>ℹ️ الجدول محدث بالفعل - لا توجد تغييرات مطلوبة</div>";
    } else {
        echo "<div class='success'><strong>🎉 تم التحديث بنجاح!</strong><br>التغييرات المطبقة:<br>• " . implode('<br>• ', $updates) . "</div>";
    }
    
    echo "<a href='../admin/iot/index.php' class='btn'>🚀 الذهاب إلى لوحة التحكم IoT</a>";
    
} catch (Exception $e) {
    echo "<div class='error'>❌ خطأ: " . htmlspecialchars($e->getMessage()) . "</div>";
    echo "<div class='error'>التفاصيل: " . htmlspecialchars($e->getTraceAsString()) . "</div>";
}

echo "</div></body></html>";
?>
