<?php
/**
 * Update iot_devices table structure
 * Adds missing columns
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        die('Database connection failed');
    }
    
    echo "<!DOCTYPE html>
    <html lang='ar' dir='rtl'>
    <head>
        <meta charset='UTF-8'>
        <title>Update IoT Devices Table</title>
        <style>
            body { font-family: Arial; padding: 20px; background: #f3f4f6; }
            .box { background: white; padding: 20px; margin: 10px 0; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            .success { background: #10b981; color: white; }
            .error { background: #ef4444; color: white; }
            .info { background: #3b82f6; color: white; }
            h1 { color: #667eea; }
        </style>
    </head>
    <body>
    <h1>🔧 Updating iot_devices Table</h1>";
    
    // Check current structure
    echo "<div class='box'><h2>Current Table Structure</h2>";
    $columns = $db->query("SHOW COLUMNS FROM iot_devices")->fetchAll(PDO::FETCH_ASSOC);
    $existing_columns = array_column($columns, 'Field');
    
    echo "<div class='box info'>Existing columns: " . implode(', ', $existing_columns) . "</div>";
    echo "</div>";
    
    // Add missing columns
    $columns_to_add = [
        'is_active' => "ALTER TABLE iot_devices ADD COLUMN is_active BOOLEAN DEFAULT TRUE AFTER is_online",
        'ip_address' => "ALTER TABLE iot_devices ADD COLUMN ip_address VARCHAR(45) AFTER last_seen",
        'firmware_version' => "ALTER TABLE iot_devices ADD COLUMN firmware_version VARCHAR(20) AFTER ip_address"
    ];
    
    echo "<div class='box'><h2>Adding Missing Columns</h2>";
    
    foreach ($columns_to_add as $column => $sql) {
        if (!in_array($column, $existing_columns)) {
            try {
                $db->exec($sql);
                echo "<div class='box success'>✅ Added column: {$column}</div>";
            } catch (Exception $e) {
                echo "<div class='box error'>❌ Error adding {$column}: " . htmlspecialchars($e->getMessage()) . "</div>";
            }
        } else {
            echo "<div class='box info'>ℹ️ Column {$column} already exists</div>";
        }
    }
    echo "</div>";
    
    // Verify final structure
    echo "<div class='box'><h2>📋 Final Structure</h2>";
    $columns = $db->query("SHOW COLUMNS FROM iot_devices")->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<table style='width:100%;border-collapse:collapse;'>";
    echo "<tr style='background:#f3f4f6;'><th style='padding:10px;text-align:right;'>Column</th><th style='padding:10px;text-align:right;'>Type</th><th style='padding:10px;text-align:right;'>Default</th></tr>";
    foreach ($columns as $col) {
        echo "<tr style='border-bottom:1px solid #e5e7eb;'>";
        echo "<td style='padding:10px;'>" . htmlspecialchars($col['Field']) . "</td>";
        echo "<td style='padding:10px;'>" . htmlspecialchars($col['Type']) . "</td>";
        echo "<td style='padding:10px;'>" . htmlspecialchars($col['Default'] ?? 'NULL') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    echo "</div>";
    
    echo "<div class='box success'>
        <h2>🎉 Table Updated Successfully!</h2>
        <p>Now let's create the missing tables...</p>
        <a href='fix_missing_tables.php' style='display:inline-block;background:#667eea;color:white;padding:15px 30px;border-radius:10px;text-decoration:none;font-weight:bold;margin-top:10px;'>
        ➡️ Create Missing Tables
        </a>
    </div>";
    
    echo "</body></html>";
    
} catch (Exception $e) {
    echo "<div class='box error'>❌ Fatal Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}
?>
