import subprocess

# Step 1: Tambah tabel device di database via PHP
php_code = '''<?php
require_once '/home/caracuanbiz/public_html/ict.offshoreai.biz.id/fgdash/config.php';
$db = getDB();

// Tambah tabel devices
$db->exec("
CREATE TABLE IF NOT EXISTS fg_user_devices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    device_hash VARCHAR(64) NOT NULL,
    device_name VARCHAR(200),
    ip_address VARCHAR(45),
    first_seen DATETIME DEFAULT CURRENT_TIMESTAMP,
    last_seen DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    is_active TINYINT(1) DEFAULT 1,
    UNIQUE KEY unique_user_device (user_id, device_hash),
    FOREIGN KEY (user_id) REFERENCES fg_users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Tambah kolom max_devices ke fg_users jika belum ada
try {
    $db->exec("ALTER TABLE fg_users ADD COLUMN max_devices INT DEFAULT 2");
    echo "Column max_devices added\\n";
} catch(Exception $e) {
    echo "Column max_devices already exists\\n";
}

echo "Tables OK\\n";
?>'''

with open('/tmp/migrate_devices.php', 'w') as f:
    f.write(php_code)

result = subprocess.run(['php', '/tmp/migrate_devices.php'], capture_output=True, text=True)
print(result.stdout)
if result.stderr: print("ERR:", result.stderr[:200])

print("DB migration done")
