<?php

namespace SGC\eGiftCard\Database\Migrations;

defined('ABSPATH') || exit; // Prevent direct file access.

/**
 * Class UserBalanceMigrator
 *
 * Handles the migration of the user_balances table.
 */
class UserBalanceMigrator {

    /**
     * @var string The name of the database table.
     */
    protected static $tableName = 'user_balances';

    /**
     * Migrates the user_balances table.
     *
     * Creates the table if it doesn't exist.
     *
     * @return void
     */
    public static function migrate() {
        global $wpdb;

        // Get the table charset and collation
        $charsetCollate = $wpdb->get_charset_collate();

        // Construct the table name properly
        $table = $wpdb->prefix . static::$tableName;

        // Check if the table already exists
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            // @codingStandardsIgnoreStart
            // SQL to create the table if it doesn't exist
            $sql = "CREATE TABLE {$table} (
                `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                `user_id` BIGINT(20) UNSIGNED NOT NULL,
                `balance` DECIMAL(10,2) NOT NULL DEFAULT 0.00,
                `last_updated` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                `gift_code` VARCHAR(20) DEFAULT NULL,
                `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                PRIMARY KEY (`id`),
                UNIQUE KEY `idx_user_id` (`user_id`)
            ) {$charsetCollate};";
            // @codingStandardsIgnoreEnd
            // Use dbDelta to create or update the table
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
}