<?php
/**
 * Add current_state column to device_pins 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 current_state column to device_pins...</h2>";
    
    // Check if column exists
    $check_query = "SHOW COLUMNS FROM device_pins LIKE 'current_state'";
    $check_stmt = $db->query($check_query);
    
    if ($check_stmt->rowCount() > 0) {
        echo "<p style='color: orange;'>✓ Column 'current_state' already exists!</p>";
    } else {
        // Add current_state column
        $alter_query = "ALTER TABLE device_pins 
                       ADD COLUMN current_state TINYINT(1) DEFAULT 0 
                       AFTER pin_icon";
        $db->exec($alter_query);
        echo "<p style='color: green;'>✓ Column 'current_state' added successfully!</p>";
    }
    
    echo "<h3>Current pins:</h3>";
    $pins_query = "SELECT device_id, pin_name, pin_gpio, current_state FROM device_pins";
    $pins_stmt = $db->query($pins_query);
    $pins = $pins_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo "<table border='1' cellpadding='10'>";
    echo "<tr><th>Device ID</th><th>Pin Name</th><th>GPIO</th><th>Current State</th></tr>";
    foreach ($pins as $pin) {
        $state_color = $pin['current_state'] == 1 ? 'green' : 'gray';
        $state_text = $pin['current_state'] == 1 ? 'ON' : 'OFF';
        echo "<tr>";
        echo "<td>{$pin['device_id']}</td>";
        echo "<td>{$pin['pin_name']}</td>";
        echo "<td>GPIO{$pin['pin_gpio']}</td>";
        echo "<td style='color: $state_color; font-weight: bold;'>$state_text</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<p style='color: green; font-weight: bold;'>✅ All done!</p>";
    echo "<p><a href='../admin/iot/control.php'>← Back to Control Panel</a></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ Error: " . $e->getMessage() . "</p>";
}
?>
