<?php

/**
 * Migration 044 – Add TOTP two-factor authentication support
 *
 * Adds totp_secret, totp_enabled, totp_recovery_codes columns to iw_users
 * and a global toggle setting.
 */

use App\Database\Migration;

class AddTotpSupport extends Migration
{
    public function up(): void
    {
        $cols = $this->columnNames('iw_users');

        if (!in_array('totp_secret', $cols, true)) {
            $this->db->query("ALTER TABLE iw_users ADD COLUMN totp_secret VARCHAR(64) NULL DEFAULT NULL AFTER password_hash");
        }
        if (!in_array('totp_enabled', $cols, true)) {
            $this->db->query("ALTER TABLE iw_users ADD COLUMN totp_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER totp_secret");
        }
        if (!in_array('totp_recovery_codes', $cols, true)) {
            $this->db->query("ALTER TABLE iw_users ADD COLUMN totp_recovery_codes TEXT NULL DEFAULT NULL AFTER totp_enabled");
        }

        // Feature toggle (disabled by default – opt-in)
        $exists = $this->db->fetch("SELECT 1 FROM iw_settings WHERE setting_key = 'totp_2fa_available'");
        if (!$exists) {
            $this->db->insert('iw_settings', [
                'setting_key'   => 'totp_2fa_available',
                'setting_value' => '0',
                'setting_group' => 'features',
            ]);
        }
    }

    public function down(): void
    {
        $this->db->query("ALTER TABLE iw_users DROP COLUMN IF EXISTS totp_secret");
        $this->db->query("ALTER TABLE iw_users DROP COLUMN IF EXISTS totp_enabled");
        $this->db->query("ALTER TABLE iw_users DROP COLUMN IF EXISTS totp_recovery_codes");
        $this->db->query("DELETE FROM iw_settings WHERE setting_key = 'totp_2fa_available'");
    }

    private function columnNames(string $table): array
    {
        $rows = $this->db->fetchAll("SHOW COLUMNS FROM {$table}");
        return array_column($rows, 'Field');
    }
}
