<?php

namespace classes;

/**
 * Ensures additive schema for department-scoped customer price overrides.
 */
class department_customer_price_overrides_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(
            "CREATE TABLE IF NOT EXISTS `department_customer_price_overrides` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `department_id` INT NOT NULL,
                `user_id` INT NOT NULL,
                `is_category` TINYINT(1) NOT NULL DEFAULT 0,
                `product_or_category_id` VARCHAR(191) NOT NULL,
                `percentage` INT NOT NULL DEFAULT 0,
                `fixed_price` INT NULL DEFAULT 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_department_customer_price_overrides_lookup` (`department_id`, `user_id`, `is_category`, `product_or_category_id`),
                KEY `idx_department_customer_price_overrides_department` (`department_id`),
                KEY `idx_department_customer_price_overrides_user` (`user_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );

        self::$initialized = true;
    }
}
