<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "Testing IoT Estimation Setup...\n\n";

// Test 1: Check if database config exists
$config_path = __DIR__ . '/../config/database.php';
echo "1. Checking database config: ";
if (file_exists($config_path)) {
    echo "✅ Found\n";
    require_once $config_path;
} else {
    echo "❌ Not found at: $config_path\n";
    exit;
}

// Test 2: Check database connection
echo "2. Testing database connection: ";
try {
    $database = new Database();
    $conn = $database->getConnection();
    if ($conn) {
        echo "✅ Connected\n";
    } else {
        echo "❌ Failed\n";
        exit;
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    exit;
}

// Test 3: Check SQL file
$sql_file = __DIR__ . '/create_iot_estimation_tables.sql';
echo "3. Checking SQL file: ";
if (file_exists($sql_file)) {
    echo "✅ Found\n";
} else {
    echo "❌ Not found\n";
    exit;
}

// Test 4: Execute SQL
echo "4. Executing SQL statements...\n";
$sql = file_get_contents($sql_file);
$statements = array_filter(
    array_map('trim', explode(';', $sql)),
    function($stmt) {
        return !empty($stmt) && !preg_match('/^--/', $stmt);
    }
);

echo "   Found " . count($statements) . " statements\n";

$success = 0;
$errors = 0;

foreach ($statements as $statement) {
    try {
        $conn->exec($statement);
        $success++;
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'already exists') === false) {
            echo "   ⚠️  Warning: " . $e->getMessage() . "\n";
            $errors++;
        }
    }
}

echo "   ✅ Executed $success statements successfully\n";
if ($errors > 0) {
    echo "   ⚠️  $errors warnings\n";
}

// Test 5: Verify tables
echo "5. Verifying tables:\n";
$tables = ['iot_projects', 'iot_project_rooms', 'iot_project_devices', 'iot_device_templates', 'iot_room_templates'];

foreach ($tables as $table) {
    $stmt = $conn->query("SHOW TABLES LIKE '{$table}'");
    if ($stmt->rowCount() > 0) {
        $countStmt = $conn->query("SELECT COUNT(*) as count FROM {$table}");
        $count = $countStmt->fetch(PDO::FETCH_ASSOC)['count'];
        echo "   ✅ {$table} ({$count} records)\n";
    } else {
        echo "   ❌ {$table} NOT FOUND\n";
    }
}

echo "\n🎉 Setup completed successfully!\n";
echo "\nYou can now access the system at: backend/admin/iot-estimation/index.php\n";
?>
