<?php
// ============================================================
// Admin/auth/migration_cryptography.php
// سكريبت لترحيل التشفير القديم (CBC) إلى التشفير الجديد (AES-256-GCM)
// يمكن تشغيله عبر الـ CLI أو المتصفح (بصلاحيات مسؤول).
// ============================================================

require_once __DIR__ . '/../../connect.php';

echo "Starting Cryptography Migration to AES-256-GCM...\n";
ob_flush(); flush();

$tables = [
    'driver' => [
        'phone', 'email', 'gender', 'birthdate', 'site',
        'first_name', 'last_name', 'accountBank', 'education',
        'employmentType', 'maritalStatus', 'national_number',
        'name_arabic', 'address'
    ],
    'passengers' => [
        'phone', 'email', 'gender', 'birthdate', 
        'first_name', 'last_name', 'token'
    ],
    'CarRegistration' => [
        'vin', 'car_plate', 'owner', 'address'
    ],
    'carPlateEdit' => [
        'carPlate', 'owner'
    ],
    'phone_verification' => [
        'phone_number'
    ],
    'phone_verification_passenger' => [
        'phone_number'
    ],
    'driverToken' => [
        'token'
    ],
    'passengerToken' => [
        'token'
    ],
    'mishwari' => [
        'phone', 'gender', 'name', 'name_english', 'car_plate', 'token', 'education', 'national_number', 'age'
    ],
    'rate_app' => [
        'email', 'phone'
    ],
    'admins' => [
        'name', 'phone', 'email', 'fp'
    ],
    'driver_assurance' => [
        'assured', 'health_insurance_provider'
    ],
    'blacklist_drivers' => [
        'phone'
    ],
    'blacklist_passengers' => [
        'phone'
    ],
    'feedBack' => [
        'feedBack'
    ]
];

$totalUpdated = 0;

foreach ($tables as $table => $columns) {
    echo "Processing table: $table ...\n";
    ob_flush(); flush();

    try {
        $sql = "SELECT `id`, `" . implode("`, `", $columns) . "` FROM `$table`";
        $stmt = $con->query($sql);
        if (!$stmt) {
            echo "Skipped $table (Not found or missing columns).\n";
            continue;
        }
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        echo "Skipped $table due to error: " . $e->getMessage() . "\n";
        continue;
    }
    
    $tableUpdatedCount = 0;

    foreach ($rows as $row) {
        $id = $row['id'];
        $needsUpdate = false;
        $updateValues = [];
        $params = [':id' => $id];

        foreach ($columns as $col) {
            $value = $row[$col];
            
            // تحقق إذا كان الحقل يحتوي على قيمة وإذا لم يكن مشفر بالنظام الجديد
            if (!empty($value) && strpos($value, 'GCM:') !== 0) {
                // محاولة فك التشفير القديم (CBC)
                try {
                    $decrypted = $encryptionHelper->decryptData($value);
                    if ($decrypted !== false && $decrypted !== '') {
                        // إعادة التشفير (سيستخدم GCM الآن)
                        $newEncrypted = $encryptionHelper->encryptData($decrypted);
                        $updateValues[] = "`$col` = :$col";
                        $params[":$col"] = $newEncrypted;
                        $needsUpdate = true;
                    }
                } catch (Exception $e) {
                    error_log("Failed to migrate $col for ID $id in $table: " . $e->getMessage());
                }
            }
        }

        if ($needsUpdate) {
            $setClause = implode(", ", $updateValues);
            $updateSql = "UPDATE `$table` SET $setClause WHERE `id` = :id";
            $updateStmt = $con->prepare($updateSql);
            $updateStmt->execute($params);
            $tableUpdatedCount++;
        }
    }

    echo "Finished $table. Updated rows: $tableUpdatedCount\n";
    $totalUpdated += $tableUpdatedCount;
    ob_flush(); flush();
}

echo "Migration completed! Total rows updated: $totalUpdated\n";
?>
