<?php
/**
 * IoT System Test Page
 * Quick test to check database connection and tables
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<!DOCTYPE html>
<html lang='ar' dir='rtl'>
<head>
    <meta charset='UTF-8'>
    <title>IoT System Test</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; }
        .warning { background: #f59e0b; color: white; }
        .info { background: #3b82f6; color: white; }
        pre { background: #1f2937; color: #10b981; padding: 15px; border-radius: 5px; overflow-x: auto; }
        a { color: white; text-decoration: underline; }
    </style>
</head>
<body>
<h1>🔧 IoT System Test</h1>";

// Test 1: Database Connection
echo "<div class='box'><h2>1️⃣ Database Connection</h2>";
try {
    require_once '../config/database.php';
    $database = new Database();
    $db = $database->getConnection();
    
    if ($db) {
        echo "<div class='box success'>✅ Database connected successfully!</div>";
    } else {
        echo "<div class='box error'>❌ Database connection failed!</div>";
        exit;
    }
} catch (Exception $e) {
    echo "<div class='box error'>❌ Error: " . htmlspecialchars($e->getMessage()) . "</div>";
    exit;
}
echo "</div>";

// Test 2: Check Tables
echo "<div class='box'><h2>2️⃣ IoT Tables Check</h2>";
$tables = ['iot_devices', 'iot_commands', 'iot_logs', 'iot_sensors_data', 'iot_schedules'];
$missing_tables = [];

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='box success'>✅ Table '{$table}' exists ({$count} rows)</div>";
    } else {
        $missing_tables[] = $table;
        echo "<div class='box error'>❌ Table '{$table}' NOT FOUND</div>";
    }
}

if (!empty($missing_tables)) {
    echo "<div class='box warning'>
        ⚠️ Missing tables detected!<br><br>
        <a href='../database/run_iot_setup.php' style='display:inline-block;background:white;color:#f59e0b;padding:10px 20px;border-radius:5px;text-decoration:none;font-weight:bold;'>
        🚀 Run Setup Script
        </a>
    </div>";
}
echo "</div>";

// Test 3: Sample Query
if (empty($missing_tables)) {
    echo "<div class='box'><h2>3️⃣ Sample Data</h2>";
    try {
        $devices = $db->query("SELECT * FROM iot_devices LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
        if (!empty($devices)) {
            echo "<div class='box info'>📱 Found " . count($devices) . " devices:</div>";
            echo "<pre>" . json_encode($devices, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "</pre>";
        } else {
            echo "<div class='box warning'>⚠️ No devices found. Add some devices to test!</div>";
        }
    } catch (Exception $e) {
        echo "<div class='box error'>❌ Query Error: " . htmlspecialchars($e->getMessage()) . "</div>";
    }
    echo "</div>";
}

// Test 4: API Endpoints
echo "<div class='box'><h2>4️⃣ API Endpoints</h2>";
$apis = [
    'Devices API' => '../api/iot/devices.php',
    'Commands API' => '../api/iot/commands.php',
    'Logs API' => '../api/iot/logs.php',
    'ESP Control API' => '../api/esp_control.php'
];

foreach ($apis as $name => $path) {
    if (file_exists($path)) {
        echo "<div class='box success'>✅ {$name} exists</div>";
    } else {
        echo "<div class='box error'>❌ {$name} NOT FOUND at {$path}</div>";
    }
}
echo "</div>";

// Final Status
echo "<div class='box info'>
    <h2>🎯 Next Steps</h2>
    <ul style='line-height: 2;'>
        <li><a href='../database/run_iot_setup.php'>Run Database Setup</a></li>
        <li><a href='iot_devices.php'>Go to IoT Dashboard</a></li>
        <li><a href='../api/iot/devices.php'>Test Devices API</a></li>
    </ul>
</div>";

echo "</body></html>";
?>
