<?php
/**
 * Create IoT Settings Table
 */

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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    echo "<!DOCTYPE html>
    <html lang='ar' dir='rtl'>
    <head>
        <meta charset='UTF-8'>
        <title>Create Settings Table</title>
        <style>
            body { font-family: Arial; padding: 20px; background: #667eea; }
            .box { background: white; padding: 20px; margin: 10px auto; border-radius: 15px; max-width: 600px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
            .success { background: #10b981; color: white; }
            h1 { color: white; text-align: center; }
        </style>
    </head>
    <body>
    <h1>🔧 Creating Settings Table</h1>";
    
    // Create settings table
    $db->exec("
        CREATE TABLE IF NOT EXISTS `iot_settings` (
          `id` INT AUTO_INCREMENT PRIMARY KEY,
          `setting_key` VARCHAR(100) UNIQUE NOT NULL,
          `setting_value` TEXT,
          `description` TEXT,
          `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    
    echo "<div class='box success'>✅ Settings table created!</div>";
    
    // Insert default settings
    $defaults = [
        ['wifi_ssid', '', 'WiFi Network Name'],
        ['wifi_password', '', 'WiFi Password'],
        ['server_url', 'http://YOUR_SERVER_IP/KL/backend/api/esp_control.php', 'Server API URL'],
        ['server_port', '80', 'Server Port (80 for HTTP, 443 for HTTPS)'],
        ['poll_interval', '3000', 'Polling interval in milliseconds'],
        ['relay_pin', '5', 'Default relay pin (GPIO5/D1)'],
        ['led_pin', '2', 'Default LED pin (GPIO2/D4)'],
        ['test_led_pin', '2', 'Built-in test LED (GPIO2)'],
        ['serial_baud', '115200', 'Serial Monitor Baud Rate']
    ];
    
    foreach ($defaults as $setting) {
        try {
            $stmt = $db->prepare("INSERT IGNORE INTO iot_settings (setting_key, setting_value, description) VALUES (?, ?, ?)");
            $stmt->execute($setting);
        } catch (Exception $e) {
            // Ignore duplicates
        }
    }
    
    echo "<div class='box success'>✅ Default settings inserted!</div>";
    
    echo "<div class='box success' style='text-align:center;'>
        <h2 style='color:white;margin:0 0 20px 0;'>🎉 Done!</h2>
        <a href='../admin/iot_settings.php' 
           style='display:inline-block;background:#667eea;color:white;padding:15px 30px;
                  border-radius:10px;text-decoration:none;font-weight:bold;'>
        ⚙️ Go to Settings
        </a>
    </div>";
    
    echo "</body></html>";
    
} catch (Exception $e) {
    echo "<div class='box' style='background:#ef4444;color:white;'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</div>";
}
?>
