<?php
/**
 * نظام الترحيل المُصحّح v2.0
 * نقل البيانات من supehgku_Packagemaker إلى supehgku_test0
 * التاريخ: 25 أكتوبر 2025
 */

// ====== الإعدادات ======
$CONFIG = [
    'source' => [
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'supehgku_Packagemaker'
    ],
    'target' => [
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'supehgku_test0'
    ],
    'dry_run' => true  // true = اختبار، false = تنفيذ حقيقي
];

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ====== الاتصال ======
try {
    $src = new PDO(
        "mysql:host={$CONFIG['source']['host']};dbname={$CONFIG['source']['database']};charset=utf8mb4",
        $CONFIG['source']['username'],
        $CONFIG['source']['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    echo "✅ اتصال بالمصدر: {$CONFIG['source']['database']}\n";
    
    $tgt = new PDO(
        "mysql:host={$CONFIG['target']['host']};dbname={$CONFIG['target']['database']};charset=utf8mb4",
        $CONFIG['target']['username'],
        $CONFIG['target']['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    echo "✅ اتصال بالهدف: {$CONFIG['target']['database']}\n\n";
    
} catch (PDOException $e) {
    die("❌ فشل الاتصال: " . $e->getMessage() . "\n");
}

$dryRun = $CONFIG['dry_run'];
$stats = ['migrated' => 0, 'skipped' => 0, 'errors' => 0];

echo "الوضع: " . ($dryRun ? "🧪 DRY RUN (اختبار)\n\n" : "⚡ LIVE (تنفيذ حقيقي)\n\n");

// ====== المرحلة 0: التحضير ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "📋 المرحلة 0: التحضير\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

// التحقق من المجموعة الافتراضية
$stmt = $tgt->query("SELECT id FROM account_groups WHERE id = 1");
if (!$stmt->fetch()) {
    echo "⚠️ المجموعة الافتراضية غير موجودة\n";
    if (!$dryRun) {
        $tgt->exec("INSERT INTO account_groups (id, group_name, description, is_default, locked, active) 
                    VALUES (1, 'default', 'المجموعة العامة', 1, 1, 1)");
        echo "✅ تم إنشاء المجموعة الافتراضية\n";
    } else {
        echo "🧪 [DRY RUN] سيتم إنشاء المجموعة\n";
    }
} else {
    echo "✅ المجموعة الافتراضية موجودة\n";
}

if (!$dryRun) {
    $tgt->exec("SET FOREIGN_KEY_CHECKS=0");
    echo "🔓 تم تعطيل Foreign Keys\n";
}
echo "\n";

// ====== المرحلة 1: البيانات الأساسية ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "📦 المرحلة 1: البيانات الأساسية\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

// 1.1 sub_bots
echo "🤖 sub_bots\n";
$count = $src->query("SELECT COUNT(*) FROM sub_bots")->fetchColumn();
echo "   المصدر: $count بوت\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم نقل $count بوت\n";
    $stats['migrated'] += $count;
} else {
    $stmt = $src->query("SELECT id, label, bot_token, channel_id, max_users, is_paused, welcome_message, created_at, updated_at FROM sub_bots");
    $insertStmt = $tgt->prepare("INSERT IGNORE INTO sub_bots (id, label, bot_token, channel_id, max_users, is_paused, force_subscription, welcome_message, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)");
    
    $migrated = 0;
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $insertStmt->execute($row);
        if ($insertStmt->rowCount() > 0) $migrated++;
    }
    echo "   ✅ $migrated منقول\n";
    $stats['migrated'] += $migrated;
}

// 1.2 steam_accounts
echo "💎 steam_accounts\n";
$count = $src->query("SELECT COUNT(*) FROM steam_accounts")->fetchColumn();
echo "   المصدر: $count حساب\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم نقل $count حساب\n";
    $stats['migrated'] += $count;
} else {
    $tgt->exec("INSERT IGNORE INTO steam_accounts SELECT * FROM {$CONFIG['source']['database']}.steam_accounts");
    $migrated = $tgt->query("SELECT COUNT(*) FROM steam_accounts")->fetchColumn();
    echo "   ✅ $migrated منقول\n";
    $stats['migrated'] += $migrated;
}

// 1.3 allowed_users
echo "👥 allowed_users\n";
$count = $src->query("SELECT COUNT(*) FROM allowed_users")->fetchColumn();
echo "   المصدر: $count مستخدم\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم نقل $count مستخدم\n";
    $stats['migrated'] += $count;
} else {
    $tgt->exec("INSERT IGNORE INTO allowed_users SELECT * FROM {$CONFIG['source']['database']}.allowed_users");
    $migrated = $tgt->query("SELECT ROW_COUNT()")->fetchColumn();
    echo "   ✅ $migrated منقول\n";
    $stats['migrated'] += $migrated;
}

// 1.4 message_templates
echo "📝 message_templates\n";
$count = $src->query("SELECT COUNT(*) FROM message_templates")->fetchColumn();
echo "   المصدر: $count قالب\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم دمج $count قالب\n";
    $stats['migrated'] += $count;
} else {
    $stmt = $src->query("SELECT `key`, text FROM message_templates");
    $insertStmt = $tgt->prepare("INSERT INTO message_templates (`key`, text) VALUES (?, ?) ON DUPLICATE KEY UPDATE text = VALUES(text)");
    $merged = 0;
    while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
        $insertStmt->execute($row);
        $merged++;
    }
    echo "   ✅ $merged مدمج\n";
    $stats['migrated'] += $merged;
}

// 1.5 control_sessions
echo "🔄 control_sessions\n";
$count = $src->query("SELECT COUNT(*) FROM control_sessions")->fetchColumn();
echo "   المصدر: $count جلسة\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم نقل $count جلسة\n";
    $stats['migrated'] += $count;
} else {
    $tgt->exec("INSERT IGNORE INTO control_sessions SELECT * FROM {$CONFIG['source']['database']}.control_sessions");
    echo "   ✅ $count منقول\n";
    $stats['migrated'] += $count;
}

echo "\n";

// ====== المرحلة 2: daily_attempts → limits_bot ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "⚙️ المرحلة 2: نقل daily_attempts إلى limits_bot\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

$stmt = $src->query("SELECT label, daily_attempts FROM sub_bots");
$bots = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "   المصدر: " . count($bots) . " بوت\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم نقل daily_attempts\n";
    foreach ($bots as $bot) {
        $daily = $bot['daily_attempts'] ?? 2;
        echo "      - {$bot['label']}: $daily/يوم\n";
    }
} else {
    $insertStmt = $tgt->prepare("INSERT INTO limits_bot (bot_label, mode, per_day, per_week, per_month, ban_duration) VALUES (?, 'daily', ?, ?, ?, 1) ON DUPLICATE KEY UPDATE per_day=VALUES(per_day), per_week=VALUES(per_week), per_month=VALUES(per_month)");
    
    $migrated = 0;
    foreach ($bots as $bot) {
        $daily = $bot['daily_attempts'] ?? 2;
        $weekly = $daily * 7;
        $monthly = $daily * 30;
        $insertStmt->execute([$bot['label'], $daily, $weekly, $monthly]);
        $migrated++;
        echo "   ✓ {$bot['label']}: $daily/يوم\n";
    }
    echo "   ✅ تم نقل $migrated بوت\n";
}

echo "\n";

// ====== المرحلة 3: الربط ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "🔗 المرحلة 3: ربط العلاقات\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

// الحسابات
echo "🔗 ربط الحسابات بالمجموعة الافتراضية\n";
$count = $tgt->query("SELECT COUNT(*) FROM steam_accounts")->fetchColumn();

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم ربط $count حساب\n";
} else {
    $tgt->exec("INSERT IGNORE INTO group_accounts (group_id, account_id) SELECT 1, id FROM steam_accounts");
    $linked = $tgt->query("SELECT COUNT(*) FROM group_accounts WHERE group_id=1")->fetchColumn();
    echo "   ✅ $linked حساب مربوط\n";
}

// البوتات
echo "🔗 ربط البوتات بالمجموعة الافتراضية\n";
$count = $tgt->query("SELECT COUNT(*) FROM sub_bots")->fetchColumn();

if ($dryRun) {
    echo "   🧪 [DRY RUN] سيتم ربط $count بوت\n";
} else {
    $tgt->exec("INSERT IGNORE INTO bot_groups (bot_id, group_id) SELECT id, 1 FROM sub_bots");
    $linked = $tgt->query("SELECT COUNT(*) FROM bot_groups WHERE group_id=1")->fetchColumn();
    echo "   ✅ $linked بوت مربوط\n";
}

echo "\n";

// ====== المرحلة 4: التنظيف ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "🧹 المرحلة 4: التنظيف\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";

if ($dryRun) {
    echo "   🧪 [DRY RUN] تخطي التنظيف\n";
} else {
    $tgt->exec("SET FOREIGN_KEY_CHECKS=1");
    echo "   ✅ تم إعادة Foreign Keys\n";
    
    // تحديث AUTO_INCREMENT
    foreach (['sub_bots', 'steam_accounts', 'allowed_users', 'control_sessions'] as $table) {
        $max = $tgt->query("SELECT MAX(id) FROM $table")->fetchColumn();
        if ($max) {
            $tgt->exec("ALTER TABLE $table AUTO_INCREMENT = " . ($max + 1));
            echo "   ✓ $table: AUTO_INCREMENT=" . ($max + 1) . "\n";
        }
    }
    
    // التحقق
    echo "\n   ✔️ التحقق:\n";
    $orphaned = $tgt->query("SELECT COUNT(*) FROM steam_accounts sa LEFT JOIN group_accounts ga ON ga.account_id=sa.id WHERE ga.account_id IS NULL")->fetchColumn();
    echo "   " . ($orphaned == 0 ? "✅" : "⚠️") . " حسابات يتيمة: $orphaned\n";
    
    $orphaned = $tgt->query("SELECT COUNT(*) FROM sub_bots sb LEFT JOIN bot_groups bg ON bg.bot_id=sb.id WHERE bg.bot_id IS NULL")->fetchColumn();
    echo "   " . ($orphaned == 0 ? "✅" : "⚠️") . " بوتات يتيمة: $orphaned\n";
}

echo "\n";

// ====== النتيجة النهائية ======
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "📊 النتيجة النهائية\n";
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
echo "السجلات المنقولة: {$stats['migrated']}\n";
echo "الأخطاء: {$stats['errors']}\n";

if ($dryRun) {
    echo "\n🧪 DRY RUN - لم يتم تنفيذ أي شيء\n";
    echo "💡 لتنفيذ حقيقي: عدّل \$CONFIG['dry_run'] = false\n";
} else {
    echo "\n🎉 اكتمل الترحيل بنجاح!\n";
}

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
