<?php
/**
 * ميزات LIMS 2 الكاملة:
 * 1. reference_ranges - المدى المرجعي حسب العمر والجنس
 * 2. samples - توسيع status (collected, in_progress, completed, disposed)
 * 3. qc_results - rule_violated إن لم يكن موجوداً
 */
$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 = [];

// 1. reference_ranges - المدى المرجعي حسب العمر والجنس
$pdo->exec(
    "CREATE TABLE IF NOT EXISTS reference_ranges (
        id INT AUTO_INCREMENT PRIMARY KEY,
        test_id INT NOT NULL,
        age_min_years DECIMAL(5,2) NULL,
        age_max_years DECIMAL(5,2) NULL,
        gender ENUM('M','F','both') NOT NULL DEFAULT 'both',
        reference_range VARCHAR(150) NOT NULL,
        critical_value_min DECIMAL(10,3) NULL,
        critical_value_max DECIMAL(10,3) NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        KEY idx_test (test_id),
        KEY idx_test_age_gender (test_id, age_min_years, age_max_years, gender)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"
);
$changes[] = 'reference_ranges';

// 2. qc_results - rule_violated
try {
    $pdo->query('SELECT rule_violated FROM qc_results LIMIT 1');
} catch (PDOException $e) {
    try {
        $pdo->exec('ALTER TABLE qc_results ADD COLUMN rule_violated VARCHAR(50) NULL AFTER status');
        $changes[] = 'qc_results.rule_violated';
    } catch (PDOException $e2) {}
}

// 3. samples - توسيع status
try {
    $pdo->exec("ALTER TABLE samples MODIFY COLUMN status ENUM('pending','collected','received','in_progress','used','disposed','rejected') NOT NULL DEFAULT 'pending'");
    $changes[] = 'samples.status';
} catch (PDOException $e) {}

echo "LIMS 2 features migration done. Changes: " . implode(', ', $changes) . "\n";
