<?php

namespace classes;

class limited_backoffice_schema_bootstrap
{
    private static bool $initialized = false;

    public static function ensureTables(): void
    {
        if (self::$initialized) {
            return;
        }

        global $db;

        if (!isset($db) || !is_object($db) || !method_exists($db, 'query')) {
            return;
        }

        $db->query(<<<'SQL'
CREATE TABLE IF NOT EXISTS `limited_backoffice_employees` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_id` INT NOT NULL,
    `managed_group_id` INT NOT NULL,
    `role_key` VARCHAR(64) NOT NULL,
    `department_ids` LONGTEXT NOT NULL,
    `created_by_user_id` INT NOT NULL,
    `updated_by_user_id` INT NULL,
    `deactivated_at` DATETIME NULL,
    `created_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uniq_limited_backoffice_employees_user_id` (`user_id`),
    KEY `idx_limited_backoffice_employees_group_id` (`managed_group_id`),
    KEY `idx_limited_backoffice_employees_role_key` (`role_key`),
    KEY `idx_limited_backoffice_employees_deactivated_at` (`deactivated_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
SQL);

        self::$initialized = true;
    }
}
