<?php
/**
 * Migration: Create Donations Tables
 *
 * Creates all custom tables required by the Donations module.
 *
 * @package AmbassadorHub\Donations\Migrations
 */

namespace AmbassadorHub\Donations\Migrations;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange

/**
 * Creates ambh_donations and ambh_donation_meta tables.
 *
 * Added in plugin 1.0.0.
 */
class CreateTables {

	/**
	 * Run the migration.
	 *
	 * @return void
	 */
	public static function up(): void {
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$charset_collate = $wpdb->get_charset_collate();

		// Donations table — full final schema.
		$donations_table = $wpdb->prefix . 'ambh_donations';
		dbDelta(
			"CREATE TABLE IF NOT EXISTS {$donations_table} (
			id                bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			fundraiser_id     bigint(20) unsigned DEFAULT NULL,
			donor_name        varchar(255)        NOT NULL DEFAULT '',
			donor_first_name  varchar(100)        DEFAULT NULL,
			donor_middle_name varchar(100)        DEFAULT NULL,
			donor_last_name   varchar(100)        DEFAULT NULL,
			donor_email       varchar(255)        NOT NULL DEFAULT '',
			amount            decimal(10,2)       NOT NULL,
			currency          varchar(3)          NOT NULL DEFAULT 'EUR',
			status            varchar(20)         NOT NULL DEFAULT 'pending',
			transaction_id    varchar(255)        DEFAULT NULL,
			notes             text                DEFAULT NULL,
			message           text                DEFAULT NULL,
			is_anonymous      tinyint(1)          NOT NULL DEFAULT 0,
			created_at        datetime            NOT NULL,
			updated_at        datetime            NOT NULL,
			PRIMARY KEY  (id),
			KEY fundraiser_id (fundraiser_id),
			KEY donor_email (donor_email),
			KEY status (status),
			KEY created_at (created_at)
		) {$charset_collate};"
		);

		// Donation meta table — mirrors WordPress postmeta structure.
		$meta_table = $wpdb->prefix . 'ambh_donation_meta';
		dbDelta(
			"CREATE TABLE IF NOT EXISTS {$meta_table} (
			meta_id     bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			donation_id bigint(20) unsigned NOT NULL DEFAULT 0,
			meta_key    varchar(255)        NOT NULL DEFAULT '',
			meta_value  longtext,
			PRIMARY KEY  (meta_id),
			KEY donation_id (donation_id),
			KEY meta_key    (meta_key(191))
		) {$charset_collate};"
		);
	}
}
