<?php
/**
 * 1. result_summary_templates - قوالب خلاصة النتائج
 * 2. tests - إضافة رموز CPT للفوترة
 */
$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. جدول قوالب خلاصة النتائج
try {
    $pdo->query('SELECT id FROM result_summary_templates LIMIT 1');
} catch (PDOException $e) {
    try {
        $pdo->exec("CREATE TABLE result_summary_templates (
            id INT AUTO_INCREMENT PRIMARY KEY,
            tenant_id INT NULL,
            title VARCHAR(100) NOT NULL,
            template_text TEXT NOT NULL,
            category VARCHAR(50) NULL,
            sort_order INT NOT NULL DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            INDEX idx_tenant (tenant_id),
            INDEX idx_category (category)
        )");
        $changes[] = 'result_summary_templates';
    } catch (PDOException $e2) {}
}

// 2. رموز CPT للفحوصات
try {
    $pdo->query('SELECT cpt_code FROM tests LIMIT 1');
} catch (PDOException $e) {
    try {
        $pdo->exec("ALTER TABLE tests ADD COLUMN cpt_code VARCHAR(20) NULL AFTER default_price");
        $changes[] = 'tests.cpt_code';
    } catch (PDOException $e2) {}
}

echo "Migration 021 done. Changes: " . implode(', ', $changes) . "\n";
