<?php

/**
 * Create Retention Logs Table
 *
 * Database migration for the retention analytics log table.
 *
 * @package ArraySubs\Features\RetentionAnalytics\Migrations
 * @since 1.9.0
 */

namespace ArraySubs\Features\RetentionAnalytics\Migrations;

defined('ABSPATH') || exit;

/**
 * Creates the retention_logs table using dbDelta
 */
class CreateRetentionLogsTable
{
    /**
     * Run the migration
     *
     * @return void
     */
    public static function up(): void
    {
        global $wpdb;

        $table_name      = $wpdb->prefix . 'arraysubs_retention_logs';
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE {$table_name} (
            id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            subscription_id bigint(20) unsigned NOT NULL DEFAULT 0,
            customer_id bigint(20) unsigned NOT NULL DEFAULT 0,
            customer_name_snapshot varchar(200) NOT NULL DEFAULT '',
            event_type varchar(30) NOT NULL DEFAULT '',
            reason varchar(100) NOT NULL DEFAULT '',
            reason_details text NOT NULL,
            offer_type varchar(50) NOT NULL DEFAULT '',
            offer_data text NOT NULL,
            initiated_by varchar(20) NOT NULL DEFAULT '',
            effective_product_id bigint(20) unsigned NOT NULL DEFAULT 0,
            product_name_snapshot varchar(200) NOT NULL DEFAULT '',
            subscription_age int(11) NOT NULL DEFAULT 0,
            payments_count int(11) NOT NULL DEFAULT 0,
            recurring_amount decimal(19,4) NOT NULL DEFAULT 0,
            currency varchar(10) NOT NULL DEFAULT '',
            created_at datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
            PRIMARY KEY  (id),
            KEY idx_subscription_id (subscription_id),
            KEY idx_customer_id (customer_id),
            KEY idx_event_type (event_type),
            KEY idx_effective_product_id (effective_product_id),
            KEY idx_created_at (created_at)
        ) {$charset_collate};";

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        dbDelta($sql);
    }

    /**
     * Drop the table (for uninstall only)
     *
     * @return void
     */
    public static function down(): void
    {
        global $wpdb;

        $table_name = $wpdb->prefix . 'arraysubs_retention_logs';

        // Table name is constructed from $wpdb->prefix, safe to use directly.
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
        $wpdb->query('DROP TABLE IF EXISTS ' . esc_sql($table_name));
    }

    /**
     * Get the table name
     *
     * @return string
     */
    public static function getTableName(): string
    {
        global $wpdb;
        return $wpdb->prefix . 'arraysubs_retention_logs';
    }
}
