<?php
/**
 * تهيئة جداول مالتي-تِنانت الأساسية
 * يشغّل أولاً إذا كانت جدولي tenants و subscription_plans غير موجودين
 */
$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]
);

$done = [];

// 1. خطط الاشتراك
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 NOT NULL DEFAULT 1,
        max_users INT NOT NULL DEFAULT 5,
        max_patients_per_month INT NULL,
        storage_gb DECIMAL(10,2) NULL,
        api_access TINYINT(1) NOT NULL DEFAULT 0,
        price_monthly DECIMAL(10,2) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $done[] = 'subscription_plans';
    $pdo->exec("INSERT IGNORE INTO subscription_plans (id, code, name, max_branches, max_users, price_monthly) VALUES (1, 'basic', 'Basic', 1, 5, 29.99)");
    $pdo->exec("INSERT IGNORE INTO subscription_plans (id, code, name, max_branches, max_users, price_monthly) VALUES (2, 'pro', 'Pro', 3, 15, 79.99)");
    $pdo->exec("INSERT IGNORE INTO subscription_plans (id, code, name, max_branches, max_users, price_monthly) VALUES (3, 'enterprise', 'Enterprise', 999, 999, 199.99)");
} catch (PDOException $e) {
    echo "subscription_plans: " . $e->getMessage() . "\n";
}

// 2. جدول المختبرات (tenants)
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 NOT NULL DEFAULT 1,
        logo_url VARCHAR(500) NULL,
        primary_color VARCHAR(20) NULL DEFAULT '#0d9488',
        status ENUM('active','suspended','trial') NOT NULL DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (plan_id) REFERENCES subscription_plans(id)
    )");
    $done[] = 'tenants';
    $pdo->exec("INSERT IGNORE INTO tenants (id, slug, name, plan_id, status) VALUES (1, 'main', 'المختبر الرئيسي', 1, 'active')");
} catch (PDOException $e) {
    if (strpos($e->getMessage(), 'already exists') === false) {
        echo "tenants: " . $e->getMessage() . "\n";
    }
}

// 3. التأكد من وجود دور Administrator (للتسجيل)
try {
    $pdo->query('SELECT id FROM roles LIMIT 1');
    $pdo->exec("INSERT IGNORE INTO roles (name) VALUES ('Administrator')");
    $done[] = 'roles';
} catch (PDOException $e) {}

echo "تم تهيئة مالتي-تِنانت. الجداول: " . implode(', ', $done) . "\n";
