-- ============================================================
-- migration_feature_flags.sql
-- ============================================================
-- Adds per-organization feature gating: lets the vendor turn a new
-- feature on for ONE organization (e.g. Company A asked for it) without
-- it showing up for every other organization (Company B, C, ...).
--
-- Two tables:
--   feature_flags          catalog of features that exist in the app,
--                           with a default on/off for organizations
--                           that don't have an explicit override yet.
--   organization_features  the actual per-organization on/off switch.
--
-- Managed from the vendor console: modules/companies/index.php
-- ("Feature Flags" card). Checked in PHP via hasFeature('key') /
-- requireFeature('key') / orgHasFeature($db,$orgId,'key') — see
-- includes/functions.php.
--
-- Run this once against your existing database:
--   mysql -u <user> -p <database_name> < migration_feature_flags.sql
-- ============================================================

CREATE TABLE IF NOT EXISTS feature_flags (
    id                  INT AUTO_INCREMENT PRIMARY KEY,
    feature_key         VARCHAR(60) UNIQUE NOT NULL,
    name                VARCHAR(150) NOT NULL,
    description         VARCHAR(500) NULL,
    is_default_enabled  TINYINT(1) DEFAULT 0,
    created_at          DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS organization_features (
    id               INT AUTO_INCREMENT PRIMARY KEY,
    organization_id  INT NOT NULL,
    feature_key      VARCHAR(60) NOT NULL,
    is_enabled       TINYINT(1) DEFAULT 1,
    updated_at       DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_org_feature (organization_id, feature_key),
    FOREIGN KEY (organization_id) REFERENCES organizations(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE INDEX idx_org_features_org ON organization_features(organization_id);

-- Example seed row — delete this once you've created your own real
-- feature flags from the vendor console. Left OFF by default, which is
-- normally what you want: create it, then flip it on for just the one
-- organization that asked for it.
INSERT IGNORE INTO feature_flags (feature_key, name, description, is_default_enabled)
VALUES ('sample_feature', 'Sample Feature', 'Example flag — replace with a real feature, or delete this row.', 0);
