-- ============================================================
-- Run this on EACH COMPANY (tenant) database that already
-- existed before the License + Single-Device-Login update.
-- Safe to re-run (uses IF NOT EXISTS / INSERT IGNORE).
--
-- Tip: the Super Admin panel has a "Run Migration on All
-- Companies" button on the dashboard that runs this
-- automatically on every tenant database for you — you don't
-- have to run this by hand unless you prefer to.
-- ============================================================

-- Fixes a pre-existing gap: tab_permissions column was used by
-- the app but was missing from some installs.
ALTER TABLE users
    ADD COLUMN IF NOT EXISTS tab_permissions TEXT NULL AFTER role;

-- Single-device login: only the token stored here is considered
-- the "live" session. A fresh login overwrites it, which
-- immediately invalidates any older session for that user.
ALTER TABLE users
    ADD COLUMN IF NOT EXISTS active_session_token VARCHAR(64) NULL AFTER status,
    ADD COLUMN IF NOT EXISTS last_login_at DATETIME NULL AFTER active_session_token,
    ADD COLUMN IF NOT EXISTS last_login_ip VARCHAR(45) NULL AFTER last_login_at;

-- License count copied into this company's own settings table so
-- the app can check it without needing the master DB on every page.
INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('license_count', '5');
