<?php

namespace WKO\Model\Migration;

class AddProductsAndCategoriesColumn extends BaseMigration
{
    private string $table_name;

    public function __construct()
    {
        global $wpdb;
        $this->table_name = $wpdb->prefix . 'wko_installment_rules';
    }

    public function run(): void
    {
        if ($this->tableExists()) {
            $this->addMissingColumns();
        }
    }

    private function tableExists(): bool
    {
        global $wpdb;

        $query = $wpdb->prepare(
            "SELECT COUNT(*)
             FROM information_schema.tables
             WHERE table_schema = %s
             AND table_name = %s",
            $wpdb->dbname,
            $this->table_name
        );

        return (bool) $wpdb->get_var($query);
    }

    private function columnExists(string $columnName): bool
    {
        global $wpdb;

        $query = $wpdb->prepare(
            "SELECT COUNT(*)
             FROM information_schema.columns
             WHERE table_schema = %s
             AND table_name = %s
             AND column_name = %s",
            $wpdb->dbname,
            $this->table_name,
            $columnName
        );

        return (bool) $wpdb->get_var($query);
    }

    private function addMissingColumns(): void
    {
        global $wpdb;

        $columns = [
            'products' => "ADD COLUMN products LONGTEXT AFTER card_brands",
            'brands' => "ADD COLUMN brands LONGTEXT AFTER products",
            'categories' => "ADD COLUMN categories LONGTEXT AFTER brands"
        ];

        foreach ($columns as $columnName => $alterStatement) {
            if (!$this->columnExists($columnName)) {
                $wpdb->query($wpdb->prepare("ALTER TABLE %i {$alterStatement}", $this->table_name));
            }
        }
    }
}
