<?php
/**
 * Deploy Runner — HTTP-triggered migration executor
 * Usage:  https://site.com/wp-content/themes/dekart/deploy-runner.php?migrate=003
 * 
 * Self-destructs after execution (renames to .done).
 * Requires wp-config.php for DB credentials.
 */

// Prevent WordPress from intercepting
define('WP_USE_THEMES', false);

$allowed_migrations = ['003', '004'];

$migrate = isset($_GET['migrate']) ? $_GET['migrate'] : '';

if (!in_array($migrate, $allowed_migrations)) {
    header('Content-Type: text/plain');
    die("Usage: ?migrate=003 (allowed: " . implode(', ', $allowed_migrations) . ")\n");
}

// Load WordPress config for DB credentials
$wp_config_path = dirname(__FILE__) . '/../../../wp-config.php';
if (!file_exists($wp_config_path)) {
    // Try parent directory
    $wp_config_path = dirname(__FILE__) . '/../../wp-config.php';
}
if (!file_exists($wp_config_path)) {
    $wp_config_path = dirname(__FILE__) . '/../wp-config.php';
}

require_once $wp_config_path;

header('Content-Type: text/plain; charset=utf-8');
echo "=== Deploy Runner: migration $migrate ===\n\n";

// ─── Shared helpers ──────────────────────────────────────────────────
function dp_get_wpdb() {
    $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (!$conn) {
        die("DB connection failed: " . mysqli_connect_error() . "\n");
    }
    echo "Connected to DB: " . DB_NAME . "\n";
    return $conn;
}

function dp_get_theme_dir() {
    // Our deploy-runner lives in the theme root
    $theme_dir = dirname(__FILE__);
    echo "Theme dir: {$theme_dir}\n";
    return $theme_dir;
}

if ($migrate === '003') {
    // Fix banner_text typo: rарантированная → гарантированная
    $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
    if (!$conn) {
        die("DB connection failed: " . mysqli_connect_error() . "\n");
    }
    echo "Connected to DB: " . DB_NAME . "\n\n";

    $post_id = 2;
    $meta_keys = ['_banner_text', 'banner_text'];
    $fixed = 0;

    foreach ($meta_keys as $meta_key) {
        $res = mysqli_query($conn, 
            "SELECT meta_id, meta_value FROM wp_postmeta WHERE post_id = $post_id AND meta_key = '$meta_key'");
        
        while ($row = mysqli_fetch_assoc($res)) {
            $old_val = $row['meta_value'];
            $new_val = str_replace('rарантированная', 'гарантированная', $old_val);
            $new_val = str_replace('rантированная', 'гантированная', $new_val);
            
            if ($new_val !== $old_val) {
                $meta_id = (int)$row['meta_id'];
                $escaped = mysqli_real_escape_string($conn, $new_val);
                mysqli_query($conn, 
                    "UPDATE wp_postmeta SET meta_value = '$escaped' WHERE meta_id = $meta_id");
                echo "✅ FIXED meta_id=$meta_key key=$meta_key\n";
                echo "   OLD: $old_val\n";
                echo "   NEW: $new_val\n\n";
                $fixed++;
            }
        }
    }

    if ($fixed === 0) {
        echo "✅ Nothing to fix — typo already corrected\n";
    }

    echo "\nTotal meta values updated: $fixed\n";
    mysqli_close($conn);
}

if ($migrate === '004') {
    // ─── 004a: Remove post 740 (custom-css-js orphan) ───
    $conn = dp_get_wpdb();

    $post_740 = mysqli_query($conn, "SELECT ID FROM wp_posts WHERE ID = 740 AND post_type = 'custom-css-js'");
    if (mysqli_num_rows($post_740) > 0) {
        // Hard-delete post + meta
        mysqli_query($conn, "DELETE FROM wp_posts WHERE ID = 740");
        mysqli_query($conn, "DELETE FROM wp_postmeta WHERE post_id = 740");
        echo "✅ DELETED post ID 740 (custom-css-js)\n";

        // Remove physical file if exists
        $theme_dir = dp_get_theme_dir();
        $upload_dir = dirname(dirname($theme_dir)) . '/uploads';
        $files_to_check = [
            $upload_dir . '/custom-css-js/740.css',
            $upload_dir . '/custom-css-js/740.min.css',
        ];
        foreach ($files_to_check as $file) {
            if (file_exists($file)) {
                unlink($file);
                echo "✅ DELETED file: {$file}\n";
            }
        }
    } else {
        echo "ℹ️  Post ID 740 not found — already removed\n";
    }

    // ─── 004b: Clean wp_custom_css option ───
    // We need wp-load.php for get_option/update_option
    $wp_load = dirname(__FILE__) . '/../../../wp-load.php';
    if (!file_exists($wp_load)) {
        $wp_load = dirname(__FILE__) . '/../../wp-load.php';
    }
    if (file_exists($wp_load)) {
        require_once $wp_load;
        echo "✅ Loaded WordPress\n";

        $option_name = 'wp_custom_css';
        $current = get_option($option_name, '');
        if (!empty($current)) {
            $before = strlen($current);
            $cleaned = preg_replace('/\.(pksh|ms-|ms-text-)[^}]+}\s*/', '', $current);
            $cleaned = preg_replace('/\.(pksh|ms-|ms-text-)[^{]*\{\s*\}\s*/', '', $cleaned);
            $cleaned = trim($cleaned);
            $after = strlen($cleaned);
            $diff = $before - $after;

            if ($diff > 0) {
                update_option($option_name, $cleaned);
                echo "✅ wp_custom_css: {$before} → {$after} chars (removed {$diff})\n";
            } else {
                echo "ℹ️  wp_custom_css unchanged ({$before} chars)\n";
            }
        } else {
            echo "ℹ️  wp_custom_css option is empty\n";
        }

        if (function_exists('opcache_reset')) {
            opcache_reset();
            echo "✅ OPcache reset\n";
        }
    } else {
        echo "⚠️  wp-load.php not found — skipping wp_custom_css cleanup\n";
    }

    mysqli_close($conn);
}

echo "\n=== Migration complete ===\n";

// Self-destruct: rename this file
$self = __FILE__;
$done = $self . '.done';
rename($self, $done);
echo "Self-destruct: renamed to " . basename($done) . "\n";
