<?php
/**
 * إضافة tenant_id للجداول وتحديث البيانات الموجودة
 * ينشئ أيضاً subscription_plans و tenants إن لم تكونا موجودتين
 */
$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]
);

// إنشاء جداول SaaS إن لم تكن موجودة
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS subscription_plans (id INT AUTO_INCREMENT PRIMARY KEY, code VARCHAR(50) NOT NULL UNIQUE, name VARCHAR(100) NOT NULL, max_branches INT DEFAULT 1, max_users INT DEFAULT 5, price_monthly DECIMAL(10,2) NULL)");
    $pdo->exec("INSERT IGNORE INTO subscription_plans (id, code, name, max_branches, max_users) VALUES (1, 'basic', 'Basic', 1, 5)");
} catch (PDOException $e) {}
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS tenants (id INT AUTO_INCREMENT PRIMARY KEY, slug VARCHAR(80) NOT NULL UNIQUE, name VARCHAR(150) NOT NULL, plan_id INT DEFAULT 1, logo_url VARCHAR(500) NULL, primary_color VARCHAR(20) DEFAULT '#0d9488', status ENUM('active','suspended','trial') DEFAULT 'active')");
    $pdo->exec("INSERT IGNORE INTO tenants (id, slug, name, plan_id) VALUES (1, 'main', 'المختبر الرئيسي', 1)");
} catch (PDOException $e) {}

$tables = [
    'users', 'patients', 'doctors', 'branches',
    'test_categories', 'tests', 'inventory_items',
    'lab_orders', 'settings'
];

foreach ($tables as $table) {
    try {
        $pdo->exec("ALTER TABLE $table ADD COLUMN tenant_id INT NOT NULL DEFAULT 1");
        echo "Added tenant_id to $table\n";
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Duplicate column') === false) {
            echo "Warning $table: " . $e->getMessage() . "\n";
        }
    }
}

try {
    $pdo->exec("ALTER TABLE patients ADD COLUMN email VARCHAR(150) NULL");
    echo "Added email to patients\n";
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'Duplicate column') === false) echo "Warning: " . $e->getMessage() . "\n";
}

// order_items يرث من lab_orders - لا يحتاج tenant_id
// invoices, results ترث عبر order/order_items
// patient_attachments - عبر patient
// devices, device_tests - قد تكون مشتركة أو per-tenant

$pdo->exec("UPDATE users SET tenant_id = 1 WHERE tenant_id = 0 OR tenant_id IS NULL");
$pdo->exec("UPDATE patients SET tenant_id = 1");
$pdo->exec("UPDATE doctors SET tenant_id = 1");
$pdo->exec("UPDATE branches SET tenant_id = 1");
$pdo->exec("UPDATE lab_orders SET tenant_id = 1");

echo "Done. Default tenant_id = 1 applied.\n";
