<?php
/**
 * إضافة tenant_id لجدولي devices و device_tests
 */
$config = require __DIR__ . '/../config/config.php';
$pdo = new PDO(
    'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8mb4',
    $config['db']['user'],
    $config['db']['pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

foreach (['devices', 'device_tests'] as $table) {
    try {
        $pdo->exec("ALTER TABLE $table ADD COLUMN tenant_id INT NOT NULL DEFAULT 1");
        echo "Added tenant_id to $table\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate column') === false) {
            echo "Warning $table: " . $e->getMessage() . "\n";
        }
    }
}

try {
    $pdo->exec("UPDATE devices SET tenant_id = 1 WHERE tenant_id = 0 OR tenant_id IS NULL");
    $pdo->exec("UPDATE device_tests SET tenant_id = 1 WHERE tenant_id = 0 OR tenant_id IS NULL");
} catch (PDOException $e) {
    // الجداول قد لا تكون موجودة
}
echo "Done.\n";
