<?php

use App\Core\Auth;
use App\Core\Tenant;

if (!($auth instanceof Auth) || !$auth->can('tests.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى إدارة التحاليل';
    return;
}

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';
$testsTenantAnd = '';
$testsTenantParams = [];
$testsTenantAndNoAlias = '';
$testsTenantParamsNoAlias = [];
$testsTenantUpdate = '';
try {
    $db->query('SELECT tenant_id FROM tests LIMIT 1');
    $testsTenantAnd = ' AND t.tenant_id = ?';
    $testsTenantParams = [$tenantId];
    $testsTenantAndNoAlias = ' AND tenant_id = ?';
    $testsTenantParamsNoAlias = [$tenantId];
    $testsTenantUpdate = ' AND tenant_id = :tid';
} catch (Throwable $e) {}

// نسخ فحص (duplicate)
if ($action === 'duplicate' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('tests.create')) {
        http_response_code(403);
        echo 'غير مسموح بنسخ التحاليل';
        return;
    }
    $dupId = (int)$_GET['id'];
    if ($dupId > 0) {
        try {
            $cptSel = '';
            try { $db->query('SELECT cpt_code FROM tests LIMIT 1'); $cptSel = ', t.cpt_code'; } catch (Throwable $e) {}
            $stmt = $db->prepare('SELECT t.name, t.category_id, t.default_price' . $cptSel . ', t.unit, t.reference_range, t.method, t.tat_hours, t.inventory_item_id, t.consumption_quantity, t.critical_value_min, t.critical_value_max FROM tests t WHERE t.id = ?' . $testsTenantAnd);
            $stmt->execute(array_merge([$dupId], $testsTenantParams));
            $src = $stmt->fetch();
        } catch (Throwable $e) {
            $src = false;
        }
        
        if ($src) {
            $code = 'T' . time();
            try {
                $db->query('SELECT tenant_id FROM tests LIMIT 1');
                try {
                    $db->query('SELECT cpt_code FROM tests LIMIT 1');
                    $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, cpt_code, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max, tenant_id) VALUES (:code, :name, :cat, :price, :cpt, :unit, :ref, :method, :tat, :inv, :cons, :cmin, :cmax, :tid)');
                    $stmt->execute([
                        'code' => $code, 'name' => $src['name'] . ' (نسخة)', 'cat' => $src['category_id'], 'price' => $src['default_price'], 'cpt' => $src['cpt_code'] ?? null, 'unit' => $src['unit'], 'ref' => $src['reference_range'], 'method' => $src['method'], 'tat' => (int)($src['tat_hours'] ?? 0), 'inv' => $src['inventory_item_id'], 'cons' => (float)($src['consumption_quantity'] ?? 0), 'cmin' => $src['critical_value_min'], 'cmax' => $src['critical_value_max'], 'tid' => $tenantId
                    ]);
                } catch (Throwable $cptEx) {
                    $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max, tenant_id) VALUES (:code, :name, :cat, :price, :unit, :ref, :method, :tat, :inv, :cons, :cmin, :cmax, :tid)');
                    $stmt->execute([
                        'code' => $code, 'name' => $src['name'] . ' (نسخة)', 'cat' => $src['category_id'], 'price' => $src['default_price'], 'unit' => $src['unit'], 'ref' => $src['reference_range'], 'method' => $src['method'], 'tat' => (int)($src['tat_hours'] ?? 0), 'inv' => $src['inventory_item_id'], 'cons' => (float)($src['consumption_quantity'] ?? 0), 'cmin' => $src['critical_value_min'], 'cmax' => $src['critical_value_max'], 'tid' => $tenantId
                    ]);
                }
            } catch (Throwable $e) {
                $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max) VALUES (:code, :name, :cat, :price, :unit, :ref, :method, :tat, :inv, :cons, :cmin, :cmax)');
                $stmt->execute([
                    'code' => $code, 'name' => $src['name'] . ' (نسخة)', 'cat' => $src['category_id'], 'price' => $src['default_price'], 'unit' => $src['unit'], 'ref' => $src['reference_range'], 'method' => $src['method'], 'tat' => (int)($src['tat_hours'] ?? 0), 'inv' => $src['inventory_item_id'], 'cons' => (float)($src['consumption_quantity'] ?? 0), 'cmin' => $src['critical_value_min'], 'cmax' => $src['critical_value_max']
                ]);
            }
            $newId = (int)$db->lastInsertId();
            if (isset($auditLog)) {
                $auditLog->log('test_duplicated', 'test', $newId, json_encode(['source_id' => $dupId], JSON_UNESCAPED_UNICODE), json_encode(['name' => $src['name'] . ' (نسخة)', 'code' => $code], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
            $_SESSION['tests_msg'] = 'تم نسخ الفحص بنجاح. يمكنك تعديل الاسم والحفظ.';
            header('Location: index.php?page=tests&action=edit&id=' . $newId);
            exit;
        }
    }
    header('Location: index.php?page=tests');
    exit;
}

// حذف فحص
if ($action === 'delete' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('tests.delete')) {
        http_response_code(403);
        echo 'غير مسموح بحذف التحاليل';
        return;
    }
    $delId = (int)$_GET['id'];
    if ($delId > 0) {
        try {
            $stmt = $db->prepare('SELECT id, name, test_code FROM tests WHERE id = ?' . $testsTenantAndNoAlias);
            $stmt->execute(array_merge([$delId], $testsTenantParamsNoAlias));
            $test = $stmt->fetch();
        } catch (Throwable $e) {
            $test = false;
        }
        
        if ($test) {
            // التحقق من وجود طلبات مرتبطة
            $orderCount = 0;
            try {
                try {
                    $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
                    $stmt = $db->prepare('SELECT COUNT(*) FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE oi.test_id = ? AND o.tenant_id = ?');
                    $stmt->execute([$delId, $tenantId]);
                } catch (Throwable $e) {
                    $stmt = $db->prepare('SELECT COUNT(*) FROM order_items WHERE test_id = ?');
                    $stmt->execute([$delId]);
                }
                $orderCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e) {}
            
            // التحقق من وجود في البانلات
            $panelCount = 0;
            try {
                $stmt = $db->prepare('SELECT COUNT(*) FROM panel_tests WHERE test_id = ?');
                $stmt->execute([$delId]);
                $panelCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e) {}
            
            if ($orderCount > 0 || $panelCount > 0) {
                $_SESSION['tests_error'] = 'لا يمكن حذف هذا الفحص لأنه مرتبط بـ ' . $orderCount . ' طلب و ' . $panelCount . ' بانل. يمكنك تعديل بياناته بدلاً من ذلك.';
                header('Location: index.php?page=tests&action=view&id=' . $delId);
                exit;
            }
            
            // حذف الفحص
            try {
                $stmt = $db->prepare('DELETE FROM tests WHERE id = ?' . $testsTenantAndNoAlias);
                $stmt->execute(array_merge([$delId], $testsTenantParamsNoAlias));
                if ($stmt->rowCount() > 0) {
                    if (isset($auditLog)) {
                        $auditLog->log('test_deleted', 'test', $delId, json_encode(['name' => $test['name'], 'test_code' => $test['test_code']], JSON_UNESCAPED_UNICODE), null, $_SESSION['user_id'] ?? null);
                    }
                    $_SESSION['tests_msg'] = 'تم حذف الفحص بنجاح';
                } else {
                    $_SESSION['tests_error'] = 'الفحص غير موجود';
                }
            } catch (PDOException $e) {
                $_SESSION['tests_error'] = 'حدث خطأ أثناء حذف الفحص';
            }
        } else {
            $_SESSION['tests_error'] = 'الفحص غير موجود';
        }
    }
    header('Location: index.php?page=tests');
    exit;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!\App\Core\CSRFProtection::validatePostRequest()) {
        $_SESSION['tests_msg'] = 'طلب غير صالح. يرجى المحاولة مرة أخرى.';
        header('Location: index.php?page=tests');
        exit;
    }
    
    if (!($auth instanceof Auth) || !$auth->can('tests.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة التحاليل';
        return;
    }
    $name = trim($_POST['name'] ?? '');
    $categoryName = trim($_POST['category'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $cptCode = trim($_POST['cpt_code'] ?? '') ?: null;
    $unit = trim($_POST['unit'] ?? '');
    $referenceRange = trim($_POST['reference_range'] ?? '');
    $method = trim($_POST['method'] ?? '');
    $inventoryItemId = (int)($_POST['inventory_item_id'] ?? 0);
    $consumptionQuantity = (float)($_POST['consumption_quantity'] ?? 0);

    if ($name !== '') {
        $categoryId = null;

        if ($categoryName !== '') {
            $stmt = $db->prepare('SELECT id FROM test_categories WHERE name = :n LIMIT 1');
            $stmt->execute(['n' => $categoryName]);
            $row = $stmt->fetch();

            if ($row) {
                $categoryId = (int)$row['id'];
            } else {
                $stmt = $db->prepare('INSERT INTO test_categories (name) VALUES (:n)');
                $stmt->execute(['n' => $categoryName]);
                $categoryId = (int)$db->lastInsertId();
            }
        }

        $code = 'T' . time();
        $criticalMin = trim($_POST['critical_value_min'] ?? '');
        $criticalMax = trim($_POST['critical_value_max'] ?? '');
        $criticalMinVal = $criticalMin !== '' ? (float)$criticalMin : null;
        $criticalMaxVal = $criticalMax !== '' ? (float)$criticalMax : null;
        $eduContent = trim($_POST['educational_content'] ?? '');

        try {
            $db->query('SELECT tenant_id FROM tests LIMIT 1');
            try {
                $db->query('SELECT educational_content FROM tests LIMIT 1');
                try {
                    $db->query('SELECT cpt_code FROM tests LIMIT 1');
                    $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, cpt_code, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max, educational_content, tenant_id) VALUES (:code, :name, :cat, :price, :cpt, :unit, :ref, :method, :tat, :inv_item, :cons, :cmin, :cmax, :edu, :tid)');
                    $stmt->execute([
                        'code' => $code, 'name' => $name, 'cat' => $categoryId, 'price' => $price, 'cpt' => $cptCode, 'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null, 'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0), 'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity > 0 ? $consumptionQuantity : 0, 'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'edu' => $eduContent !== '' ? $eduContent : null, 'tid' => $tenantId
                    ]);
                } catch (Throwable $cptEx) {
                    $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max, educational_content, tenant_id) VALUES (:code, :name, :cat, :price, :unit, :ref, :method, :tat, :inv_item, :cons, :cmin, :cmax, :edu, :tid)');
                    $stmt->execute([
                        'code' => $code, 'name' => $name, 'cat' => $categoryId, 'price' => $price, 'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null, 'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0), 'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity > 0 ? $consumptionQuantity : 0, 'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'edu' => $eduContent !== '' ? $eduContent : null, 'tid' => $tenantId
                    ]);
                }
            } catch (Throwable $ex) {
                $stmt = $db->prepare('INSERT INTO tests (test_code, name, category_id, default_price, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max, tenant_id) VALUES (:code, :name, :cat, :price, :unit, :ref, :method, :tat, :inv_item, :cons, :cmin, :cmax, :tid)');
                $stmt->execute([
                    'code' => $code, 'name' => $name, 'cat' => $categoryId, 'price' => $price, 'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null, 'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0), 'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity > 0 ? $consumptionQuantity : 0, 'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'tid' => $tenantId
                ]);
            }
        } catch (Throwable $e) {
            $stmt = $db->prepare(
                'INSERT INTO tests
                 (test_code, name, category_id, default_price, unit, reference_range, method, tat_hours, inventory_item_id, consumption_quantity, critical_value_min, critical_value_max)
                 VALUES (:code, :name, :cat, :price, :unit, :ref, :method, :tat, :inv_item, :cons, :cmin, :cmax)'
            );

            $stmt->execute([
                'code' => $code,
                'name' => $name,
                'cat' => $categoryId,
                'price' => $price,
                'unit' => $unit !== '' ? $unit : null,
                'ref' => $referenceRange !== '' ? $referenceRange : null,
                'method' => $method !== '' ? $method : null,
                'tat' => (int)($_POST['tat_hours'] ?? 0),
                'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null,
                'cons' => $consumptionQuantity > 0 ? $consumptionQuantity : 0,
                'cmin' => $criticalMinVal,
                'cmax' => $criticalMaxVal
            ]);
        }
        $newTestId = (int)$db->lastInsertId();
        if (isset($auditLog) && $newTestId > 0) {
            $auditLog->log('test_created', 'test', $newTestId, null, json_encode(['name' => $name, 'test_code' => $code], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
        }
        $_SESSION['tests_msg'] = 'تم إضافة الفحص بنجاح';
    }

    header('Location: index.php?page=tests');
    exit;
}

// تعديل فحص
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('tests.update')) {
        http_response_code(403);
        echo 'غير مسموح بتعديل التحاليل';
        return;
    }
    $id = (int)($_POST['id'] ?? 0);
    if ($id > 0) {
        $name = trim($_POST['name'] ?? '');
        $categoryName = trim($_POST['category'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $unit = trim($_POST['unit'] ?? '');
        $referenceRange = trim($_POST['reference_range'] ?? '');
        $method = trim($_POST['method'] ?? '');
        $criticalMin = trim($_POST['critical_value_min'] ?? '');
        $criticalMax = trim($_POST['critical_value_max'] ?? '');
        $inventoryItemId = (int)($_POST['inventory_item_id'] ?? 0);
        $consumptionQuantity = (float)($_POST['consumption_quantity'] ?? 0);
        $cptCode = trim($_POST['cpt_code'] ?? '') ?: null;

        if ($name !== '') {
            $categoryId = null;
            // معالجة الفئة - يمكن أن تأتي من select أو input جديد
            $categoryInput = trim($_POST['category'] ?? '');
            if ($categoryInput !== '') {
                $stmt = $db->prepare('SELECT id FROM test_categories WHERE name = :n LIMIT 1');
                $stmt->execute(['n' => $categoryInput]);
                $row = $stmt->fetch();
                if ($row) {
                    $categoryId = (int)$row['id'];
                } else {
                    // إنشاء فئة جديدة
                    $stmt = $db->prepare('INSERT INTO test_categories (name) VALUES (:n)');
                    $stmt->execute(['n' => $categoryInput]);
                    $categoryId = (int)$db->lastInsertId();
                }
            }

            $criticalMinVal = $criticalMin !== '' ? (float)$criticalMin : null;
            $criticalMaxVal = $criticalMax !== '' ? (float)$criticalMax : null;

            $eduContent = trim($_POST['educational_content'] ?? '');
            $redirectBranchId = (int)($_POST['redirect_to_branch_id'] ?? 0) ?: null;
            try {
                $db->query('SELECT educational_content FROM tests LIMIT 1');
                try {
                    $db->query('SELECT redirect_to_branch_id FROM tests LIMIT 1');
                    try {
                        $db->query('SELECT cpt_code FROM tests LIMIT 1');
                        $stmt = $db->prepare('UPDATE tests SET name=:name, category_id=:cat, default_price=:price, cpt_code=:cpt, unit=:unit, reference_range=:ref, method=:method, tat_hours=:tat, inventory_item_id=:inv_item, consumption_quantity=:cons, critical_value_min=:cmin, critical_value_max=:cmax, educational_content=:edu, redirect_to_branch_id=:redirect WHERE id=:id' . $testsTenantUpdate);
                        $updateParams = [
                            'name' => $name, 'cat' => $categoryId, 'price' => $price, 'cpt' => $cptCode,
                            'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null,
                            'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0),
                            'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity >= 0 ? $consumptionQuantity : 0,
                            'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'edu' => $eduContent !== '' ? $eduContent : null, 'redirect' => $redirectBranchId, 'id' => $id
                        ];
                        if ($testsTenantUpdate) $updateParams['tid'] = $tenantId;
                        $stmt->execute($updateParams);
                    } catch (Throwable $cptEx) {
                        $stmt = $db->prepare('UPDATE tests SET name=:name, category_id=:cat, default_price=:price, unit=:unit, reference_range=:ref, method=:method, tat_hours=:tat, inventory_item_id=:inv_item, consumption_quantity=:cons, critical_value_min=:cmin, critical_value_max=:cmax, educational_content=:edu, redirect_to_branch_id=:redirect WHERE id=:id' . $testsTenantUpdate);
                        $updateParams = [
                            'name' => $name, 'cat' => $categoryId, 'price' => $price,
                            'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null,
                            'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0),
                            'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity >= 0 ? $consumptionQuantity : 0,
                            'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'edu' => $eduContent !== '' ? $eduContent : null, 'redirect' => $redirectBranchId, 'id' => $id
                        ];
                        if ($testsTenantUpdate) $updateParams['tid'] = $tenantId;
                        $stmt->execute($updateParams);
                    }
                } catch (Throwable $ex) {
                    $stmt = $db->prepare('UPDATE tests SET name=:name, category_id=:cat, default_price=:price, unit=:unit, reference_range=:ref, method=:method, tat_hours=:tat, inventory_item_id=:inv_item, consumption_quantity=:cons, critical_value_min=:cmin, critical_value_max=:cmax, educational_content=:edu WHERE id=:id' . $testsTenantUpdate);
                    $updateParams = [
                        'name' => $name, 'cat' => $categoryId, 'price' => $price,
                        'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null,
                        'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0),
                        'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity >= 0 ? $consumptionQuantity : 0,
                        'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'edu' => $eduContent !== '' ? $eduContent : null, 'id' => $id
                    ];
                    if ($testsTenantUpdate) $updateParams['tid'] = $tenantId;
                    $stmt->execute($updateParams);
                }
            } catch (Throwable $e) {
                $stmt = $db->prepare(
                    'UPDATE tests SET name=:name, category_id=:cat, default_price=:price, unit=:unit,
                     reference_range=:ref, method=:method, tat_hours=:tat, inventory_item_id=:inv_item,
                     consumption_quantity=:cons, critical_value_min=:cmin, critical_value_max=:cmax
                     WHERE id=:id' . $testsTenantUpdate
                );
                $updateParams = [
                    'name' => $name, 'cat' => $categoryId, 'price' => $price,
                    'unit' => $unit !== '' ? $unit : null, 'ref' => $referenceRange !== '' ? $referenceRange : null,
                    'method' => $method !== '' ? $method : null, 'tat' => (int)($_POST['tat_hours'] ?? 0),
                    'inv_item' => $inventoryItemId > 0 ? $inventoryItemId : null, 'cons' => $consumptionQuantity >= 0 ? $consumptionQuantity : 0,
                    'cmin' => $criticalMinVal, 'cmax' => $criticalMaxVal, 'id' => $id
                ];
                if ($testsTenantUpdate) $updateParams['tid'] = $tenantId;
                $stmt->execute($updateParams);
            }
            if (isset($auditLog)) {
                $auditLog->log('test_updated', 'test', $id, null, json_encode(['name' => $name, 'price' => $price], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
            }
            $_SESSION['tests_msg'] = 'تم تحديث بيانات الفحص بنجاح';
        }
    }
    header('Location: index.php?page=tests&action=view&id=' . $id);
    exit;
}

// صفحة عرض التفاصيل
$viewId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($viewId > 0 && ($action === 'view' || $action === 'profile')) {
    $eduCol = '';
    $cptColView = '';
    try { $db->query('SELECT educational_content FROM tests LIMIT 1'); $eduCol = ', t.educational_content'; } catch (Throwable $e) {}
    try { $db->query('SELECT cpt_code FROM tests LIMIT 1'); $cptColView = ', t.cpt_code'; } catch (Throwable $e) {}
    
    try {
        $stmt = $db->prepare(
            'SELECT t.id, t.test_code, t.name, t.default_price' . $cptColView . ', t.unit, t.reference_range, t.method, t.tat_hours,
             t.inventory_item_id, t.consumption_quantity, t.critical_value_min, t.critical_value_max' . $eduCol . ',
             c.name AS category_name, i.name AS inventory_name, i.item_code AS inventory_code
             FROM tests t 
             LEFT JOIN test_categories c ON c.id = t.category_id 
             LEFT JOIN inventory_items i ON i.id = t.inventory_item_id 
             WHERE t.id = ?' . $testsTenantAnd
        );
        $stmt->execute(array_merge([$viewId], $testsTenantParams));
        $test = $stmt->fetch();
    } catch (Throwable $e) {
        $test = false;
    }
    
    if (!$test) {
        header('Location: index.php?page=tests');
        exit;
    }
    
    // إحصائيات الفحص
    $stats = [
        'total_orders' => 0,
        'total_revenue' => 0,
        'recent_orders' => []
    ];
    
    try {
        $tenantOrd = '';
        try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantOrd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        
        $stmt = $db->prepare(
            'SELECT COUNT(*) FROM order_items oi 
             JOIN lab_orders o ON o.id = oi.order_id 
             WHERE oi.test_id = ?' . ($tenantOrd ? ' AND o.tenant_id = ' . (int)$tenantId : '')
        );
        $stmt->execute([$viewId]);
        $stats['total_orders'] = (int)$stmt->fetchColumn();
        
        try {
            $stmt = $db->prepare(
                'SELECT COALESCE(SUM(oi.price), 0) FROM order_items oi 
                 JOIN lab_orders o ON o.id = oi.order_id 
                 WHERE oi.test_id = ?' . ($tenantOrd ? ' AND o.tenant_id = ' . (int)$tenantId : '')
            );
            $stmt->execute([$viewId]);
            $stats['total_revenue'] = (float)$stmt->fetchColumn();
        } catch (Throwable $e) {}
        
        // آخر الطلبات
        $stmt = $db->prepare(
            'SELECT o.id, o.order_number, o.order_date, o.status, oi.price,
                    p.full_name AS patient_name, p.patient_code, d.full_name AS doctor_name
             FROM order_items oi
             JOIN lab_orders o ON o.id = oi.order_id
             LEFT JOIN patients p ON p.id = o.patient_id
             LEFT JOIN doctors d ON d.id = o.doctor_id
             WHERE oi.test_id = ?' . ($tenantOrd ? ' AND o.tenant_id = ' . (int)$tenantId : '') . '
             ORDER BY o.order_date DESC
             LIMIT 10'
        );
        $stmt->execute([$viewId]);
        $stats['recent_orders'] = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>تفاصيل الفحص</h1>
        <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
            <?php if ($auth->can('tests.update')): ?>
            <a href="index.php?page=tests&action=edit&id=<?php echo (int)$viewId; ?>" class="btn-primary">تعديل</a>
            <?php endif; ?>
            <?php if ($auth->can('tests.create')): ?>
            <a href="index.php?page=tests&action=duplicate&id=<?php echo (int)$viewId; ?>" class="btn-secondary">نسخ</a>
            <?php endif; ?>
            <?php if ($auth->can('tests.delete')): ?>
            <a href="index.php?page=tests&action=delete&id=<?php echo (int)$viewId; ?>" 
               class="btn-secondary" 
               onclick="return confirm('هل أنت متأكد من حذف هذا الفحص؟');">حذف</a>
            <?php endif; ?>
            <a href="index.php?page=tests" class="btn-secondary">← رجوع</a>
        </div>
    </div>
    
    <?php if (isset($_SESSION['tests_msg'])): ?>
        <div class="alert alert-info" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($_SESSION['tests_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['tests_msg']); ?>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['tests_error'])): ?>
        <div class="alert alert-danger" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($_SESSION['tests_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['tests_error']); ?>
        </div>
    <?php endif; ?>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;">المعلومات الأساسية</h2>
        <div class="form-grid">
            <div>
                <label><strong>الكود:</strong></label>
                <div><?php echo htmlspecialchars($test['test_code'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>اسم الفحص:</strong></label>
                <div><?php echo htmlspecialchars($test['name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>الفئة:</strong></label>
                <div><?php echo htmlspecialchars($test['category_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>السعر:</strong></label>
                <div><?php echo number_format((float)$test['default_price'], 2); ?> د.ع</div>
            </div>
            <?php if (!empty($test['cpt_code'])): ?>
            <div>
                <label><strong>رمز CPT:</strong></label>
                <div><?php echo htmlspecialchars($test['cpt_code'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <?php endif; ?>
            <div>
                <label><strong>الوحدة:</strong></label>
                <div><?php echo htmlspecialchars($test['unit'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div class="full-width">
                <label><strong>المدى المرجعي:</strong></label>
                <div><?php echo htmlspecialchars($test['reference_range'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>طريقة الفحص:</strong></label>
                <div><?php echo htmlspecialchars($test['method'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>زمن التنفيذ:</strong></label>
                <div><?php echo (int)($test['tat_hours'] ?? 0); ?> ساعة</div>
            </div>
            <?php if (!empty($test['critical_value_min']) || !empty($test['critical_value_max'])): ?>
            <div>
                <label><strong>القيم الحرجة:</strong></label>
                <div>
                    <?php if (!empty($test['critical_value_min'])): ?>
                        أدنى: <?php echo htmlspecialchars($test['critical_value_min'], ENT_QUOTES, 'UTF-8'); ?>
                    <?php endif; ?>
                    <?php if (!empty($test['critical_value_min']) && !empty($test['critical_value_max'])): ?> | <?php endif; ?>
                    <?php if (!empty($test['critical_value_max'])): ?>
                        أعلى: <?php echo htmlspecialchars($test['critical_value_max'], ENT_QUOTES, 'UTF-8'); ?>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
            <?php if (!empty($test['inventory_name'])): ?>
            <div>
                <label><strong>مادة المخزون:</strong></label>
                <div><?php echo htmlspecialchars($test['inventory_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?> - <?php echo htmlspecialchars($test['inventory_name'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <div>
                <label><strong>كمية الاستهلاك:</strong></label>
                <div><?php echo htmlspecialchars($test['consumption_quantity'], ENT_QUOTES, 'UTF-8'); ?></div>
            </div>
            <?php endif; ?>
            <?php if (!empty($test['educational_content'])): ?>
            <div class="full-width">
                <label><strong>المحتوى التعليمي:</strong></label>
                <div style="padding:10px;background:#f5f5f5;border-radius:6px;"><?php echo nl2br(htmlspecialchars($test['educational_content'], ENT_QUOTES, 'UTF-8')); ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;">الإحصائيات</h2>
        <div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:20px;">
            <div style="padding:15px;background:#f5f5f5;border-radius:8px;">
                <div style="font-size:24px;font-weight:bold;color:#2196F3;"><?php echo $stats['total_orders']; ?></div>
                <div style="color:#666;">إجمالي الطلبات</div>
            </div>
            <div style="padding:15px;background:#f5f5f5;border-radius:8px;">
                <div style="font-size:24px;font-weight:bold;color:#4CAF50;"><?php echo number_format($stats['total_revenue'], 2); ?> د.ع</div>
                <div style="color:#666;">إجمالي الإيرادات</div>
            </div>
        </div>
    </div>
    
    <?php if (!empty($stats['recent_orders'])): ?>
    <div class="card">
        <h2 style="margin-top:0;">آخر الطلبات</h2>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                    <tr>
                        <th>رقم الطلب</th>
                        <th>المريض</th>
                        <th>الطبيب</th>
                        <th>التاريخ</th>
                        <th>الحالة</th>
                        <th>السعر</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($stats['recent_orders'] as $order): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($order['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['patient_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['doctor_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
                        <td><?php echo htmlspecialchars($order['order_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                        <td>
                            <?php
                            $statusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغي'];
                            $statusColors = ['new' => '#2196F3', 'in_progress' => '#FF9800', 'completed' => '#4CAF50', 'cancelled' => '#f44336'];
                            $status = $order['status'] ?? 'new';
                            ?>
                            <span style="padding:4px 8px;background:<?php echo $statusColors[$status] ?? '#999'; ?>;color:white;border-radius:4px;font-size:12px;">
                                <?php echo $statusLabels[$status] ?? $status; ?>
                            </span>
                        </td>
                        <td><?php echo number_format((float)($order['price'] ?? 0), 2); ?> د.ع</td>
                        <td><a href="index.php?page=orders&action=view&id=<?php echo (int)$order['id']; ?>">عرض</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    
    <?php
    return;
}

if ($action === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=tests');
        exit;
    }
    
    // جلب بيانات الفحص
    $eduCol = '';
    $redirectCol = '';
    $cptCol = '';
    try { $db->query('SELECT educational_content FROM tests LIMIT 1'); $eduCol = ', t.educational_content'; } catch (Throwable $e) {}
    try { $db->query('SELECT redirect_to_branch_id FROM tests LIMIT 1'); $redirectCol = ', t.redirect_to_branch_id'; } catch (Throwable $e) {}
    try { $db->query('SELECT cpt_code FROM tests LIMIT 1'); $cptCol = ', t.cpt_code'; } catch (Throwable $e) {}
    
    try {
        $stmt = $db->prepare(
            'SELECT t.id, t.test_code, t.name, t.default_price' . $cptCol . ', t.unit, t.reference_range, t.method, t.tat_hours,
             t.inventory_item_id, t.consumption_quantity, t.critical_value_min, t.critical_value_max' . $eduCol . $redirectCol . ',
             t.category_id, c.name AS category_name 
             FROM tests t 
             LEFT JOIN test_categories c ON c.id = t.category_id 
             WHERE t.id = ?' . $testsTenantAnd
        );
        $stmt->execute(array_merge([$id], $testsTenantParams));
        $test = $stmt->fetch();
    } catch (Throwable $e) {
        $test = false;
    }
    
    if (!$test) {
        header('Location: index.php?page=tests');
        exit;
    }
    
    // جلب قائمة الفئات
    $categories = [];
    try {
        try {
            $db->query('SELECT tenant_id FROM test_categories LIMIT 1');
            $stmt = $db->prepare('SELECT id, name FROM test_categories WHERE tenant_id = ? ORDER BY name ASC');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, name FROM test_categories ORDER BY name ASC');
        }
        $categories = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب قائمة مواد المخزون
    $inventoryItems = [];
    try {
        try {
            $db->query('SELECT tenant_id FROM inventory_items LIMIT 1');
            $stmt = $db->prepare('SELECT id, item_code, name, unit, current_quantity FROM inventory_items WHERE tenant_id = ? ORDER BY name ASC');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, item_code, name, unit, current_quantity FROM inventory_items ORDER BY name ASC');
        }
        $inventoryItems = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب قائمة الفروع
    $branches = [];
    try {
        try {
            $db->query('SELECT tenant_id FROM branches LIMIT 1');
            $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
        }
        $branches = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // إحصائيات سريعة
    $orderCount = 0;
    try {
        try {
            $db->query('SELECT tenant_id FROM lab_orders LIMIT 1');
            $stmt = $db->prepare('SELECT COUNT(*) FROM order_items oi JOIN lab_orders o ON o.id = oi.order_id WHERE oi.test_id = ? AND o.tenant_id = ?');
            $stmt->execute([$id, $tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->prepare('SELECT COUNT(*) FROM order_items WHERE test_id = ?');
            $stmt->execute([$id]);
        }
        $orderCount = (int)$stmt->fetchColumn();
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>تعديل فحص: <?php echo htmlspecialchars($test['name'], ENT_QUOTES, 'UTF-8'); ?></h1>
        <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
            <a href="index.php?page=tests&action=view&id=<?php echo (int)$id; ?>" class="btn-secondary">← رجوع</a>
            <?php if ($auth->can('tests.create')): ?>
            <a href="index.php?page=tests&action=duplicate&id=<?php echo (int)$id; ?>" class="btn-secondary">نسخ</a>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if (isset($_SESSION['tests_error'])): ?>
        <div class="alert alert-danger" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($_SESSION['tests_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['tests_error']); ?>
        </div>
    <?php endif; ?>
    
    <?php if ($orderCount > 0): ?>
        <div class="alert alert-info" style="margin-bottom:20px;">
            <strong>ملاحظة:</strong> هذا الفحص مستخدم في <?php echo $orderCount; ?> طلب. التعديلات ستؤثر على الطلبات الجديدة فقط.
        </div>
    <?php endif; ?>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;margin-bottom:20px;">المعلومات الأساسية</h2>
        <form method="post" class="form-grid" id="testEditForm">
            <input type="hidden" name="id" value="<?php echo (int)$test['id']; ?>">
            
            <div>
                <label>الكود <span style="color:#999;font-size:0.9em;">(للقراءة فقط)</span></label>
                <input type="text" value="<?php echo htmlspecialchars($test['test_code'], ENT_QUOTES, 'UTF-8'); ?>" readonly disabled style="background:#f5f5f5;">
            </div>
            
            <div>
                <label>اسم الفحص <span class="required">*</span></label>
                <input type="text" name="name" required value="<?php echo htmlspecialchars($test['name'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="اسم الفحص">
            </div>
            
            <div>
                <label>الفئة</label>
                <div style="display:flex;gap:8px;align-items:flex-start;flex-wrap:wrap;">
                    <div style="flex:1;min-width:200px;">
                        <select name="category" id="categorySelect" style="width:100%;">
                            <option value="">— اختر فئة موجودة —</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8'); ?>" 
                                    <?php echo (isset($test['category_id']) && (int)$test['category_id'] === (int)$cat['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8'); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div style="flex:1;min-width:200px;">
                        <div style="display:flex;gap:4px;">
                            <input type="text" name="category_new" id="categoryNew" placeholder="أدخل اسم الفئة الجديدة هنا..." style="flex:1;display:none;">
                            <button type="button" id="toggleCategoryBtn" class="btn-secondary" style="padding:8px 16px;white-space:nowrap;flex-shrink:0;">+ فئة جديدة</button>
                        </div>
                    </div>
                </div>
                <small style="color:#666;font-size:0.85em;display:block;margin-top:6px;padding:8px;background:#f0f9ff;border-radius:4px;">
                    <span id="categoryHint">💡 يمكنك اختيار فئة موجودة من القائمة أعلاه، أو النقر على "فئة جديدة" لإضافة فئة جديدة</span>
                </small>
            </div>
            
            <div>
                <label>السعر (د.ع) <span class="required">*</span></label>
                <input type="number" step="0.01" name="price" required value="<?php echo htmlspecialchars($test['default_price'], ENT_QUOTES, 'UTF-8'); ?>" min="0" placeholder="0.00">
            </div>
            <?php if ($cptCol !== ''): ?>
            <div>
                <label>رمز CPT</label>
                <input type="text" name="cpt_code" value="<?php echo htmlspecialchars($test['cpt_code'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: 80053" maxlength="20">
                <small style="color:#666;font-size:0.85em;">للفوترة والتأمين (اختياري)</small>
            </div>
            <?php endif; ?>
            <div>
                <label>الوحدة</label>
                <input type="text" name="unit" value="<?php echo htmlspecialchars($test['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: mg/dL, g/L, %">
                <small style="color:#666;font-size:0.85em;">الوحدة المستخدمة في النتائج</small>
            </div>
            
            <div class="full-width">
                <label>المدى المرجعي</label>
                <input type="text" name="reference_range" value="<?php echo htmlspecialchars($test['reference_range'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: 70-100 mg/dL أو &lt;5.0">
                <small style="color:#666;font-size:0.85em;">القيم الطبيعية للفحص</small>
            </div>
            
            <div>
                <label>طريقة الفحص</label>
                <input type="text" name="method" value="<?php echo htmlspecialchars($test['method'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: Colorimetric, ELISA, Automated">
            </div>
            
            <div>
                <label>زمن التنفيذ (ساعة)</label>
                <input type="number" name="tat_hours" value="<?php echo (int)($test['tat_hours'] ?? 0); ?>" min="0" placeholder="0">
                <small style="color:#666;font-size:0.85em;">الوقت المتوقع لإنجاز الفحص</small>
            </div>
        </form>
    </div>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;margin-bottom:20px;">القيم الحرجة</h2>
        <form method="post" class="form-grid" id="criticalValuesForm">
            <input type="hidden" name="id" value="<?php echo (int)$test['id']; ?>">
            
            <div>
                <label>القيمة الحرجة (أدنى)</label>
                <input type="number" step="0.01" name="critical_value_min" value="<?php echo htmlspecialchars($test['critical_value_min'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="اختياري">
                <small style="color:#666;font-size:0.85em;">إذا كانت النتيجة أقل من هذه القيمة، سيتم تنبيه الطبيب</small>
            </div>
            
            <div>
                <label>القيمة الحرجة (أعلى)</label>
                <input type="number" step="0.01" name="critical_value_max" value="<?php echo htmlspecialchars($test['critical_value_max'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="اختياري">
                <small style="color:#666;font-size:0.85em;">إذا كانت النتيجة أعلى من هذه القيمة، سيتم تنبيه الطبيب</small>
            </div>
        </form>
    </div>
    
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;margin-bottom:20px;">إدارة المخزون</h2>
        <form method="post" class="form-grid" id="inventoryForm">
            <input type="hidden" name="id" value="<?php echo (int)$test['id']; ?>">
            
            <div>
                <label>مادة المخزون المرتبطة</label>
                <select name="inventory_item_id" id="inventorySelect">
                    <option value="">— بدون ربط —</option>
                    <?php foreach ($inventoryItems as $item): ?>
                        <option value="<?php echo (int)$item['id']; ?>" 
                            <?php echo (int)($test['inventory_item_id'] ?? 0) === (int)$item['id'] ? 'selected' : ''; ?>
                            data-quantity="<?php echo htmlspecialchars($item['current_quantity'] ?? 0, ENT_QUOTES, 'UTF-8'); ?>">
                            <?php echo htmlspecialchars($item['item_code'] . ' - ' . $item['name'], ENT_QUOTES, 'UTF-8'); ?>
                            <?php if (isset($item['current_quantity'])): ?>
                                (المتاح: <?php echo htmlspecialchars($item['current_quantity'], ENT_QUOTES, 'UTF-8'); ?> <?php echo htmlspecialchars($item['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?>)
                            <?php endif; ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <small style="color:#666;font-size:0.85em;">اختر مادة المخزون المستخدمة في هذا الفحص</small>
            </div>
            
            <div>
                <label>كمية الاستهلاك من المخزون</label>
                <input type="number" step="0.01" name="consumption_quantity" value="<?php echo htmlspecialchars($test['consumption_quantity'], ENT_QUOTES, 'UTF-8'); ?>" min="0" placeholder="0.00" id="consumptionQty">
                <small style="color:#666;font-size:0.85em;">كمية المادة المستهلكة لكل فحص</small>
            </div>
        </form>
    </div>
    
    <?php if (count($branches) > 0): try { $db->query('SELECT redirect_to_branch_id FROM tests LIMIT 1'); ?>
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;margin-bottom:20px;">إعادة التوجيه</h2>
        <form method="post" class="form-grid" id="redirectForm">
            <input type="hidden" name="id" value="<?php echo (int)$test['id']; ?>">
            
            <div>
                <label>إعادة توجيه لمختبر مركزي/فرع</label>
                <select name="redirect_to_branch_id">
                    <option value="">— لا إعادة توجيه —</option>
                    <?php foreach ($branches as $b): ?>
                        <option value="<?php echo (int)$b['id']; ?>" 
                            <?php echo (int)($test['redirect_to_branch_id'] ?? 0) === (int)$b['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($b['name'], ENT_QUOTES, 'UTF-8'); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <small style="color:#666;font-size:0.85em;">إذا كان الفحص يتم في فرع آخر، اختر الفرع هنا</small>
            </div>
        </form>
    </div>
    <?php } catch (Throwable $e) {} endif; ?>
    
    <?php if (isset($test['educational_content'])): ?>
    <div class="card" style="margin-bottom:20px;">
        <h2 style="margin-top:0;margin-bottom:20px;">المحتوى التعليمي</h2>
        <form method="post" class="form-grid" id="educationalForm">
            <input type="hidden" name="id" value="<?php echo (int)$test['id']; ?>">
            
            <div class="full-width">
                <label>شرح مبسط للنتيجة (يعرض للمريض)</label>
                <textarea name="educational_content" rows="6" placeholder="مثال: السكر الصائم يقيس مستوى الجلوكوز في الدم بعد الصيام 8 ساعات. القيم الطبيعية: 70-100 ملغ/دل. القيم المرتفعة قد تشير إلى مرض السكري."><?php echo htmlspecialchars($test['educational_content'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                <small style="color:#666;font-size:0.85em;">هذا النص سيظهر للمريض عند عرض النتائج لمساعدته على فهمها</small>
            </div>
        </form>
    </div>
    <?php endif; ?>
    
    <div class="card">
        <div class="full-width form-actions">
            <button type="submit" form="testEditForm" class="btn-primary" style="padding:12px 24px;font-size:16px;">💾 حفظ جميع التعديلات</button>
            <a href="index.php?page=tests&action=view&id=<?php echo (int)$id; ?>" class="btn-secondary">إلغاء</a>
        </div>
    </div>
    
    <script>
    // دمج جميع الحقول في نموذج واحد عند الإرسال
    document.getElementById('testEditForm').addEventListener('submit', function(e) {
        // جمع البيانات من جميع النماذج
        const criticalForm = document.getElementById('criticalValuesForm');
        const inventoryForm = document.getElementById('inventoryForm');
        const redirectForm = document.getElementById('redirectForm');
        const educationalForm = document.getElementById('educationalForm');
        
        // نسخ الحقول من النماذج الأخرى
        if (criticalForm) {
            const criticalMin = criticalForm.querySelector('[name="critical_value_min"]');
            const criticalMax = criticalForm.querySelector('[name="critical_value_max"]');
            if (criticalMin) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'critical_value_min';
                input.value = criticalMin.value;
                this.appendChild(input);
            }
            if (criticalMax) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'critical_value_max';
                input.value = criticalMax.value;
                this.appendChild(input);
            }
        }
        
        if (inventoryForm) {
            const invItem = inventoryForm.querySelector('[name="inventory_item_id"]');
            const consQty = inventoryForm.querySelector('[name="consumption_quantity"]');
            if (invItem) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'inventory_item_id';
                input.value = invItem.value;
                this.appendChild(input);
            }
            if (consQty) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'consumption_quantity';
                input.value = consQty.value;
                this.appendChild(input);
            }
        }
        
        if (redirectForm) {
            const redirectBranch = redirectForm.querySelector('[name="redirect_to_branch_id"]');
            if (redirectBranch) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'redirect_to_branch_id';
                input.value = redirectBranch.value;
                this.appendChild(input);
            }
        }
        
        if (educationalForm) {
            const eduContent = educationalForm.querySelector('[name="educational_content"]');
            if (eduContent) {
                const textarea = document.createElement('textarea');
                textarea.name = 'educational_content';
                textarea.style.display = 'none';
                textarea.value = eduContent.value;
                this.appendChild(textarea);
            }
        }
        
        // معالجة الفئة - إذا تم إدخال فئة جديدة، استخدمها بدلاً من القائمة
        const categorySelect = document.getElementById('categorySelect');
        const categoryNew = document.getElementById('categoryNew');
        if (categoryNew && categoryNew.style.display !== 'none' && categoryNew.value.trim() !== '') {
            // إذا كان حقل الفئة الجديدة مرئي وله قيمة، استخدمه
            const categoryInput = this.querySelector('[name="category"]');
            if (categoryInput) {
                categoryInput.value = categoryNew.value.trim();
            }
        }
    });
    
    // تبديل بين القائمة المنسدلة وحقل النص للفئة
    const categorySelect = document.getElementById('categorySelect');
    const categoryNew = document.getElementById('categoryNew');
    const toggleCategoryBtn = document.getElementById('toggleCategoryBtn');
    const categoryHint = document.getElementById('categoryHint');
    
    if (categorySelect && categoryNew && toggleCategoryBtn && categoryHint) {
        // عند النقر على زر "فئة جديدة"
        toggleCategoryBtn.addEventListener('click', function() {
            if (categoryNew.style.display === 'none' || categoryNew.style.display === '') {
                // إظهار حقل إدخال الفئة الجديدة
                categoryNew.style.display = 'block';
                categoryNew.focus();
                categorySelect.value = ''; // مسح الاختيار من القائمة
                toggleCategoryBtn.textContent = '← استخدام فئة موجودة';
                categoryHint.textContent = 'أدخل اسم الفئة الجديدة في الحقل أعلاه';
            } else {
                // إخفاء حقل إدخال الفئة الجديدة
                categoryNew.style.display = 'none';
                categoryNew.value = '';
                toggleCategoryBtn.textContent = '+ فئة جديدة';
                categoryHint.textContent = 'يمكنك اختيار فئة موجودة من القائمة أو النقر على "فئة جديدة" لإضافة فئة جديدة';
            }
        });
        
        // عند اختيار فئة من القائمة، إخفاء حقل الفئة الجديدة
        categorySelect.addEventListener('change', function() {
            if (this.value !== '') {
                categoryNew.style.display = 'none';
                categoryNew.value = '';
                toggleCategoryBtn.textContent = '+ فئة جديدة';
                categoryHint.textContent = 'تم اختيار الفئة: ' + this.options[this.selectedIndex].text;
            }
        });
        
        // إذا كانت الفئة الحالية موجودة في القائمة، إخفاء حقل النص
        if (categorySelect.value !== '') {
            categoryNew.style.display = 'none';
            categoryHint.textContent = 'تم اختيار الفئة: ' + categorySelect.options[categorySelect.selectedIndex].text;
        } else {
            categoryHint.textContent = 'يمكنك اختيار فئة موجودة من القائمة أو النقر على "فئة جديدة" لإضافة فئة جديدة';
        }
    }
    
    // عرض كمية المخزون عند اختيار مادة
    const inventorySelect = document.getElementById('inventorySelect');
    if (inventorySelect) {
        inventorySelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            const quantity = selectedOption.getAttribute('data-quantity');
            if (quantity && parseFloat(quantity) > 0) {
                // يمكن إضافة تنبيه بصري هنا
            }
        });
    }
    </script>
    
    <?php
    return;
}

if ($action === 'create') {
    $inventoryItems = [];

    try {
        try {
            $db->query('SELECT tenant_id FROM inventory_items LIMIT 1');
            $stmt = $db->prepare('SELECT id, item_code, name, unit FROM inventory_items WHERE tenant_id = ? ORDER BY name ASC');
            $stmt->execute([$tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->query('SELECT id, item_code, name, unit FROM inventory_items ORDER BY name ASC');
        }
        $inventoryItems = $stmt->fetchAll();
    } catch (Throwable $e) {
    }
    ?>
    <div class="page-header">
        <h1>إضافة فحص جديد</h1>
        <a href="index.php?page=tests" class="btn-secondary">← رجوع</a>
    </div>
    <div class="card">
    <form method="post" class="form-grid">
        <div>
            <label>اسم الفحص <span class="required">*</span></label>
            <input type="text" name="name" required placeholder="اسم الفحص">
        </div>
        <div>
            <label>الفئة</label>
            <input type="text" name="category" placeholder="مثال: كيمياء، هيماتولوجي...">
        </div>
        <div>
            <label>السعر</label>
            <input type="number" step="0.01" name="price" value="0">
        </div>
        <?php try { $db->query('SELECT cpt_code FROM tests LIMIT 1'); ?>
        <div>
            <label>رمز CPT</label>
            <input type="text" name="cpt_code" placeholder="مثال: 80053" maxlength="20">
        </div>
        <?php } catch (Throwable $e) {} ?>
        <div>
            <label>الوحدة</label>
            <input type="text" name="unit" placeholder="مثال: mg/dL, g/L...">
        </div>
        <div class="full-width">
            <label>المدى المرجعي</label>
            <input type="text" name="reference_range" placeholder="مثال: 70-100 mg/dL">
        </div>
        <div>
            <label>القيمة الحرجة (أدنى)</label>
            <input type="number" step="0.01" name="critical_value_min" placeholder="اختياري">
        </div>
        <div>
            <label>القيمة الحرجة (أعلى)</label>
            <input type="number" step="0.01" name="critical_value_max" placeholder="اختياري">
        </div>
        <div>
            <label>طريقة الفحص</label>
            <input type="text" name="method" placeholder="مثال: Colorimetric, ELISA...">
        </div>
        <div>
            <label>زمن التنفيذ (ساعة)</label>
            <input type="number" name="tat_hours" value="0">
        </div>
        <div>
            <label>مادة المخزون المرتبطة</label>
            <select name="inventory_item_id">
                <option value="">بدون ربط</option>
                <?php foreach ($inventoryItems as $item): ?>
                    <option value="<?php echo (int)$item['id']; ?>">
                        <?php
                        echo htmlspecialchars($item['item_code'], ENT_QUOTES, 'UTF-8')
                            . ' - '
                            . htmlspecialchars($item['name'], ENT_QUOTES, 'UTF-8');
                        ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label>كمية الاستهلاك من المخزون</label>
            <input type="number" step="0.01" name="consumption_quantity" value="0">
        </div>
        <?php try { $db->query('SELECT educational_content FROM tests LIMIT 1'); ?>
        <div class="full-width">
            <label>محتوى تعليمي (شرح مبسط للنتيجة - يعرض للمريض)</label>
            <textarea name="educational_content" rows="4" placeholder="مثال: السكر الصائم يقيس مستوى الجلوكوز في الدم بعد الصيام 8 ساعات. القيم الطبيعية: 70-100 ملغ/دل"></textarea>
        </div>
        <?php } catch (Throwable $e) {} ?>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">حفظ</button>
            <a href="index.php?page=tests" class="btn-secondary">إلغاء</a>
        </div>
    </form>
    </div>
    <?php
    return;
}

// صفحة القائمة الرئيسية
$tests = [];
$search = trim($_GET['q'] ?? '');

$cptColList = '';
try { $db->query('SELECT cpt_code FROM tests LIMIT 1'); $cptColList = ', t.cpt_code'; } catch (Throwable $e) {}
try {
    $sql = 'SELECT t.id, t.test_code, t.name, t.default_price' . $cptColList . ', t.unit, t.reference_range,
                c.name AS category_name,
                i.name AS inventory_name,
                t.consumption_quantity,
                COUNT(DISTINCT oi.id) AS orders_count
         FROM tests t
         LEFT JOIN test_categories c ON c.id = t.category_id
         LEFT JOIN inventory_items i ON i.id = t.inventory_item_id
         LEFT JOIN order_items oi ON oi.test_id = t.id';
    try { 
        $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); 
        $sql .= ' LEFT JOIN lab_orders o ON o.id = oi.order_id';
    } catch (Throwable $e) {}
    $sql .= ' WHERE 1=1';
    $params = [];
    if ($search !== '') {
        $sql .= ' AND (t.name LIKE :q OR t.test_code LIKE :q2 OR c.name LIKE :q3)';
        $params['q'] = '%' . $search . '%';
        $params['q2'] = '%' . $search . '%';
        $params['q3'] = '%' . $search . '%';
    }
    try { 
        $db->query('SELECT tenant_id FROM tests LIMIT 1'); 
        $sql .= ' AND t.tenant_id = :tid'; 
        $params['tid'] = $tenantId; 
    } catch (Throwable $e) {}
    try { 
        $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); 
        $sql .= ' AND (o.tenant_id = :tid2 OR oi.id IS NULL)'; 
        $params['tid2'] = $tenantId; 
    } catch (Throwable $e) {}
    $sql .= ' GROUP BY t.id ORDER BY t.name ASC LIMIT 500';
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $tests = $stmt->fetchAll();
} catch (Throwable $e) {
}

?>
<div class="page-header">
    <h1>تعريف الفحوصات</h1>
    <div class="actions-bar" style="flex-wrap:wrap;gap:12px;">
        <form method="get" class="search-form" style="display:inline-flex;gap:8px;align-items:center;">
            <input type="hidden" name="page" value="tests">
            <input type="search" name="q" placeholder="ابحث بالاسم أو الكود أو الفئة..." value="<?php echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:200px;">
            <button type="submit" class="btn-secondary">بحث</button>
            <?php if ($search !== ''): ?>
            <a href="index.php?page=tests" class="btn-secondary">إلغاء</a>
            <?php endif; ?>
        </form>
        <?php if ($auth->can('tests.create')): ?>
        <a href="index.php?page=tests&action=create" class="btn-primary">+ فحص جديد</a>
        <?php endif; ?>
    </div>
</div>

<?php if (isset($_SESSION['tests_msg'])): ?>
    <div class="alert alert-info" style="margin-bottom:16px;">
        <?php echo htmlspecialchars($_SESSION['tests_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['tests_msg']); ?>
    </div>
<?php endif; ?>

<?php if (isset($_SESSION['tests_error'])): ?>
    <div class="alert alert-danger" style="margin-bottom:16px;">
        <?php echo htmlspecialchars($_SESSION['tests_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['tests_error']); ?>
    </div>
<?php endif; ?>

<?php if (empty($tests)): ?>
    <div class="card">
        <p style="text-align:center;color:#666;padding:40px;">
            <?php if ($search): ?>
                لم يتم العثور على فحوصات مطابقة للبحث.
            <?php else: ?>
                لا يوجد فحوصات مسجلة حالياً.
            <?php endif; ?>
        </p>
    </div>
<?php else: ?>
<div class="table-wrapper">
<table class="table">
    <thead>
        <tr>
            <th>الكود</th>
            <th>الاسم</th>
            <th>الفئة</th>
            <th>السعر</th>
            <th>الوحدة</th>
            <th>المدى المرجعي</th>
            <th>عدد الطلبات</th>
            <th>المخزون</th>
            <th>إجراءات</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach ($tests as $t): ?>
        <tr>
            <td><?php echo htmlspecialchars($t['test_code'], ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <strong><?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?></strong>
            </td>
            <td><?php echo htmlspecialchars($t['category_name'] ?? 'غير محدد', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo number_format((float)$t['default_price'], 2); ?> د.ع</td>
            <?php if ($cptColList !== ''): ?><td><?php echo htmlspecialchars($t['cpt_code'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td><?php endif; ?>
            <td><?php echo htmlspecialchars($t['unit'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
            <td><?php echo htmlspecialchars($t['reference_range'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <a href="index.php?page=orders&test_id=<?php echo (int)$t['id']; ?>" style="color:#2196F3;">
                    <?php echo (int)($t['orders_count'] ?? 0); ?>
                </a>
            </td>
            <td><?php echo htmlspecialchars($t['inventory_name'] ?? 'غير مرتبط', ENT_QUOTES, 'UTF-8'); ?></td>
            <td>
                <div style="display:flex;gap:8px;flex-wrap:wrap;">
                    <a href="index.php?page=tests&action=view&id=<?php echo (int)$t['id']; ?>" style="padding:4px 12px;background:#2196F3;color:white;text-decoration:none;border-radius:4px;font-size:13px;">عرض</a>
                    <?php if ($auth->can('tests.update')): ?>
                    <a href="index.php?page=tests&action=edit&id=<?php echo (int)$t['id']; ?>" style="padding:4px 12px;background:#FF9800;color:white;text-decoration:none;border-radius:4px;font-size:13px;">تعديل</a>
                    <?php endif; ?>
                    <?php if ($auth->can('tests.create')): ?>
                    <a href="index.php?page=tests&action=duplicate&id=<?php echo (int)$t['id']; ?>" style="padding:4px 12px;background:#9C27B0;color:white;text-decoration:none;border-radius:4px;font-size:13px;">نسخ</a>
                    <?php endif; ?>
                    <?php if ($auth->can('tests.delete')): ?>
                    <a href="index.php?page=tests&action=delete&id=<?php echo (int)$t['id']; ?>" 
                       style="padding:4px 12px;background:#f44336;color:white;text-decoration:none;border-radius:4px;font-size:13px;"
                       onclick="return confirm('هل أنت متأكد من حذف هذا الفحص؟');">حذف</a>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
</div>
<?php endif; ?>
