<?php

namespace SGC\eGiftCard\Database\Migrations;

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

/**
 * Class GiftCodeMigrator
 *
 * Handles the migration of the gift_codes table.
 */
class GiftCodeMigrator {
    
    /**
     * @var string The name of the database table.
     */
    protected static $tableName = 'gift_codes';

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

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

        // Escape 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 query to create the table if it doesn't exist
            $sql = "CREATE TABLE {$table} (
                `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
                `gift_code` VARCHAR(20) NOT NULL,
                `order_id` BIGINT(20) NOT NULL,
                `sender_name` VARCHAR(100) NOT NULL DEFAULT '',
                `recipient_email` VARCHAR(100) NOT NULL DEFAULT '',
                `recipient_name` VARCHAR(100) NOT NULL DEFAULT '',
                `gift_message` VARCHAR(500) NOT NULL DEFAULT '',
                `gift_amount` FLOAT NOT NULL DEFAULT 0,
                `delivery_date` DATE NOT NULL,
                `is_delivered` TINYINT(1) NOT NULL DEFAULT 0,
                `design_url` VARCHAR(255) NOT NULL DEFAULT '',
                `is_redeemed` TINYINT(1) NOT NULL DEFAULT 0,
                `redeemed_by` BIGINT(20) DEFAULT NULL,
                `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
                `expires_at` DATETIME DEFAULT NULL,
                PRIMARY KEY (`id`),
                UNIQUE KEY `gift_code_unique` (`gift_code`)
            ) {$charsetCollate};";
            // @codingStandardsIgnoreEnd

            // Use dbDelta to create or update the table
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
}