<?php
/**
 * IoT System Database Setup Script
 * Run this file once to create all IoT tables
 */

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception('Database connection failed');
    }
    
    echo "<!DOCTYPE html>
    <html lang='ar' dir='rtl'>
    <head>
        <meta charset='UTF-8'>
        <meta name='viewport' content='width=device-width, initial-scale=1.0'>
        <title>IoT System Setup</title>
        <style>
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px; }
            .container { max-width: 800px; margin: 0 auto; background: white; border-radius: 15px; padding: 30px; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
            h1 { color: #667eea; margin-bottom: 30px; }
            .success { background: #10b981; color: white; padding: 15px; border-radius: 8px; margin: 10px 0; }
            .error { background: #ef4444; color: white; padding: 15px; border-radius: 8px; margin: 10px 0; }
            .info { background: #3b82f6; color: white; padding: 15px; border-radius: 8px; margin: 10px 0; }
            pre { background: #f3f4f6; padding: 15px; border-radius: 8px; overflow-x: auto; }
            .btn { display: inline-block; background: #667eea; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; margin-top: 20px; }
            .btn:hover { background: #5568d3; }
        </style>
    </head>
    <body>
        <div class='container'>
            <h1>🔧 IoT System Database Setup</h1>";
    
    // Read SQL file
    $sql_file = __DIR__ . '/create_iot_tables.sql';
    
    if (!file_exists($sql_file)) {
        throw new Exception('SQL file not found: ' . $sql_file);
    }
    
    $sql = file_get_contents($sql_file);
    
    // Split by semicolon and execute each statement
    $statements = array_filter(array_map('trim', explode(';', $sql)));
    
    $success_count = 0;
    $error_count = 0;
    
    foreach ($statements as $statement) {
        if (empty($statement) || strpos($statement, '--') === 0) {
            continue;
        }
        
        try {
            $db->exec($statement);
            $success_count++;
            
            // Extract table name for display
            if (preg_match('/CREATE TABLE.*?`(\w+)`/i', $statement, $matches)) {
                echo "<div class='success'>✅ Table created: {$matches[1]}</div>";
            } elseif (preg_match('/INSERT INTO.*?`(\w+)`/i', $statement, $matches)) {
                echo "<div class='success'>✅ Sample data inserted into: {$matches[1]}</div>";
            }
        } catch (PDOException $e) {
            $error_count++;
            echo "<div class='error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</div>";
        }
    }
    
    echo "<div class='info'>
            <strong>📊 Summary:</strong><br>
            ✅ Successful operations: {$success_count}<br>
            ❌ Failed operations: {$error_count}
          </div>";
    
    // Verify tables
    echo "<h2>📋 Verification</h2>";
    $tables = ['iot_devices', 'iot_commands', 'iot_logs', 'iot_sensors_data', 'iot_schedules'];
    
    foreach ($tables as $table) {
        $check = $db->query("SHOW TABLES LIKE '{$table}'");
        if ($check->rowCount() > 0) {
            $count = $db->query("SELECT COUNT(*) FROM {$table}")->fetchColumn();
            echo "<div class='success'>✅ Table '{$table}' exists ({$count} rows)</div>";
        } else {
            echo "<div class='error'>❌ Table '{$table}' not found</div>";
        }
    }
    
    echo "<a href='../admin/iot_devices.php' class='btn'>🚀 Go to IoT Dashboard</a>
        </div>
    </body>
    </html>";
    
} catch (Exception $e) {
    echo "<div class='error'>❌ Fatal Error: " . htmlspecialchars($e->getMessage()) . "</div>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}
?>
