<?php

namespace classes;

/**
 * Ensures additive schema for customer product price overrides.
 */
class price_overrides_schema_bootstrap
{
    private static bool $initialized = false;

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

        global $db;

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

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

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

        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);
    }
}
