<?php
/**
 * generate_k2_redirects.php
 *
 * Populates wp_fg_redirect table with 301 redirect entries for all K2 items
 * migrated to WordPress.
 *
 * Joomla K2 URL pattern: /es/[menu]/NNN-alias.html
 * Stored in wp_fg_redirect as: NNN-alias.html
 * FG plugin matches via LIKE '%NNN-alias.html' fallback.
 *
 * Also adds redirects for K2 categories → WP categories.
 *
 * Usage: php generate_k2_redirects.php [--dry-run]
 */

$dry_run = in_array('--dry-run', $argv ?? []);

// DB config - WordPress
$wp_host = 'wordpress-mysql';
$wp_db   = 'wordpress_db';
$wp_user = 'wordpress_user';
$wp_pass = 'wordpress_pass';

// DB config - Joomla
$jm_host = 'joomla-mysql';
$jm_db   = 'joomla_db';
$jm_user = 'joomla_user';
$jm_pass = 'joomla_pass';

$wp_pdo = new PDO("mysql:host=$wp_host;dbname=$wp_db;charset=utf8mb4", $wp_user, $wp_pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$jm_pdo = new PDO("mysql:host=$jm_host;dbname=$jm_db;charset=utf8mb4", $jm_user, $jm_pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

echo "=== Generate K2 Redirects → wp_fg_redirect ===\n";
echo $dry_run ? "[DRY RUN]\n\n" : "[LIVE RUN]\n\n";

// -------------------------------------------------------------------------
// Step 1: Build K2 ID → alias map from Joomla
// -------------------------------------------------------------------------
echo "Loading K2 items from Joomla...\n";
$stmt = $jm_pdo->query("SELECT id, alias FROM ew4r_k2_items WHERE alias != '' AND alias IS NOT NULL");
$k2_aliases = [];
foreach ($stmt as $row) {
    $k2_aliases[(int)$row['id']] = $row['alias'];
}
echo "  K2 items loaded: " . count($k2_aliases) . "\n";

// -------------------------------------------------------------------------
// Step 2: Load WP postmeta: K2 ID → WP post ID
// -------------------------------------------------------------------------
echo "Loading WP postmeta (_fgj2wp_old_k2_id)...\n";
$stmt = $wp_pdo->query("
    SELECT pm.meta_value AS k2_id, pm.post_id AS wp_id
    FROM wp_postmeta pm
    JOIN wp_posts p ON pm.post_id = p.ID
    WHERE pm.meta_key = '_fgj2wp_old_k2_id'
      AND p.post_type = 'post'
");
$k2_to_wp = [];
foreach ($stmt as $row) {
    $k2_to_wp[(int)$row['k2_id']] = (int)$row['wp_id'];
}
echo "  WP posts with K2 ID: " . count($k2_to_wp) . "\n\n";

// -------------------------------------------------------------------------
// Step 3: Check existing redirects to avoid duplicates
// -------------------------------------------------------------------------
echo "Loading existing redirects...\n";
$existing = [];
$stmt = $wp_pdo->query("SELECT old_url FROM wp_fg_redirect");
foreach ($stmt as $row) {
    $existing[$row['old_url']] = true;
}
echo "  Existing entries: " . count($existing) . "\n\n";

// -------------------------------------------------------------------------
// Step 4: Build and insert K2 item redirects
// -------------------------------------------------------------------------
echo "Building K2 item redirects...\n";
$insert = $wp_pdo->prepare("
    INSERT IGNORE INTO wp_fg_redirect (old_url, id, type, activated)
    VALUES (?, ?, 'post', 1)
");

$stats = ['inserted' => 0, 'skipped_no_alias' => 0, 'skipped_no_wp' => 0, 'skipped_exists' => 0];

// Process in batches
$batch = [];
foreach ($k2_to_wp as $k2_id => $wp_id) {
    if (!isset($k2_aliases[$k2_id])) {
        $stats['skipped_no_alias']++;
        continue;
    }
    $alias = $k2_aliases[$k2_id];
    $old_url = $k2_id . '-' . $alias . '.html';

    if (isset($existing[$old_url])) {
        $stats['skipped_exists']++;
        continue;
    }

    $batch[] = [$old_url, $wp_id];
}

echo "  Redirects to insert: " . count($batch) . "\n";

if (!$dry_run) {
    $wp_pdo->beginTransaction();
    try {
        foreach ($batch as [$old_url, $wp_id]) {
            $insert->execute([$old_url, $wp_id]);
            $stats['inserted']++;
            if ($stats['inserted'] % 1000 === 0) {
                echo "  ... {$stats['inserted']} inserted\n";
                $wp_pdo->commit();
                $wp_pdo->beginTransaction();
            }
        }
        $wp_pdo->commit();
    } catch (Exception $e) {
        $wp_pdo->rollBack();
        echo "ERROR: " . $e->getMessage() . "\n";
        exit(1);
    }
} else {
    $stats['inserted'] = count($batch);
    // Show first 5 samples
    echo "\n  Sample entries:\n";
    foreach (array_slice($batch, 0, 5) as [$old_url, $wp_id]) {
        echo "    $old_url → post ID $wp_id\n";
    }
}

// -------------------------------------------------------------------------
// Step 5: K2 category redirects
// -------------------------------------------------------------------------
echo "\nBuilding K2 category redirects...\n";

// Load K2 categories from Joomla
$stmt = $jm_pdo->query("SELECT id, alias FROM ew4r_k2_categories WHERE published=1");
$k2_cats = [];
foreach ($stmt as $row) {
    $k2_cats[(int)$row['id']] = $row['alias'];
}
echo "  K2 categories: " . count($k2_cats) . "\n";

// Load WP term IDs for K2 categories via postmeta equivalent
// FG plugin stores category mapping in wp_term_meta or wp_termmeta
$stmt = $wp_pdo->query("
    SELECT tm.term_id, tm.meta_value AS k2_cat_id
    FROM wp_termmeta tm
    WHERE tm.meta_key = '_fgj2wp_old_k2_category_id'
");
$k2_cat_to_wp = [];
foreach ($stmt as $row) {
    $k2_cat_to_wp[(int)$row['k2_cat_id']] = (int)$row['term_id'];
}
echo "  WP categories with K2 ID: " . count($k2_cat_to_wp) . "\n";

$insert_cat = $wp_pdo->prepare("
    INSERT IGNORE INTO wp_fg_redirect (old_url, id, type, activated)
    VALUES (?, ?, 'category', 1)
");

$cat_inserted = 0;
foreach ($k2_cat_to_wp as $k2_cat_id => $wp_term_id) {
    if (!isset($k2_cats[$k2_cat_id])) continue;
    $alias = $k2_cats[$k2_cat_id];
    // K2 category URL: /es/[alias] or /es/k2-items/[alias]
    $old_url = $alias . '.html';
    if (isset($existing[$old_url])) continue;
    if (!$dry_run) {
        $insert_cat->execute([$old_url, $wp_term_id]);
    }
    $cat_inserted++;
}
echo "  Category redirects: $cat_inserted\n";

// -------------------------------------------------------------------------
// Summary
// -------------------------------------------------------------------------
echo "\n=== Results ===\n";
echo "K2 item redirects inserted: {$stats['inserted']}\n";
echo "Skipped (no alias):         {$stats['skipped_no_alias']}\n";
echo "Skipped (no WP post):       {$stats['skipped_no_wp']}\n";
echo "Skipped (already exists):   {$stats['skipped_exists']}\n";
echo "Category redirects:         $cat_inserted\n";
echo "\nTotal in wp_fg_redirect now:\n";
if (!$dry_run) {
    $count = $wp_pdo->query("SELECT COUNT(*) FROM wp_fg_redirect")->fetchColumn();
    echo "  $count entries\n";
}
echo "\nDone.\n";
