<?php
/**
 * المدى المرجعي حسب العمر والجنس — إدارة reference_ranges
 */
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();
$testTenantAnd = '';
$testTenantAndNoAlias = '';
$testTenantParams = [];
try {
    $db->query('SELECT tenant_id FROM tests LIMIT 1');
    $testTenantAnd = ' AND t.tenant_id = ?';
    $testTenantAndNoAlias = ' AND tenant_id = ?';
    $testTenantParams = [$tenantId];
} catch (Throwable $e) {}

$action = $_GET['action'] ?? 'index';
$testId = (int)($_GET['test_id'] ?? 0);

// إنشاء reference_ranges إن لم يكن الجدول موجوداً
try {
    $db->query('SELECT id FROM reference_ranges LIMIT 1');
} catch (Throwable $e) {
    try {
        $db->exec("CREATE TABLE 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)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    } catch (Throwable $e2) {}
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_range']) && $auth->can('tests.update')) {
        $testIdPost = (int)($_POST['test_id'] ?? 0);
        $ageMin = trim($_POST['age_min'] ?? '') !== '' ? (float)$_POST['age_min'] : null;
        $ageMax = trim($_POST['age_max'] ?? '') !== '' ? (float)$_POST['age_max'] : null;
        $gender = in_array($_POST['gender'] ?? '', ['M','F','both']) ? $_POST['gender'] : 'both';
        $refRange = trim($_POST['reference_range'] ?? '');
        $critMin = trim($_POST['critical_value_min'] ?? '') !== '' ? (float)$_POST['critical_value_min'] : null;
        $critMax = trim($_POST['critical_value_max'] ?? '') !== '' ? (float)$_POST['critical_value_max'] : null;

        if ($testIdPost > 0 && $refRange !== '') {
            try {
                $stmt = $db->prepare('SELECT id FROM tests WHERE id = ?' . $testTenantAndNoAlias);
                $stmt->execute(array_merge([$testIdPost], $testTenantParams));
                if ($stmt->fetch()) {
                    $db->prepare('INSERT INTO reference_ranges (test_id, age_min_years, age_max_years, gender, reference_range, critical_value_min, critical_value_max) VALUES (?, ?, ?, ?, ?, ?, ?)')
                        ->execute([$testIdPost, $ageMin, $ageMax, $gender, $refRange, $critMin, $critMax]);
                    $_SESSION['ref_ranges_msg'] = 'تم إضافة المدى المرجعي.';
                }
            } catch (Throwable $e) {}
        }
        header('Location: index.php?page=reference_ranges&test_id=' . $testIdPost);
        exit;
    }
    if (isset($_POST['delete_range'])) {
        $rid = (int)($_POST['range_id'] ?? 0);
        if ($rid > 0 && $auth->can('tests.update')) {
            try {
                $db->prepare('DELETE FROM reference_ranges WHERE id = ?')->execute([$rid]);
                $_SESSION['ref_ranges_msg'] = 'تم حذف المدى المرجعي.';
            } catch (Throwable $e) {}
        }
        header('Location: index.php?page=reference_ranges' . ($testId > 0 ? '&test_id=' . $testId : ''));
        exit;
    }
}

$tests = [];
try {
    $stmt = $db->prepare('SELECT id, name, test_code, reference_range FROM tests t WHERE 1=1' . $testTenantAnd . ' ORDER BY name');
    $stmt->execute($testTenantParams);
    $tests = $stmt->fetchAll();
} catch (Throwable $e) {}

$ranges = [];
$selectedTest = null;
if ($testId > 0) {
    try {
        $stmt = $db->prepare('SELECT id, name, test_code FROM tests WHERE id = ?' . $testTenantAndNoAlias);
        $stmt->execute(array_merge([$testId], $testTenantParams));
        $selectedTest = $stmt->fetch();
    } catch (Throwable $e) {}
    if ($selectedTest) {
        $stmt = $db->prepare('SELECT * FROM reference_ranges WHERE test_id = ? ORDER BY age_min_years ASC, gender');
        $stmt->execute([$testId]);
        $ranges = $stmt->fetchAll();
    }
}
?>
<div class="page-header">
    <h1>المدى المرجعي حسب العمر والجنس</h1>
    <a href="index.php?page=tests" class="btn-secondary">← الفحوصات</a>
</div>

<?php if (!empty($_SESSION['ref_ranges_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['ref_ranges_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['ref_ranges_msg']); ?></div>
<?php endif; ?>

<div class="section-card">
    <h3>اختر الفحص</h3>
    <form method="get">
        <input type="hidden" name="page" value="reference_ranges">
        <select name="test_id" onchange="this.form.submit()" style="min-width:280px;padding:10px;">
            <option value="">— اختر فحص —</option>
            <?php foreach ($tests as $t): ?>
            <option value="<?php echo (int)$t['id']; ?>" <?php echo $testId === (int)$t['id'] ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($t['name'] . ' (' . $t['test_code'] . ')', ENT_QUOTES, 'UTF-8'); ?>
            </option>
            <?php endforeach; ?>
        </select>
    </form>
</div>

<?php if ($selectedTest && $auth->can('tests.update')): ?>
<div class="section-card">
    <h3>إضافة مدى مرجعي — <?php echo htmlspecialchars($selectedTest['name'], ENT_QUOTES, 'UTF-8'); ?></h3>
    <form method="post" class="form-grid">
        <input type="hidden" name="add_range" value="1">
        <input type="hidden" name="test_id" value="<?php echo (int)$testId; ?>">
        <div>
            <label>العمر من (سنة)</label>
            <input type="number" step="0.1" name="age_min" placeholder="فارغ = لا حد">
        </div>
        <div>
            <label>العمر إلى (سنة)</label>
            <input type="number" step="0.1" name="age_max" placeholder="فارغ = لا حد">
        </div>
        <div>
            <label>الجنس</label>
            <select name="gender">
                <option value="both">الكل</option>
                <option value="M">ذكر</option>
                <option value="F">أنثى</option>
            </select>
        </div>
        <div>
            <label>المدى المرجعي</label>
            <input type="text" name="reference_range" required placeholder="مثال: 3.5-5.5 أو &gt;10">
        </div>
        <div>
            <label>قيمة حرجة أدنى</label>
            <input type="number" step="0.001" name="critical_value_min" placeholder="اختياري">
        </div>
        <div>
            <label>قيمة حرجة أعلى</label>
            <input type="number" step="0.001" name="critical_value_max" placeholder="اختياري">
        </div>
        <div class="full-width form-actions">
            <button type="submit" class="btn-primary">إضافة</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php if ($selectedTest): ?>
<div class="section-card">
    <h3>المدي المرجعية المعرفة — <?php echo htmlspecialchars($selectedTest['name'], ENT_QUOTES, 'UTF-8'); ?></h3>
    <p style="color:var(--text-muted);margin-bottom:12px;">إذا لم يُعرّف مدى حسب العمر/الجنس، يُستخدم المدى الافتراضي من تعريف الفحص.</p>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>العمر (سنة)</th>
                    <th>الجنس</th>
                    <th>المدى المرجعي</th>
                    <th>قيمة حرجة أدنى</th>
                    <th>قيمة حرجة أعلى</th>
                    <?php if ($auth->can('tests.update')): ?><th>إجراء</th><?php endif; ?>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($ranges as $r): ?>
                <tr>
                    <td><?php
                    $aMin = $r['age_min_years'] !== null ? (float)$r['age_min_years'] : null;
                    $aMax = $r['age_max_years'] !== null ? (float)$r['age_max_years'] : null;
                    if ($aMin === null && $aMax === null) echo '—';
                    elseif ($aMin === null) echo '&lt; ' . $aMax;
                    elseif ($aMax === null) echo '&gt; ' . $aMin;
                    else echo $aMin . ' – ' . $aMax;
                    ?></td>
                    <td><?php echo $r['gender'] === 'M' ? 'ذكر' : ($r['gender'] === 'F' ? 'أنثى' : 'الكل'); ?></td>
                    <td><?php echo htmlspecialchars($r['reference_range'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo $r['critical_value_min'] !== null ? htmlspecialchars($r['critical_value_min'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
                    <td><?php echo $r['critical_value_max'] !== null ? htmlspecialchars($r['critical_value_max'], ENT_QUOTES, 'UTF-8') : '—'; ?></td>
                    <?php if ($auth->can('tests.update')): ?>
                    <td>
                        <form method="post" style="display:inline;" onsubmit="return confirm('حذف هذا المدى؟');">
                            <input type="hidden" name="delete_range" value="1">
                            <input type="hidden" name="range_id" value="<?php echo (int)$r['id']; ?>">
                            <button type="submit" class="btn-secondary btn-sm">حذف</button>
                        </form>
                    </td>
                    <?php endif; ?>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (empty($ranges)): ?>
    <p class="patients-empty">لا توجد مدى مرجعية حسب العمر/الجنس لهذا الفحص. أضف واحدة أعلاه.</p>
    <?php endif; ?>
</div>
<?php endif; ?>
