<?php

use App\Database\Migration;

/**
 * Migration 016 – Add version field to iw_downloads (Phase 8b)
 *
 * Adds a simple version string (e.g. "1.0.4", "v2.1") per download.
 *
 * MySQL/MariaDB compatible:
 *   ALTER TABLE … ADD COLUMN IF NOT EXISTS is MariaDB-only.
 *   This migration uses an information_schema check instead, which
 *   works on MySQL 5.7+ and MariaDB 10.3+ alike.
 *
 * Safe re-run: skipped silently if the column already exists.
 * Backward-compatible: NULL means no version set (existing downloads unaffected).
 */
class AddVersionToDownloads extends Migration
{
    public function up(): void
    {
        // MySQL-compatible existence check via information_schema
        $exists = (int) $this->db->fetchColumn(
            "SELECT COUNT(*)
             FROM   information_schema.COLUMNS
             WHERE  TABLE_SCHEMA = DATABASE()
               AND  TABLE_NAME   = 'iw_downloads'
               AND  COLUMN_NAME  = 'version'"
        );

        if ($exists === 0) {
            $this->db->query(
                "ALTER TABLE iw_downloads
                 ADD COLUMN version VARCHAR(50) DEFAULT NULL AFTER excerpt"
            );
        }
    }

    public function down(): void
    {
        // MySQL-compatible existence check for rollback as well
        $exists = (int) $this->db->fetchColumn(
            "SELECT COUNT(*)
             FROM   information_schema.COLUMNS
             WHERE  TABLE_SCHEMA = DATABASE()
               AND  TABLE_NAME   = 'iw_downloads'
               AND  COLUMN_NAME  = 'version'"
        );

        if ($exists > 0) {
            $this->db->query(
                "ALTER TABLE iw_downloads DROP COLUMN version"
            );
        }
    }
}
