<?php

namespace classes;

class subusers_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;
        }

        self::ensureColumn(
            'subuser_grants',
            'assigned_vehicle_id',
            'INT NULL AFTER `subuser`'
        );
        self::ensureIndex(
            'subuser_grants',
            'idx_subuser_grants_assigned_vehicle_id',
            '`assigned_vehicle_id`'
        );
        self::ensureColumn(
            'subusers',
            'phone_verified_at',
            'DATETIME NULL AFTER `phone`'
        );
        self::ensureColumn(
            'subusers',
            'email_verified_at',
            'DATETIME NULL AFTER `email`'
        );

        self::$initialized = true;
    }

    private static function ensureColumn(string $table, string $column, string $definition): void
    {
        global $db;

        $table = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
        $column = preg_replace('/[^a-zA-Z0-9_]/', '', $column);
        if ($table === '' || $column === '') {
            return;
        }

        $columnSql = $db->escape_string($column);
        $result = $db->query("SHOW COLUMNS FROM `$table` LIKE '$columnSql'");
        if ($result !== false && $result->num_rows > 0) {
            return;
        }

        $db->query("ALTER TABLE `$table` ADD COLUMN `$column` $definition");
    }

    private static function ensureIndex(string $table, string $index, string $columns): void
    {
        global $db;

        $table = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
        $index = preg_replace('/[^a-zA-Z0-9_]/', '', $index);
        if ($table === '' || $index === '') {
            return;
        }

        $indexSql = $db->escape_string($index);
        $result = $db->query("SHOW INDEX FROM `$table` WHERE Key_name = '$indexSql'");
        if ($result !== false && $result->num_rows > 0) {
            return;
        }

        $db->query("ALTER TABLE `$table` ADD INDEX `$index` ($columns)");
    }
}
