<?php
$db = new SQLite3(__DIR__ . '/mac_users.db');
$columns = [];
$res = $db->query('PRAGMA table_info(mac_auth)');
while ($row = $res->fetchArray(SQLITE3_ASSOC)) { $columns[] = $row['name']; }
if (!in_array('portal_slot', $columns)) { $db->exec('ALTER TABLE mac_auth ADD COLUMN portal_slot INTEGER NOT NULL DEFAULT 1'); }
$schema = $db->querySingle("SELECT sql FROM sqlite_master WHERE type='table' AND name='mac_auth'");
if (stripos((string)$schema, 'UNIQUE(mac_address, portal_slot)') === false) {
    $db->exec('BEGIN TRANSACTION');
    $db->exec('ALTER TABLE mac_auth RENAME TO mac_auth_old');
    $db->exec("CREATE TABLE mac_auth (id INTEGER PRIMARY KEY AUTOINCREMENT, mac_address TEXT NOT NULL, portal_slot INTEGER NOT NULL DEFAULT 1, username TEXT NOT NULL, password TEXT NOT NULL, status TEXT DEFAULT 'ACTIVE', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, last_access DATETIME, notes TEXT, UNIQUE(mac_address, portal_slot))");
    $db->exec("INSERT OR IGNORE INTO mac_auth (id, mac_address, portal_slot, username, password, status, created_at, last_access, notes) SELECT id, mac_address, COALESCE(portal_slot, 1), username, password, COALESCE(status, 'ACTIVE'), created_at, last_access, notes FROM mac_auth_old");
    $db->exec('DROP TABLE mac_auth_old');
    $db->exec('COMMIT');
}
$db->exec('CREATE INDEX IF NOT EXISTS idx_mac_auth_mac ON mac_auth(mac_address)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_mac_auth_status ON mac_auth(status)');
$db->exec('CREATE INDEX IF NOT EXISTS idx_mac_auth_portal_slot ON mac_auth(portal_slot)');
echo 'OK - Database MAC multi-portale aggiornato';
?>
