<?php
declare(strict_types=1);

/* ---------------------------------------------------------
   1) AJAX MOTORU (STANDALONE) - ASLA BOZMA
------------------------------------------------------------ */
if (isset($_GET['action'])) {
    while (ob_get_level()) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');

    global $db, $conn, $pdo;
    $db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);

    if (!$db_obj) {
        $db_path = realpath(__DIR__ . '/../core/db.php');
        if (file_exists($db_path)) { require_once $db_path; }
        $db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);
    }

    $q = $db_obj->query("SELECT * FROM dislab_tanimlari WHERE is_active = 1 LIMIT 1");
    $conf = $q->fetch(PDO::FETCH_ASSOC);

    try {
        /* ---------------------------
           AKSİYON 1: LİSTELEME
        --------------------------- */
        if ($_GET['action'] === 'fetch') {
            $client = new SoapClient($conf['ws_url'] . "?WSDL", ['trace' => 1, 'soap_version' => SOAP_1_2]);

            $params = [
                'query' => [
                    'KurumBilgileri' => [
                        'WebUserKurumId' => 0,
                        'KullaniciAdi'   => (string)$conf['username'],
                        'Sifre'          => (string)$conf['pass_enc'],
                        'Kodu'           => (string)$conf['kurum_kodu'],
                        'KurumKodu'      => ''
                    ],
                    'DoktorBilgileri' => ['KimlikNo' => 0, 'Adi' => '', 'Soyadi' => ''],
                    'Bas' => (new DateTime($_GET['start']))->format('Y-m-d\TH:i:s'),
                    'Son' => (new DateTime($_GET['end']))->format('Y-m-d\TH:i:s'),
                    'KayitDurumu' => $_GET['status'] ?? 'Rapor'
                ]
            ];

            $res = $client->HastaListesiGetir($params);
            $list = [];
            if (isset($res->HastaListesi->Liste->HastaDetay)) {
                $data = $res->HastaListesi->Liste->HastaDetay;
                $list = is_array($data) ? $data : [$data];
            }

            ob_start();

            if (empty($list)) {
                echo '<div class="nl-empty">
                        <div class="nl-empty-icon"><i class="bi bi-inbox"></i></div>
                        <div class="nl-empty-title">Kayıt bulunamadı</div>
                        <div class="nl-empty-sub">Tarih aralığını veya durumu değiştirip tekrar deneyin.</div>
                      </div>';
            } else {
                echo '<div class="nl-head-row d-none d-lg-grid">
                        <div>HASTA</div>
                        <div>ÖRNEK NO</div>
                        <div>TARİH</div>
                        <div class="text-lg-center">DURUM</div>
                        <div class="text-end">İŞLEM</div>
                      </div>';

                foreach ($list as $p) {
                    $adi   = (string)($p->Adi ?? '');
                    $soyad = (string)($p->Soyadi ?? '');
                    $full  = trim($adi . ' ' . $soyad);
                    $tc    = (string)($p->KimlikNo ?? '-');
                    $ornek = (string)($p->OrnekNo ?? '-');
                    $tarih = (string)($p->Tarih ?? '-');
                    $durum = (string)($p->KayitDurumu ?? 'Default');

                    $st = mb_strtolower(trim($durum));
                    $st = str_replace(['ı','İ',' '], ['i','i',''], $st);
                    ?>
                    <div class="nl-data-row shadow-sm border mb-3">
                        <div class="nl-col patient-box">
                            <div class="nl-avatar shadow-sm"><?= htmlspecialchars(mb_substr($adi ?: 'H', 0, 1)) ?></div>
                            <div class="nl-info">
                                <div class="nl-name text-dark fw-bold"><?= htmlspecialchars($full ?: '-') ?></div>
                                <div class="nl-sub text-muted small">TC: <?= htmlspecialchars($tc) ?></div>
                            </div>
                        </div>

                        <div class="nl-col barcode-box">
                            <div class="nl-label d-lg-none">ÖRNEK NO</div>
                            <div class="nl-barcode-badge shadow-sm font-monospace"><?= htmlspecialchars($ornek) ?></div>
                        </div>

                        <div class="nl-col date-box">
                            <div class="nl-label d-lg-none">TARİH</div>
                            <div class="small fw-semibold text-secondary"><?= htmlspecialchars($tarih) ?></div>
                        </div>

                        <div class="nl-col status-box text-lg-center">
                            <div class="nl-label d-lg-none">DURUM</div>
                            <span class="nl-status-pill st-<?= htmlspecialchars($st ?: 'default') ?>">
                                <?= htmlspecialchars($durum ?: '-') ?>
                            </span>
                        </div>

                        <div class="nl-col action-box text-end">
                            <button class="btn btn-outline-primary w-100 rounded-3 fw-bold btn-sm py-2"
                                    onclick="fetchDetail('<?= htmlspecialchars($ornek) ?>', '<?= htmlspecialchars($full) ?>')">
                                <i class="bi bi-file-earmark-text me-1"></i> Detay
                            </button>
                        </div>
                    </div>
                    <?php
                }
            }

            $html = ob_get_clean();
            echo json_encode(['success' => true, 'html' => $html, 'count' => count($list)]);
            exit;
        }

        /* ---------------------------
           AKSİYON 2: DETAY (CURL)
        --------------------------- */
        if ($_GET['action'] === 'fetch_detail') {

            $test_barkod = trim((string)($_GET['ornekNo'] ?? ''));

            $xml_payload = '<?xml version="1.0" encoding="utf-8"?>
            <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
              <soap:Body>
                <HastaSonucSorgulaOrnekNo xmlns="http://tenay.com.tr/">
                  <order>
                    <KurumBilgileri>
                      <KullaniciAdi>' . $conf['username'] . '</KullaniciAdi>
                      <Sifre>' . $conf['pass_enc'] . '</Sifre>
                      <Kodu>' . $conf['kurum_kodu'] . '</Kodu>
                    </KurumBilgileri>
                    <OrnekNo>' . $test_barkod . '</OrnekNo>
                    <Rapor>false</Rapor>
                  </order>
                </HastaSonucSorgulaOrnekNo>
              </soap:Body>
            </soap:Envelope>';

            $ch = curl_init((string)$conf['ws_url']);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_payload);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: text/xml; charset=utf-8',
                'SOAPAction: "http://tenay.com.tr/HastaSonucSorgulaOrnekNo"'
            ]);
            $response = curl_exec($ch);
            curl_close($ch);

            // --- Helpers: numeric parse + status calc ---
            $toFloat = function($v): ?float {
                $s = trim((string)$v);
                if ($s === '' || mb_strtolower($s) === 'null') return null;
                if (!preg_match('/-?\d+(?:[.,]\d+)?/u', $s, $m)) return null;
                $num = str_replace(',', '.', $m[0]);
                return is_numeric($num) ? (float)$num : null;
            };

            $normalizeStatus = function(string $raw): string {
                $s = mb_strtolower(trim($raw));
                if (str_contains($s, 'panik')) return 'panik';
                if (str_contains($s, 'yuk'))   return 'yuksek';
                if (str_contains($s, 'dus'))   return 'dusuk';
                if (str_contains($s, 'norm'))  return 'normal';
                return 'none';
            };

            $calcStatus = function($sonucStr, $minStr, $maxStr, $refDurumStr) use ($toFloat, $normalizeStatus): array {
                $sonucRaw = trim((string)$sonucStr);
                $minRaw   = trim((string)$minStr);
                $maxRaw   = trim((string)$maxStr);
                $refDurum = $normalizeStatus((string)$refDurumStr);

                $sonuc = $toFloat($sonucRaw);
                $min   = $toFloat($minRaw);
                $max   = $toFloat($maxRaw);

                $status = 'none';

                if ($sonuc !== null && ($min !== null || $max !== null)) {
                    if ($min !== null && $sonuc < $min) $status = 'dusuk';
                    else if ($max !== null && $sonuc > $max) $status = 'yuksek';
                    else $status = 'normal';
                }

                if ($refDurum === 'panik') $status = 'panik';
                if ($status === 'none' && $refDurum !== 'none') $status = $refDurum;

                $map = [
                    'normal' => ['label' => 'Normal', 'class' => 'bg-success-subtle text-success border border-success-subtle', 'icon' => 'bi-check-circle'],
                    'yuksek' => ['label' => 'Yüksek', 'class' => 'bg-danger-subtle text-danger border border-danger-subtle', 'icon' => 'bi-arrow-up-circle'],
                    'dusuk'  => ['label' => 'Düşük',  'class' => 'bg-warning-subtle text-warning border border-warning-subtle', 'icon' => 'bi-arrow-down-circle'],
                    'panik'  => ['label' => 'Panik',  'class' => 'bg-danger text-white', 'icon' => 'bi-exclamation-triangle-fill'],
                    'none'   => ['label' => 'Belirsiz', 'class' => 'bg-secondary-subtle text-secondary border border-secondary-subtle', 'icon' => 'bi-dash-circle'],
                ];

                return [$status, $map[$status]];
            };

            ob_start();

            if ($response && (stripos($response, 'TetkikSonuc') !== false || stripos($response, 'Tetkikler') !== false)) {

                $clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:', 'diffgr:', 'msdata:'], '', (string)$response);
                $xml = simplexml_load_string($clean_xml);

                if (!$xml) {
                    echo '<div class="alert alert-danger text-center mb-0">XML parse edilemedi.</div>';
                } else {

                    $results = $xml->xpath('//*[local-name()="TetkikSonuc"]') ?: [];

                    $hastaAdi = (string)($xml->xpath('//*[local-name()="HastaBilgileri"]/*[local-name()="Adi"]')[0] ?? '');
                    $hastaSoy = (string)($xml->xpath('//*[local-name()="HastaBilgileri"]/*[local-name()="Soyadi"]')[0] ?? '');
                    $hastaTC  = (string)($xml->xpath('//*[local-name()="HastaBilgileri"]/*[local-name()="KimlikNo"]')[0] ?? '');
                    $hastaFull = trim($hastaAdi . ' ' . $hastaSoy);

                    $rows = [];
                    $hasPanic = false;

                    foreach ($results as $r) {
                        $testAdi = (string)($r->Adi ?? '');
                        $sonuc   = (string)($r->Sonuc ?? '');
                        $birim   = (string)($r->Birim ?? '');
                        $rMin    = (string)($r->ReferansMin ?? '');
                        $rMax    = (string)($r->ReferansMax ?? '');
                        $refDur  = (string)($r->ReferansDurum ?? '');

                        [$statusKey, $ui] = $calcStatus($sonuc, $rMin, $rMax, $refDur);
                        if ($statusKey === 'panik') $hasPanic = true;

                        $ozel = trim((string)($r->OzelNormalDeger ?? ''));
                        $acik = trim((string)($r->Aciklama ?? ''));

                        $rows[] = [
                            'test' => $testAdi,
                            'sonuc' => $sonuc,
                            'birim' => $birim,
                            'min' => $rMin,
                            'max' => $rMax,
                            'statusKey' => $statusKey,
                            'ui' => $ui,
                            'ozel' => $ozel,
                            'acik' => $acik,
                        ];
                    }
                    ?>
                    <div class="mb-3 p-3 rounded-3 border bg-light">
                        <div class="fw-bold"><?= htmlspecialchars($hastaFull ?: 'Hasta') ?></div>
                        <div class="small text-muted">TC: <?= htmlspecialchars($hastaTC ?: '-') ?></div>
                    </div>

                    <?php if ($hasPanic): ?>
                        <div class="alert alert-danger d-flex align-items-start gap-2 mb-3">
                            <i class="bi bi-exclamation-triangle-fill fs-5"></i>
                            <div>
                                <div class="fw-bold">Panik Değer Uyarısı</div>
                                <div class="small">En az bir tetkikte “Panik” durum tespit edildi. Lütfen sonuçları öncelikli değerlendirin.</div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (empty($rows)): ?>
                        <div class="alert alert-warning text-center mb-0">Sonuç bulunamadı.</div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle border nl-result-table">
                                <thead class="bg-light">
                                    <tr class="small fw-bold text-muted">
                                        <th>TEST</th>
                                        <th class="text-center">SONUÇ</th>
                                        <th class="text-center">BİRİM</th>
                                        <th class="text-center">REFERANS</th>
                                        <th class="text-end">DURUM</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php foreach ($rows as $row):
                                    $refText = '-';
                                    if (trim($row['min']) !== '' || trim($row['max']) !== '') {
                                        $refText = trim($row['min']) . ' - ' . trim($row['max']);
                                    }

                                    $notes = [];
                                    if ($row['ozel'] !== '') $notes[] = '<span class="nl-note-chip">Özel Normal: ' . htmlspecialchars($row['ozel']) . '</span>';
                                    if ($row['acik'] !== '') $notes[] = '<span class="nl-note-chip">Not: ' . htmlspecialchars($row['acik']) . '</span>';
                                ?>
                                    <!-- SATIR CLASS: arka plan renklendirme için -->
                                    <tr class="flag-<?= htmlspecialchars($row['statusKey']) ?>">
                                        <td class="fw-bold nl-test-cell flag-<?= htmlspecialchars($row['statusKey']) ?>">
                                            <?= htmlspecialchars($row['test'] ?: '-') ?>

                                            <?php if (!empty($notes)): ?>
                                                <div class="nl-test-note mt-1">
                                                    <?= implode(' ', $notes) ?>
                                                </div>
                                            <?php endif; ?>
                                        </td>

                                        <td class="text-center">
                                            <span class="badge bg-primary-subtle text-primary border border-primary-subtle px-3 py-2">
                                                <?= htmlspecialchars($row['sonuc'] ?: '-') ?>
                                            </span>
                                        </td>

                                        <td class="text-center text-muted">
                                            <?= htmlspecialchars($row['birim'] ?: '-') ?>
                                        </td>

                                        <td class="text-center font-monospace small">
                                            <?= htmlspecialchars($refText) ?>
                                        </td>

                                        <td class="text-end">
                                            <span class="badge px-3 py-2 <?= htmlspecialchars($row['ui']['class']) ?>">
                                                <i class="bi <?= htmlspecialchars($row['ui']['icon']) ?> me-1"></i>
                                                <?= htmlspecialchars($row['ui']['label']) ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <div class="small text-muted mt-2 d-lg-none">
                            <i class="bi bi-arrows-move me-1"></i> Tabloda yatay kaydırma yapabilirsiniz.
                        </div>
                    <?php endif; ?>
                    <?php
                }

            } else {
                echo '<div class="alert alert-warning text-center mb-0">Onaylı sonuç bulunamadı.</div>';
            }

            $html = ob_get_clean();
            echo json_encode(['success' => true, 'html' => $html]);
            exit;
        }

    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

/* ---------------------------------------------------------
   2) HTML TASARIMI
------------------------------------------------------------ */
global $db, $conn, $pdo;
$db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);
$config_main = $db_obj->query("SELECT * FROM dislab_tanimlari WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);
?>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

<style>
    :root{
        --nl-bg: #f6f7fb;
        --nl-card: #ffffff;
        --nl-border: #e5e7eb;
        --nl-text: #0f172a;
        --nl-muted: #64748b;
        --nl-soft: #f1f5f9;
        --nl-primary: #2563eb;
        --nl-primary-soft: #eef2ff;
        --nl-radius: 16px;
        --nl-max: 1480px;
    }

    body { background: var(--nl-bg); }
    .nl-scope { font-family: 'Inter', sans-serif; color: var(--nl-text); }

    .nl-shell{
        max-width: var(--nl-max);
        margin: 0 auto;
        padding: 0 14px;
    }

    .nl-toolbar{
        background: var(--nl-card);
        border: 1px solid var(--nl-border);
        border-radius: var(--nl-radius);
        padding: 14px;
        position: sticky;
        top: 12px;
        z-index: 50;

        /* Mobil taşma engeli */
        overflow: hidden;
    }

    .nl-pill{
        display:inline-flex; align-items:center; gap:8px;
        padding: 10px 12px;
        border-radius: 999px;
        border: 1px solid var(--nl-border);
        background: #fff;
        font-weight: 800;
        color: var(--nl-primary);
        box-shadow: 0 6px 18px rgba(15, 23, 42, .04);
        white-space: nowrap;
        width: 100%;
        justify-content: center;
    }

    .nl-label {
        font-size: 0.70rem;
        font-weight: 800;
        color: #94a3b8;
        text-transform: uppercase;
        margin-bottom: 6px;
        letter-spacing: .04em;
    }

    .nl-input-ui{
        width: 100%;
        height: 44px;
        border-radius: 12px;
        border: 1px solid var(--nl-border);
        background: #fff;
        padding: 0 12px;
        outline: none;
        font-weight: 600;
        color: var(--nl-text);
        transition: .15s;
        max-width: 100%;
        min-width: 0;
    }
    .nl-input-ui:focus{
        border-color: rgba(37,99,235,.35);
        box-shadow: 0 0 0 4px rgba(37,99,235,.10);
    }

    .nl-btn-search{
        height: 44px;
        width: 100%;
        border: 0;
        border-radius: 12px;
        background: var(--nl-primary);
        color: #fff;
        font-weight: 800;
        letter-spacing: .02em;
        transition: .15s;
        max-width: 100%;
        min-width: 0;
        white-space: nowrap;
    }
    .nl-btn-search:hover{ filter: brightness(.95); }
    .nl-btn-search:active{ transform: translateY(1px); }

    /* Mobil taşma kilidi (Bootstrap grid min-width fix) */
    #nlFilterForm .col-12,
    #nlFilterForm .col-md-6,
    #nlFilterForm .col-lg-3,
    #nlFilterForm .col-lg-2,
    #nlFilterForm .col-lg-1 { min-width: 0; }

    #nlFilterForm input,
    #nlFilterForm select,
    #nlFilterForm button { max-width: 100%; min-width: 0; }

    .nl-head-row{
        background: transparent;
        border: 1px dashed rgba(148,163,184,.6);
        border-radius: 14px;
        padding: 10px 18px;
        margin-bottom: 10px;
        color: #94a3b8;
        font-size: .75rem;
        font-weight: 900;
        letter-spacing: .06em;
        text-transform: uppercase;

        display: grid;
        align-items: center;
        gap: 10px;
        grid-template-columns: 2.5fr 1fr 1fr 1fr 0.9fr;
    }

    .nl-data-row{
        background: var(--nl-card);
        border: 1px solid var(--nl-border);
        border-radius: var(--nl-radius);
        padding: 14px 18px;
        display: grid;
        align-items: center;
        gap: 10px;
        grid-template-columns: 2.5fr 1fr 1fr 1fr 0.9fr;
        transition: .15s;
    }
    .nl-data-row:hover{
        box-shadow: 0 18px 40px rgba(15,23,42,.06);
        transform: translateY(-1px);
    }

    @media (max-width: 991px){
        .nl-toolbar{ position: static; }
        .nl-data-row{
            grid-template-columns: 1fr;
            padding: 16px 16px;
        }
        .nl-col{
            border-bottom: 1px solid #f1f5f9;
            padding: 10px 0;
        }
        .nl-col:last-child{ border-bottom: none; padding-bottom: 0; }
        .nl-label{ margin-bottom: 4px; }
        .action-box{ padding-top: 10px !important; }
    }

    .nl-avatar{
        width: 44px; height: 44px;
        background: var(--nl-primary-soft);
        color: var(--nl-primary);
        border-radius: 12px;
        display:flex; align-items:center; justify-content:center;
        font-weight: 900;
        flex: 0 0 auto;
    }
    .patient-box{ display:flex; align-items:center; gap: 12px; min-width: 0; }
    .nl-info{ min-width: 0; }
    .nl-name{ font-size: .98rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
    .nl-sub{ color: var(--nl-muted); }

    .nl-barcode-badge{
        background: var(--nl-soft);
        padding: 7px 12px;
        border-radius: 12px;
        font-weight: 800;
        border: 1px solid var(--nl-border);
        width: fit-content;
        max-width: 100%;
    }

    .nl-status-pill{
        padding: 7px 14px;
        border-radius: 999px;
        font-size: .75rem;
        font-weight: 900;
        border: 1px solid transparent;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        width: fit-content;
    }
    .st-rapor{ background:#dcfce7; color:#166534; border-color:#bbf7d0; }
    .st-labkabul{ background:#ffedd5; color:#9a3412; border-color:#fed7aa; }
    .st-none, .st-default{ background:#e2e8f0; color:#334155; border-color:#cbd5e1; }

    .nl-empty{
        background: var(--nl-card);
        border: 1px dashed rgba(148,163,184,.55);
        border-radius: var(--nl-radius);
        padding: 46px 18px;
        text-align: center;
        color: var(--nl-muted);
    }
    .nl-empty-icon{
        width: 52px; height: 52px;
        display:inline-flex; align-items:center; justify-content:center;
        border-radius: 16px;
        background: var(--nl-soft);
        border: 1px solid var(--nl-border);
        font-size: 1.4rem;
        margin-bottom: 10px;
        color: #475569;
    }
    .nl-empty-title{ font-weight: 900; color: #334155; }
    .nl-empty-sub{ font-size: .9rem; margin-top: 4px; }

    #nl-wait-layer{
        position: fixed; inset: 0;
        background: rgba(246,247,251,0.92);
        backdrop-filter: blur(10px);
        display:none;
        align-items:center;
        justify-content:center;
        z-index: 10000;
        flex-direction: column;
    }

    .modal-content{ border-radius: 22px; overflow:hidden; border:none; }

    /* ====== MODAL: Sol şerit + notlar ====== */
    .nl-result-table .nl-test-cell{
        position: relative;
        padding-left: 18px;
        min-width: 220px;
    }
    .nl-result-table .nl-test-cell::before{
        content:"";
        position:absolute;
        left: 6px;
        top: 10px;
        bottom: 10px;
        width: 4px;
        border-radius: 999px;
        background: transparent;
        opacity: .95;
    }

    .nl-result-table .nl-test-cell.flag-yuksek::before{ background:#ef4444; }
    .nl-result-table .nl-test-cell.flag-dusuk::before{ background:#f59e0b; }
    .nl-result-table .nl-test-cell.flag-panik::before{ background:#b91c1c; }
    .nl-result-table .nl-test-cell.flag-normal::before{ background:#22c55e; }
    .nl-result-table .nl-test-cell.flag-none::before{ background:#94a3b8; }

    .nl-test-note{ display:flex; flex-wrap: wrap; gap: 6px; }
    .nl-note-chip{
        display:inline-flex;
        align-items:center;
        padding: 5px 10px;
        border-radius: 999px;
        background: #f1f5f9;
        border: 1px solid #e2e8f0;
        font-size: .75rem;
        font-weight: 700;
        color: #475569;
        line-height: 1.1;
    }

    /* ====== MODAL: SATIR ARKAPLANI (çok hafif) ====== */
    .nl-result-table tbody tr.flag-yuksek { background: rgba(239, 68, 68, 0.06); }
    .nl-result-table tbody tr.flag-dusuk  { background: rgba(245, 158, 11, 0.08); }
    .nl-result-table tbody tr.flag-panik  { background: rgba(185, 28, 28, 0.12); }
    .nl-result-table tbody tr.flag-normal { background: rgba(34, 197, 94, 0.05); }

    /* Hover’da renk bozulmasın */
    .nl-result-table.table-hover tbody tr.flag-yuksek:hover,
    .nl-result-table.table-hover tbody tr.flag-dusuk:hover,
    .nl-result-table.table-hover tbody tr.flag-panik:hover,
    .nl-result-table.table-hover tbody tr.flag-normal:hover{
        filter: brightness(0.99);
    }

    @media (max-width: 576px){
        .nl-result-table .nl-test-cell{ min-width: 180px; }
        .nl-note-chip{ font-size: .72rem; }
    }
</style>

<div id="nl-wait-layer" class="nl-scope">
    <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;"></div>
    <div class="mt-3 fw-bold">Servis sorgulanıyor...</div>
    <div class="small text-muted">Lütfen bekleyin</div>
</div>

<div class="modal fade" id="sonucModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered">
        <div class="modal-content nl-scope shadow-lg">
            <div class="modal-header border-bottom bg-light px-4">
                <div>
                    <h5 class="modal-title fw-bold mb-0" id="modalPatientName">Hasta Bilgisi</h5>
                    <p class="small text-muted mb-0">Onaylı sonuç detayları</p>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4" id="modalResultBody"></div>
            <div class="modal-footer border-top bg-light">
                <button type="button" class="btn btn-secondary fw-bold px-4" data-bs-dismiss="modal">Kapat</button>
            </div>
        </div>
    </div>
</div>

<div class="nl-scope py-3">
    <div class="nl-shell">
        <div class="nl-toolbar shadow-sm mb-3">
            <form id="nlFilterForm" class="row g-2 g-md-3 align-items-end">
                <div class="col-12 col-md-6 col-lg-3">
                    <label class="nl-label d-block">Başlangıç</label>
                    <input type="datetime-local" name="start" class="nl-input-ui"
                           value="<?= date('Y-m-d\T00:00', strtotime('-3 days')) ?>">
                </div>

                <div class="col-12 col-md-6 col-lg-3">
                    <label class="nl-label d-block">Bitiş</label>
                    <input type="datetime-local" name="end" class="nl-input-ui"
                           value="<?= date('Y-m-d\T23:59') ?>">
                </div>

                <div class="col-12 col-md-6 col-lg-3">
                    <label class="nl-label d-block">Durum</label>
                    <select name="status" class="nl-input-ui">
                        <option value="Rapor">Rapor (Onaylı)</option>
                        <option value="LabKabul">Lab Kabul</option>
                        <option value="None">Hepsi</option>
                    </select>
                </div>

                <div class="col-12 col-md-6 col-lg-2">
                    <button type="submit" class="nl-btn-search shadow-sm">
                        <i class="bi bi-search me-1"></i> Sorgula
                    </button>
                </div>

                <div class="col-12 col-lg-1">
                    <div id="nlCount" class="nl-pill">
                        <i class="bi bi-list-check"></i> <span>0</span>
                    </div>
                </div>
            </form>
        </div>

        <div id="nlDataContainer">
            <div class="nl-empty">
                <div class="nl-empty-icon"><i class="bi bi-search"></i></div>
                <div class="nl-empty-title">Sorgu bekleniyor</div>
                <div class="nl-empty-sub">Tarih aralığını seçip “Sorgula” ile sonuçları getir.</div>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const currentFile = 'modules/dislab-izle.php';

    document.getElementById('nlFilterForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const loader = document.getElementById('nl-wait-layer');
        const container = document.getElementById('nlDataContainer');
        const countBadge = document.getElementById('nlCount');

        const params = new URLSearchParams(new FormData(this));
        params.append('action', 'fetch');

        loader.style.display = 'flex';

        fetch(currentFile + '?' + params.toString())
            .then(async res => {
                const text = await res.text();
                try {
                    return JSON.parse(text);
                } catch (err) {
                    console.error("KRİTİK HATA (JSON değil):", text);
                    alert("Kritik Hata: Sunucu JSON döndürmedi. Konsolu (F12) kontrol edin.");
                    throw new Error("JSON Parse Fail");
                }
            })
            .then(data => {
                if (data.success) {
                    container.innerHTML = data.html;
                    const span = countBadge.querySelector('span');
                    if (span) span.innerText = data.count;
                } else {
                    alert("Servis Hatası: " + data.error);
                }
            })
            .catch(err => console.error(err))
            .finally(() => { loader.style.display = 'none'; });
    });
});

function fetchDetail(ornekNo, patientName) {
    const loader = document.getElementById('nl-wait-layer');
    const modalBody = document.getElementById('modalResultBody');
    const modalEl = document.getElementById('sonucModal');
    const currentFile = 'modules/dislab-izle.php';

    document.getElementById('modalPatientName').innerText = patientName + " | Barkod: " + ornekNo;
    loader.style.display = 'flex';

    fetch(currentFile + '?action=fetch_detail&ornekNo=' + encodeURIComponent(ornekNo))
        .then(async res => {
            const text = await res.text();
            return JSON.parse(text);
        })
        .then(data => {
            if (data.success) {
                modalBody.innerHTML = data.html;
                const myModal = new bootstrap.Modal(modalEl);
                myModal.show();
            } else {
                alert("Detay Hatası: " + data.error);
            }
        })
        .catch(err => console.error(err))
        .finally(() => { loader.style.display = 'none'; });
}
</script>
