<?php

namespace WKO\Model\Migration;

class AddInstallmentDisplayColumn 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->columnExists()) {
            $this->addColumn();
        }
    }

    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(): 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,
            'installment_display'
        );

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

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

        $wpdb->query(
            "ALTER TABLE {$this->table_name}
             ADD COLUMN installment_display TEXT AFTER rule_title"
        );
    }
}
