<?php
/**
 * Add status column to iot_devices table
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<h2>Adding status column to iot_devices...</h2>";
    
    // Check if column exists
    $check_query = "SHOW COLUMNS FROM iot_devices LIKE 'status'";
    $check_stmt = $db->query($check_query);
    
    if ($check_stmt->rowCount() > 0) {
        echo "<p style='color: orange;'>✓ Column 'status' already exists!</p>";
    } else {
        // Add status column
        $alter_query = "ALTER TABLE iot_devices 
                       ADD COLUMN status ENUM('online', 'offline') DEFAULT 'offline' 
                       AFTER is_online";
        $db->exec($alter_query);
        echo "<p style='color: green;'>✓ Column 'status' added successfully!</p>";
    }
    
    // Sync is_online with status
    $sync_query = "UPDATE iot_devices 
                   SET status = IF(is_online = 1, 'online', 'offline')";
    $db->exec($sync_query);
    echo "<p style='color: green;'>✓ Synced is_online with status!</p>";
    
    echo "<h3>Current devices:</h3>";
    $devices_query = "SELECT device_id, device_name, is_online, status, last_seen FROM iot_devices";
    $devices_stmt = $db->query($devices_query);
    $devices = $devices_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<table border='1' cellpadding='10'>";
    echo "<tr><th>Device ID</th><th>Name</th><th>is_online</th><th>status</th><th>Last Seen</th></tr>";
    foreach ($devices as $device) {
        $status_color = $device['status'] === 'online' ? 'green' : 'red';
        echo "<tr>";
        echo "<td>{$device['device_id']}</td>";
        echo "<td>{$device['device_name']}</td>";
        echo "<td>{$device['is_online']}</td>";
        echo "<td style='color: $status_color; font-weight: bold;'>{$device['status']}</td>";
        echo "<td>{$device['last_seen']}</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<p style='color: green; font-weight: bold;'>✅ All done!</p>";
    echo "<p><a href='../admin/iot/index.php'>← Back to IoT Dashboard</a></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . $e->getMessage() . "</p>";
}
?>
