<?php
/**
 * Manual Migration Script for Scheduled Invoices
 *
 * Run this script via WordPress admin or WP-CLI:
 * - Via browser: http://yoursite.com/wp-admin/?run_migration=1
 * - Via WP-CLI: wp-cli eval-file run_scheduled_migration.php
 */

if (!defined('ABSPATH')) {
    // Assume we're in WordPress context
    require_once dirname(__FILE__) . '/../../bedrock/wp-load.php';
}

// Run only if triggered by admin
if (isset($_GET['run_migration']) && current_user_can('manage_options')) {
    global $wpdb;

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

    $results = [];

    // 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");
        $results[] = "✓ Added scheduled_for column";
    } else {
        $results[] = "- scheduled_for column already exists";
    }

    // 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");
        $results[] = "✓ Added scheduled_for_local column";
    } else {
        $results[] = "- scheduled_for_local column already exists";
    }

    // 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");
        $results[] = "✓ Added scheduled_timezone column";
    } else {
        $results[] = "- scheduled_timezone column already exists";
    }

    // 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");
        $results[] = "✓ Added allowed_actions column";
    } else {
        $results[] = "- allowed_actions column already exists";
    }

    // Add index on scheduled_for
    $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)");
        $results[] = "✓ Added idx_scheduled_for index";
    } else {
        $results[] = "- idx_scheduled_for index already exists";
    }

    // Verify the changes
    $columns = $wpdb->get_col("SHOW COLUMNS FROM {$table_name} LIKE 'scheduled%'");
    $results[] = "✓ Migration completed successfully!";
    $results[] = "Scheduled columns now present: " . implode(', ', $columns);

    // Display results
    echo '<h2>Scheduled Invoices Migration</h2>';
    echo '<ul>';
    foreach ($results as $result) {
        echo '<li>' . esc_html($result) . '</li>';
    }
    echo '</ul>';
    echo '<p><a href="' . admin_url('admin.php?page=cloudxm-nfe') . '">Back to NFE Invoices</a></p>';
    exit;
}

// If not triggered, add admin menu item
add_action('admin_menu', function() {
    add_submenu_page(
        null, // Parent slug (hidden)
        'Run Migration',
        'Run Scheduled Migration',
        'manage_options',
        'cloudxm_nfe_run_migration',
        '',
        admin_url('admin.php?page=cloudxm-nfe&run_migration=1')
    );
});

add_action('admin_head', function() {
    if (isset($_GET['run_migration'])) {
        ?>
        <style>
            body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif; padding: 20px; }
            h2 { color: #2271b1; }
            ul { list-style: none; padding: 0; }
            li { padding: 8px 0; border-bottom: 1px solid #eee; }
            li:first-child { border-top: 1px solid #eee; }
        </style>
        <?php
    }
});
