<?php
/**
 * Add action and description columns to Points Table.
 *
 * @package Ugcify\Database\Migrations
 */

namespace Ugcify\Database\Migrations;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * AddActionToPointsTable migration class.
 */
class AddActionToPointsTable {

	/**
	 * WordPress database instance.
	 *
	 * @var \wpdb
	 */
	private $wpdb;

	/**
	 * Constructor.
	 *
	 * @param \wpdb $wpdb WordPress database instance.
	 */
	public function __construct( \wpdb $wpdb ) {
		$this->wpdb = $wpdb;
	}

	/**
	 * Run migration.
	 *
	 * Adds columns only when they do not already exist, compatible with
	 * MySQL 5.7+ (ADD COLUMN IF NOT EXISTS is MySQL 8.0.3+ / MariaDB only).
	 *
	 * @return void
	 */
	public function run(): void {
		$table = $this->wpdb->prefix . 'ugcify_points';

		foreach ( array( 'action', 'description' ) as $column ) {
			// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Schema migration; table name is a trusted internal constant.
			$exists = $this->wpdb->get_var(
				$this->wpdb->prepare(
					'SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = %s',
					$table,
					$column
				)
			);
			// phpcs:enable

			if ( $exists ) {
				continue;
			}

			if ( 'action' === $column ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- DDL migration; table name is a trusted internal constant.
				$this->wpdb->query( "ALTER TABLE {$table} ADD COLUMN action VARCHAR(64) NOT NULL DEFAULT 'manual' AFTER points" );
			} elseif ( 'description' === $column ) {
				// phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedNotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- DDL migration; table name is a trusted internal constant.
				$this->wpdb->query( "ALTER TABLE {$table} ADD COLUMN description VARCHAR(255) NOT NULL DEFAULT '' AFTER action" );
			}
		}
	}
}
