<?php
/**
 * Migration: Add Scheduled Fields to NFe Emissions Table
 *
 * Adds fields for supporting scheduled invoice functionality:
 * - scheduled_for: UTC datetime for scheduled emission
 * - scheduled_for_local: Local datetime for display
 * - scheduled_timezone: Timezone identifier
 * - allowed_actions: JSON array of available actions from API
 *
 * @package CloudXM\NFe\Persistence\Migrations
 * @since 2.1.0
 */

declare(strict_types=1);

namespace CloudXM\NFe\Persistence\Migrations;

use CloudXM\SDK\Support\HasLogger;
use CloudXM\SDK\Contracts\MigrationInterface;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Migration: Add Scheduled Fields
 */
class AddScheduledFields implements MigrationInterface
{
    use HasLogger;

    private string $table_prefix;

    /**
     * Constructor
     */
    public function __construct(string $table_prefix)
    {
        $this->table_prefix = $table_prefix;
    }

    /**
     * Run migration
     */
    public function run(): bool
    {
        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . $this->table_prefix . 'emissions';

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

        // Add scheduled_for column
        $column_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND COLUMN_NAME = 'scheduled_for'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name}
                 ADD COLUMN scheduled_for datetime DEFAULT NULL"
            );
        }

        // Add scheduled_for_local column
        $column_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND COLUMN_NAME = 'scheduled_for_local'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name}
                 ADD COLUMN scheduled_for_local datetime DEFAULT NULL"
            );
        }

        // Add scheduled_timezone column
        $column_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND COLUMN_NAME = 'scheduled_timezone'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name}
                 ADD COLUMN scheduled_timezone varchar(50) DEFAULT NULL"
            );
        }

        // Add allowed_actions column
        $column_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND COLUMN_NAME = 'allowed_actions'",
                $table_name
            )
        );

        if (!$column_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name}
                 ADD COLUMN allowed_actions json DEFAULT NULL"
            );
        }

        // Add index on scheduled_for for better query performance
        $index_exists = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
                 WHERE TABLE_SCHEMA = DATABASE()
                 AND TABLE_NAME = %s
                 AND INDEX_NAME = 'idx_scheduled_for'",
                $table_name
            )
        );

        if (!$index_exists) {
            $wpdb->query(
                "ALTER TABLE {$table_name}
                 ADD INDEX idx_scheduled_for (scheduled_for)"
            );
        }

        $this->log()->debug('nfe.migration_completed', [
            'migration' => '005_add_scheduled_fields',
            'version' => '2.1.0',
            'operation' => 'add_scheduled_fields',
            'table' => $table_name,
            'columns' => ['scheduled_for', 'scheduled_for_local', 'scheduled_timezone', 'allowed_actions'],
            'timing' => date('Y-m-d H:i:s')
        ]);

        return true;
    }

    /**
     * Rollback migration
     */
    public function rollback(): bool
    {
        global $wpdb;

        $table_name = $wpdb->prefix . $this->table_prefix . 'emissions';

        // Remove columns
        $wpdb->query("ALTER TABLE {$table_name} DROP COLUMN scheduled_for");
        $wpdb->query("ALTER TABLE {$table_name} DROP COLUMN scheduled_for_local");
        $wpdb->query("ALTER TABLE {$table_name} DROP COLUMN scheduled_timezone");
        $wpdb->query("ALTER TABLE {$table_name} DROP COLUMN allowed_actions");

        // Remove index
        $wpdb->query("ALTER TABLE {$table_name} DROP INDEX idx_scheduled_for");

        $this->log()->debug('nfe.migration_rolled_back', [
            'migration' => '005_add_scheduled_fields',
            'operation' => 'drop_scheduled_fields'
        ]);

        return true;
    }

    /**
     * Get migration description
     */
    public function getDescription(): string
    {
        return 'Add scheduled invoice fields: scheduled_for, scheduled_for_local, scheduled_timezone, allowed_actions';
    }

    /**
     * Get migration version
     */
    public function getVersion(): string
    {
        return '2.1.0';
    }
}
