<?php
/**
 * نظام الترحيل البسيط والمُصحّح v2.0
 * نقل البيانات من supehgku_Packagemaker إلى supehgku_test0
 */

// ====== الإعدادات ======
$CONFIG = [
    'source' => ['host' => 'localhost', 'user' => 'root', 'pass' => '', 'db' => 'supehgku_Packagemaker'],
    'target' => ['host' => 'localhost', 'user' => 'root', 'pass' => '', 'db' => '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']['db']};charset=utf8mb4",
        $CONFIG['source']['user'], $CONFIG['source']['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
    $tgt = new PDO("mysql:host={$CONFIG['target']['host']};dbname={$CONFIG['target']['db']};charset=utf8mb4",
        $CONFIG['target']['user'], $CONFIG['target']['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    
    echo "✅ اتصال ناجح\n\n";
} catch (PDOException $e) {
    die("❌ خطأ: " . $e->getMessage() . "\n");
}

$dry = $CONFIG['dry_run'];
echo ($dry ? "🧪 DRY RUN - اختبار فقط\n" : "⚡ LIVE - تنفيذ حقيقي\n");
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n";

// ====== المرحلة 0: التحضير ======
echo "📋 المرحلة 0: التحضير\n";
$stmt = $tgt->query("SELECT id FROM account_groups WHERE id = 1");
if (!$stmt->fetch()) {
    if (!$dry) {
        $tgt->exec("INSERT INTO account_groups (id, group_name, description, is_default, locked, active) VALUES (1, 'default', 'المجموعة العامة', 1, 1, 1)");
    }
    echo "   ✅ إنشاء المجموعة الافتراضية\n";
} else {
    echo "   ✅ المجموعة الافتراضية موجودة\n";
}
if (!$dry) $tgt->exec("SET FOREIGN_KEY_CHECKS=0");
echo "\n";

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

// 1.1 sub_bots (مُصحّح)
$count = $src->query("SELECT COUNT(*) FROM sub_bots")->fetchColumn();
echo "🤖 sub_bots: $count بوت\n";
if (!$dry) {
    $stmt = $src->query("SELECT id, label, bot_token, channel_id, max_users, is_paused, welcome_message, created_at, updated_at FROM sub_bots");
    $ins = $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,?,?,?)");
    $m = 0;
    while ($r = $stmt->fetch(PDO::FETCH_NUM)) { $ins->execute($r); if($ins->rowCount()>0) $m++; }
    echo "   ✅ $m منقول\n";
}

// 1.2 steam_accounts
$count = $src->query("SELECT COUNT(*) FROM steam_accounts")->fetchColumn();
echo "💎 steam_accounts: $count حساب\n";
if (!$dry) {
    $tgt->exec("INSERT IGNORE INTO steam_accounts SELECT * FROM {$CONFIG['source']['db']}.steam_accounts");
    echo "   ✅ تم\n";
}

// 1.3 allowed_users
$count = $src->query("SELECT COUNT(*) FROM allowed_users")->fetchColumn();
echo "👥 allowed_users: $count مستخدم\n";
if (!$dry) {
    $tgt->exec("INSERT IGNORE INTO allowed_users SELECT * FROM {$CONFIG['source']['db']}.allowed_users");
    echo "   ✅ تم\n";
}

// 1.4 message_templates
$count = $src->query("SELECT COUNT(*) FROM message_templates")->fetchColumn();
echo "📝 message_templates: $count قالب\n";
if (!$dry) {
    $stmt = $src->query("SELECT `key`, text FROM message_templates");
    $ins = $tgt->prepare("INSERT INTO message_templates (`key`, text) VALUES (?,?) ON DUPLICATE KEY UPDATE text=VALUES(text)");
    while ($r = $stmt->fetch(PDO::FETCH_NUM)) $ins->execute($r);
    echo "   ✅ تم\n";
}

// 1.5 control_sessions
$count = $src->query("SELECT COUNT(*) FROM control_sessions")->fetchColumn();
echo "🔄 control_sessions: $count جلسة\n";
if (!$dry) {
    $tgt->exec("INSERT IGNORE INTO control_sessions SELECT * FROM {$CONFIG['source']['db']}.control_sessions");
    echo "   ✅ تم\n";
}
echo "\n";

// ====== المرحلة 2: daily_attempts → limits_bot ======
echo "⚙️ المرحلة 2: نقل daily_attempts إلى limits_bot\n";
$stmt = $src->query("SELECT label, daily_attempts FROM sub_bots");
$bots = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo "   البوتات: " . count($bots) . "\n";
if (!$dry) {
    $ins = $tgt->prepare("INSERT INTO limits_bot (bot_label, mode, per_day, per_week, per_month, ban_duration) VALUES (?,?,?,?,?,1) ON DUPLICATE KEY UPDATE per_day=VALUES(per_day), per_week=VALUES(per_week), per_month=VALUES(per_month)");
    foreach ($bots as $b) {
        $d = $b['daily_attempts'] ?? 2;
        $ins->execute([$b['label'], 'daily', $d, $d*7, $d*30]);
        echo "   ✓ {$b['label']}: $d/يوم\n";
    }
}
echo "\n";

// ====== المرحلة 3: الربط ======
echo "🔗 المرحلة 3: ربط العلاقات\n";
if (!$dry) {
    $tgt->exec("INSERT IGNORE INTO group_accounts (group_id, account_id) SELECT 1, id FROM steam_accounts");
    $c = $tgt->query("SELECT COUNT(*) FROM group_accounts WHERE group_id=1")->fetchColumn();
    echo "   ✅ الحسابات: $c مربوط\n";
    
    $tgt->exec("INSERT IGNORE INTO bot_groups (bot_id, group_id) SELECT id, 1 FROM sub_bots");
    $c = $tgt->query("SELECT COUNT(*) FROM bot_groups WHERE group_id=1")->fetchColumn();
    echo "   ✅ البوتات: $c مربوط\n";
}
echo "\n";

// ====== المرحلة 4: التنظيف ======
echo "🧹 المرحلة 4: التنظيف\n";
if (!$dry) {
    $tgt->exec("SET FOREIGN_KEY_CHECKS=1");
    echo "   ✅ Foreign Keys مُفعّلة\n";
    
    foreach (['sub_bots', 'steam_accounts', 'allowed_users'] as $t) {
        $max = $tgt->query("SELECT MAX(id) FROM $t")->fetchColumn();
        if ($max) $tgt->exec("ALTER TABLE $t AUTO_INCREMENT=" . ($max+1));
    }
    echo "   ✅ AUTO_INCREMENT محدّث\n";
}
echo "\n";

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