<?php
/**
 * Update IoT Logs Table - Add state and gpio 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'>
    <title>تحديث جدول IoT Logs</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; }
        h1 { color: #1f2937; margin-bottom: 30px; }
    </style>
</head>
<body>
<div class='container'>";

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<div class='info'>✅ تم الاتصال بقاعدة البيانات</div>";
    
    // Check if table exists
    $check_table = $db->query("SHOW TABLES LIKE 'iot_logs'");
    if ($check_table->rowCount() == 0) {
        throw new Exception('جدول iot_logs غير موجود!');
    }
    
    // Get current columns
    $columns_query = $db->query("SHOW COLUMNS FROM iot_logs");
    $existing_columns = $columns_query->fetchAll(PDO::FETCH_COLUMN);
    
    // Add 'gpio' column if not exists
    if (!in_array('gpio', $existing_columns)) {
        $db->exec("ALTER TABLE iot_logs ADD COLUMN gpio INT AFTER device_id");
        echo "<div class='success'>✅ تم إضافة عمود 'gpio'</div>";
    } else {
        echo "<div class='info'>⚠️ عمود 'gpio' موجود بالفعل</div>";
    }
    
    // Add 'state' column if not exists
    if (!in_array('state', $existing_columns)) {
        $db->exec("ALTER TABLE iot_logs ADD COLUMN state TINYINT DEFAULT 0 AFTER gpio");
        echo "<div class='success'>✅ تم إضافة عمود 'state'</div>";
    } else {
        echo "<div class='info'>⚠️ عمود 'state' موجود بالفعل</div>";
    }
    
    // Add index
    try {
        $db->exec("ALTER TABLE iot_logs ADD INDEX idx_device_gpio (device_id, gpio)");
        echo "<div class='success'>✅ تم إضافة فهرس للبحث السريع</div>";
    } catch (Exception $e) {
        echo "<div class='info'>⚠️ الفهرس موجود بالفعل</div>";
    }
    
    echo "<div class='success'>🎉 تم التحديث بنجاح!</div>";
    
} catch (Exception $e) {
    echo "<div class='error'>❌ خطأ: " . htmlspecialchars($e->getMessage()) . "</div>";
}

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