<?php

namespace classes;

/**
 * Ensures additive schema for product metadata used outside the core product form.
 */
class products_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;
        }

        if (!self::tableExists($db, 'products')) {
            return;
        }

        if (!self::columnExists($db, 'products', 'max_quantity_per_order')) {
            $db->query(
                "ALTER TABLE products
                    ADD COLUMN max_quantity_per_order INT NULL DEFAULT NULL
                    AFTER order_priority"
            );
        }

        self::$initialized = true;
    }

    private static function tableExists(object $db, string $table): bool
    {
        $table = self::escapeIdentifier($table);
        $result = $db->query("SHOW TABLES LIKE '{$table}'");

        if ($result === false || !is_object($result) || !property_exists($result, 'num_rows')) {
            return false;
        }

        return (int)$result->num_rows > 0;
    }

    private static function columnExists(object $db, string $table, string $column): bool
    {
        $table = self::escapeIdentifier($table);
        $column = self::escapeIdentifier($column);
        $result = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");

        if ($result === false || !is_object($result) || !property_exists($result, 'num_rows')) {
            return false;
        }

        return (int)$result->num_rows > 0;
    }

    private static function escapeIdentifier(string $value): string
    {
        return str_replace(['\\', "'", '`'], ['\\\\', "\\'", ''], $value);
    }
}
