<?php
/**
 * عزل مالتي-تِنانت كامل:
 * 1. إعدادات per-tenant: (tenant_id, setting_key) unique
 * 2. تعيين tenant_id=1 للبيانات الموجودة
 */
$config = require __DIR__ . '/../config/config.php';
$pdo = new PDO(
    'mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['name'] . ';charset=utf8mb4',
    $config['db']['user'],
    $config['db']['pass'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);

$changes = [];

// التأكد من وجود tenant_id في settings
try {
    $pdo->query('SELECT tenant_id FROM settings LIMIT 1');
} catch (PDOException $e) {
    try {
        $pdo->exec('ALTER TABLE settings ADD COLUMN tenant_id INT NOT NULL DEFAULT 1');
        $changes[] = 'settings.tenant_id';
    } catch (PDOException $e2) {}
}

// تحديث القيد الفريد لدعم per-tenant
foreach (['setting_key', 'setting_key_2'] as $idx) {
    try {
        $pdo->exec("ALTER TABLE settings DROP INDEX `$idx`");
        $changes[] = "settings dropped $idx";
        break;
    } catch (PDOException $e) {}
}

try {
    $pdo->exec('ALTER TABLE settings ADD UNIQUE KEY uk_tenant_setting (tenant_id, setting_key)');
    $changes[] = 'settings uk_tenant_setting';
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Duplicate') !== false) {
        // موجود مسبقاً
    }
}

// تعيين tenant_id للصفوف القديمة إن وُجدت
try {
    $pdo->exec('UPDATE settings SET tenant_id = 1 WHERE tenant_id = 0 OR tenant_id IS NULL');
    $changes[] = 'settings tenant_id normalized';
} catch (PDOException $e) {}

echo "Full multi-tenant migration done. Changes: " . implode(', ', $changes) . "\n";
