<?php
session_start();
require_once __DIR__ . '/../../core/db.php';
require_once __DIR__ . '/../../src/Auth.php';

use App\Auth;
use App\Database;

// Oturum kontrolü
Auth::init();
if (!Auth::user()) {
    header('Location: ../login.php');
    exit;
}

$db_obj = Database::getConnection();
$currentFile = basename(__FILE__);

// AJAX action handler
$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action) {
    header('Content-Type: application/json; charset=utf-8');
    
    if ($action === 'get_patients_by_date_range') {
        $startDate = trim($_GET['start_date'] ?? '');
        $endDate = trim($_GET['end_date'] ?? '');
        
        if (!$startDate || !$endDate) {
            echo json_encode(['success' => false, 'error' => 'Tarih aralığı gerekli']);
            exit;
        }
        
        $stmt = $db_obj->prepare('
            SELECT DISTINCT 
                p.id, 
                CONCAT(p.first_name, " ", p.last_name) as full_name,
                p.national_id,
                p.birth_date,
                COUNT(lr.id) as result_count,
                MAX(lr.result_date) as last_result_date
            FROM patients p
            LEFT JOIN patient_lab_results lr ON p.id = lr.patient_id 
                AND lr.result_date >= :start AND lr.result_date <= :end
            WHERE p.id IN (
                SELECT DISTINCT patient_id FROM patient_lab_results 
                WHERE result_date >= :start2 AND result_date <= :end2
            )
            GROUP BY p.id
            ORDER BY p.first_name, p.last_name
        ');
        
        $stmt->execute([
            ':start' => $startDate . ' 00:00:00',
            ':end' => $endDate . ' 23:59:59',
            ':start2' => $startDate . ' 00:00:00',
            ':end2' => $endDate . ' 23:59:59'
        ]);
        
        $patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'patients' => $patients], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_patient_results') {
        $patientId = (int)($_GET['patient_id'] ?? 0);
        
        if (!$patientId) {
            echo json_encode(['success' => false, 'error' => 'Hasta ID gerekli']);
            exit;
        }
        
        $stmt = $db_obj->prepare('
            SELECT 
                id, test_code, test_name, result_value, reference_min, reference_max, 
                unit, status, result_date, source, external_lab_name, sample_number, notes
            FROM patient_lab_results
            WHERE patient_id = :pid
            ORDER BY result_date DESC, test_name ASC
        ');
        $stmt->execute([':pid' => $patientId]);
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'results' => $results], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'delete_result') {
        $resultId = (int)($_POST['result_id'] ?? 0);
        if (!$resultId) {
            echo json_encode(['success' => false, 'error' => 'Sonuç ID gerekli']);
            exit;
        }
        
        $stmt = $db_obj->prepare('DELETE FROM patient_lab_results WHERE id = :id');
        $stmt->execute([':id' => $resultId]);
        
        echo json_encode(['success' => true, 'message' => 'Test sonucu silindi'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_test_definitions') {
        $stmt = $db_obj->prepare('
            SELECT code, name, category
            FROM local_test_definitions
            WHERE is_active = 1
            ORDER BY category, name
        ');
        $stmt->execute();
        $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'tests' => $tests], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_test_packages') {
        $stmt = $db_obj->prepare('
            SELECT id, name, description
            FROM test_packages
            WHERE is_active = 1
            ORDER BY name
        ');
        $stmt->execute();
        $packages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'packages' => $packages], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_package_tests') {
        $packageId = (int)($_GET['package_id'] ?? 0);
        
        $stmt = $db_obj->prepare('
            SELECT test_code, test_name
            FROM test_package_items
            WHERE package_id = :pid
            ORDER BY sort_order, test_name
        ');
        $stmt->execute([':pid' => $packageId]);
        $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode($tests, JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'save_test') {
        $patientId = (int)($_POST['patient_id'] ?? 0);
        $testCode = trim($_POST['test_code'] ?? '');
        $testName = trim($_POST['test_name'] ?? '');
        $testSource = trim($_POST['test_source'] ?? 'internal'); // internal|external
        $resultValue = trim($_POST['result_value'] ?? '');
        $referenceMin = trim($_POST['reference_min'] ?? '');
        $referenceMax = trim($_POST['reference_max'] ?? '');
        $unit = trim($_POST['unit'] ?? '');
        $notes = trim($_POST['notes'] ?? '');
        
        if (!$patientId || !$testCode || !$testName) {
            echo json_encode(['success' => false, 'error' => 'Gerekli alanlar eksik'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        
        // Barkod oluştur: LAB-YYYY-MM-DD-XXX
        $date = date('Y-m-d');
        $dateKey = str_replace('-', '', $date);
        
        // Bugünün sonuç sayısını al
        $stmt = $db_obj->prepare('
            SELECT COUNT(*) as cnt FROM patient_lab_results 
            WHERE DATE(result_date) = :date
        ');
        $stmt->execute([':date' => $date]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $barcode = 'LAB-' . $date . '-' . str_pad((int)$row['cnt'] + 1, 3, '0', STR_PAD_LEFT);
        
        // Durum belirle
        $status = 'normal';
        if ($resultValue && ($referenceMin || $referenceMax)) {
            $val = (float)$resultValue;
            if ($referenceMin && $val < (float)$referenceMin) {
                $status = 'low';
            } elseif ($referenceMax && $val > (float)$referenceMax) {
                $status = 'high';
            }
        }
        
        // Sonuç ekle
        $stmt = $db_obj->prepare('
            INSERT INTO patient_lab_results 
            (patient_id, test_code, test_name, result_value, reference_min, reference_max, 
             unit, status, result_date, source, sample_number, notes)
            VALUES (:pid, :code, :name, :value, :min, :max, :unit, :status, NOW(), :source, :barcode, :notes)
        ');
        
        $stmt->execute([
            ':pid' => $patientId,
            ':code' => $testCode,
            ':name' => $testName,
            ':value' => $resultValue ?: null,
            ':min' => $referenceMin ?: null,
            ':max' => $referenceMax ?: null,
            ':unit' => $unit,
            ':status' => $status,
            ':source' => $testSource,
            ':barcode' => $barcode,
            ':notes' => $notes
        ]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Test kaydedildi',
            'barcode' => $barcode,
            'result_id' => $db_obj->lastInsertId()
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Geçersiz action'], JSON_UNESCAPED_UNICODE);
    exit;
}

?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laboratuvar Sonuçları - NephroLink</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        :root {
            --primary: #3b82f6;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
        }

        body {
            background: #f8fafc;
            font-family: 'Segoe UI', system-ui, sans-serif;
        }

        .lab-grid {
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 20px;
        }

        .lab-panel {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            display: flex;
            flex-direction: column;
            max-height: 700px;
        }

        .panel-header {
            padding: 16px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .panel-body {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }

        .filter-section {
            padding: 12px 0;
            border-bottom: 1px solid #e5e7eb;
            margin-bottom: 12px;
        }

        .filter-section label {
            font-size: 12px;
            font-weight: 600;
            color: #374151;
            margin-bottom: 6px;
            display: block;
        }

        .filter-section input,
        .filter-section select {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            font-size: 12px;
            margin-bottom: 6px;
        }

        .quick-filter-btn {
            padding: 6px 10px;
            font-size: 11px;
            font-weight: 600;
            background: #f3f4f6;
            border: 1px solid #e5e7eb;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 4px;
            margin-bottom: 6px;
        }

        .quick-filter-btn:hover {
            background: #e5e7eb;
            border-color: var(--primary);
        }

        .patient-item {
            padding: 12px;
            margin-bottom: 8px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            cursor: pointer;
            background: white;
            transition: all 0.2s;
        }

        .patient-item:hover {
            background: #f0f9ff;
            border-color: var(--primary);
            transform: translateX(2px);
        }

        .patient-item.selected {
            background: #dbeafe;
            border-color: var(--primary);
            font-weight: 600;
        }

        .patient-name {
            font-weight: 600;
            color: #111827;
            margin-bottom: 4px;
            font-size: 13px;
        }

        .patient-meta {
            font-size: 11px;
            color: #666;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 40px;
            display: block;
            margin-bottom: 10px;
        }

        .patient-info-panel {
            padding: 16px;
            background: #f9fafb;
            border-radius: 8px;
            margin-bottom: 16px;
            font-size: 13px;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }

        .info-row:last-child {
            margin-bottom: 0;
        }

        .info-label {
            font-weight: 600;
            color: #374151;
        }

        .info-value {
            color: #111827;
        }

        .quick-actions {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 16px;
        }

        .quick-actions button {
            padding: 10px 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .quick-actions button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .results-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
        }

        .results-table th {
            padding: 10px;
            background: #f9fafb;
            text-align: left;
            font-weight: 600;
            color: #374151;
            border-bottom: 2px solid #e5e7eb;
        }

        .results-table td {
            padding: 10px;
            border-bottom: 1px solid #f3f4f6;
        }

        .results-table tbody tr:hover {
            background: #f9fafb;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 600;
        }

        .status-normal { background: #d4edda; color: #155724; }
        .status-low { background: #fff3cd; color: #856404; }
        .status-high { background: #f8d7da; color: #721c24; }

        .source-badge {
            display: inline-block;
            padding: 3px 6px;
            border-radius: 4px;
            font-size: 10px;
            background: #e2e8f0;
            color: #374151;
        }

        .action-btn {
            padding: 4px 8px;
            font-size: 11px;
            background: #ef4444;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .action-btn:hover {
            background: #dc2626;
        }

        @media (max-width: 1200px) {
            .lab-grid {
                grid-template-columns: 1fr;
            }

            .lab-panel {
                max-height: none;
            }
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: 9999;
            overflow: auto;
            padding: 20px;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background: white;
            margin: 0;
            padding: 0;
            border-radius: 12px;
            max-width: 900px;
            width: 90%;
            max-height: 80vh;
            display: flex;
            flex-direction: column;
            box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3);
        }

        .modal-header {
            padding: 20px 24px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 20px;
        }

        .modal-close {
            background: rgba(255,255,255,0.2);
            border: none;
            color: white;
            font-size: 24px;
            cursor: pointer;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-footer {
            padding: 16px 24px;
            background: #f9fafb;
            border-top: 1px solid #e5e7eb;
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            border-radius: 0 0 12px 12px;
        }
        
        .form-group {
            margin-bottom: 16px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #374151;
            margin-bottom: 6px;
            font-size: 13px;
        }

        .form-control {
            width: 100%;
            padding: 10px 12px;
            border: 2px solid #e5e7eb;
            border-radius: 6px;
            font-size: 14px;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--primary);
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            font-size: 14px;
        }

        .btn-secondary {
            background: var(--gray-100);
            color: var(--gray-900);
            border: 2px solid #e5e7eb;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../../layout/topbar.php'; ?>
    
    <div style="max-width: 1800px; margin: 0 auto; padding: 24px 20px;">
        <h1 style="margin-bottom: 20px; font-size: 24px; font-weight: 700;">
            <i class="bi bi-heart-pulse-fill text-danger"></i> Laboratuvar Sonuçları
        </h1>

        <div style="display: flex; gap: 20px; max-height: 700px;">
            <!-- SOL: Hasta Listesi -->
            <div class="lab-panel" style="width: 350px;">
                <div class="panel-header">
                    <i class="bi bi-people-fill"></i> Hastalar
                </div>
                <div class="panel-body">
                    <div class="filter-section">
                        <label>Başlangıç Tarihi</label>
                        <input type="date" id="startDate">
                    </div>

                    <div class="filter-section">
                        <label>Bitiş Tarihi</label>
                        <input type="date" id="endDate">
                    </div>

                    <div class="filter-section">
                        <label>Hızlı Filtre</label>
                        <button class="quick-filter-btn" onclick="setThisMonth()">Bu Ay</button>
                        <button class="quick-filter-btn" onclick="setLastMonth()">Geçen Ay</button>
                        <br>
                        <button class="quick-filter-btn" onclick="setThisYear()">Bu Yıl</button>
                        <button class="quick-filter-btn" onclick="loadPatientsByDateRange()">
                            <i class="bi bi-search"></i> Ara
                        </button>
                    </div>

                    <div class="filter-section" style="border-bottom: 0;">
                        <label>Hasta Adı</label>
                        <input type="text" id="patientSearch" placeholder="Ara...">
                    </div>

                    <div id="patientsList">
                        <div class="empty-state">
                            <i class="bi bi-inbox"></i>
                            <p>Tarih seçin</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- SAĞ: Sonuçlar -->
            <div class="lab-panel" style="flex: 1;">
                <div class="panel-header">
                    <i class="bi bi-file-earmark-text"></i> Test Sonuçları
                </div>
                <div class="panel-body">
                    <div id="noPatientSelected" class="empty-state">
                        <i class="bi bi-inbox"></i>
                        <p>Hasta seçin</p>
                    </div>

                    <div id="selectedPatientContent" style="display: none;">
                        <div class="patient-info-panel">
                            <div class="info-row">
                                <span class="info-label">Hasta:</span>
                                <span class="info-value" id="infoName"></span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">TC:</span>
                                <span class="info-value" id="infoTC"></span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Doğum:</span>
                                <span class="info-value" id="infoBirth"></span>
                            </div>
                        </div>

                        <div class="quick-actions">
                            <button onclick="showAddTestPanel()">
                                <i class="bi bi-plus-circle"></i> Test Ekle
                            </button>
                            <button onclick="queryDislab()">
                                <i class="bi bi-cloud-download"></i> Sorgula
                            </button>
                        </div>

                        <div style="overflow-x: auto;">
                            <table class="results-table">
                                <thead>
                                    <tr>
                                        <th style="width: 80px;">Tarih</th>
                                        <th style="width: 90px;">Barkod</th>
                                        <th style="width: 70px;">Kod</th>
                                        <th>Test Adı</th>
                                        <th style="width: 70px;">Sonuç</th>
                                        <th style="width: 80px;">Referans</th>
                                        <th style="width: 60px;">Durum</th>
                                        <th style="width: 50px;">Sil</th>
                                    </tr>
                                </thead>
                                <tbody id="resultsTableBody">
                                    <tr><td colspan="8" class="text-center">Yükleniyor...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentPatientId = null;
        let allPatients = [];

        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date();
            document.getElementById('startDate').value = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
            document.getElementById('endDate').value = today.toISOString().split('T')[0];

            document.getElementById('patientSearch').addEventListener('input', function() {
                filterPatients(this.value);
            });

            loadPatientsByDateRange();
        });

        function setThisMonth() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            document.getElementById('startDate').value = firstDay.toISOString().split('T')[0];
            document.getElementById('endDate').value = today.toISOString().split('T')[0];
            loadPatientsByDateRange();
        }

        function setLastMonth() {
            const today = new Date();
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1);
            const firstDay = new Date(lastMonth.getFullYear(), lastMonth.getMonth(), 1);
            const lastDay = new Date(lastMonth.getFullYear(), lastMonth.getMonth() + 1, 0);
            document.getElementById('startDate').value = firstDay.toISOString().split('T')[0];
            document.getElementById('endDate').value = lastDay.toISOString().split('T')[0];
            loadPatientsByDateRange();
        }

        function setThisYear() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), 0, 1);
            document.getElementById('startDate').value = firstDay.toISOString().split('T')[0];
            document.getElementById('endDate').value = today.toISOString().split('T')[0];
            loadPatientsByDateRange();
        }

        async function loadPatientsByDateRange() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            if (!startDate || !endDate) return;

            try {
                const response = await fetch(`<?= $currentFile ?>?action=get_patients_by_date_range&start_date=${startDate}&end_date=${endDate}`);
                const data = await response.json();

                if (data.success) {
                    allPatients = data.patients;
                    displayPatients(allPatients);
                }
            } catch (error) {
                console.error('Hata:', error);
            }
        }

        function displayPatients(patients) {
            const list = document.getElementById('patientsList');

            if (patients.length === 0) {
                list.innerHTML = '<div class="empty-state"><i class="bi bi-inbox"></i><p>Hasta bulunamadı</p></div>';
                return;
            }

            list.innerHTML = patients.map(p => {
                const lastDate = p.last_result_date ? new Date(p.last_result_date).toLocaleDateString('tr-TR') : '-';
                return `
                    <div class="patient-item" onclick="selectPatient(${p.id}, '${p.full_name}', '${p.national_id}', '${p.birth_date}')">
                        <div class="patient-name">${p.full_name}</div>
                        <div class="patient-meta">TC: ${p.national_id || '-'} | <span class="badge bg-info" style="font-size: 10px;">${p.result_count}</span> | ${lastDate}</div>
                    </div>
                `;
            }).join('');
        }

        function filterPatients(query) {
            const filtered = allPatients.filter(p => 
                p.full_name.toLowerCase().includes(query.toLowerCase())
            );
            displayPatients(filtered);
        }

        function selectPatient(patientId, fullName, nationalId, birthDate) {
            currentPatientId = patientId;

            document.getElementById('infoName').textContent = fullName;
            document.getElementById('infoTC').textContent = nationalId || '-';
            document.getElementById('infoBirth').textContent = birthDate || '-';

            document.getElementById('noPatientSelected').style.display = 'none';
            document.getElementById('selectedPatientContent').style.display = 'block';

            loadResults();
        }

        async function loadResults() {
            if (!currentPatientId) return;

            try {
                const response = await fetch(`<?= $currentFile ?>?action=get_patient_results&patient_id=${currentPatientId}`);
                const data = await response.json();

                if (data.success) {
                    displayResults(data.results);
                }
            } catch (error) {
                console.error('Sonuçlar yüklenemedi:', error);
            }
        }

        function displayResults(results) {
            const tbody = document.getElementById('resultsTableBody');

            if (results.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center text-muted">Henüz sonuç yok</td></tr>';
                return;
            }

            tbody.innerHTML = results.map(r => {
                const date = new Date(r.result_date);
                const dateStr = date.toLocaleDateString('tr-TR');
                const refRange = (r.reference_min || r.reference_max) ? 
                    `${r.reference_min || '-'} - ${r.reference_max || '-'}` : '-';

                const statusMap = { 'normal': 'Normal', 'low': 'Düşük', 'high': 'Yüksek' };
                const sourceIcon = r.source === 'internal' ? '<i class="bi bi-building" style="color: #10b981;"></i>' : '<i class="bi bi-cloud" style="color: #0ea5e9;"></i>';
                const barcode = r.sample_number || '-';

                return `
                    <tr title="Kaynak: ${r.source === 'internal' ? 'İç Lab' : 'Dış Lab'}">
                        <td><small>${dateStr}</small></td>
                        <td><code style="font-size: 10px; background: #f3f4f6; padding: 2px 4px; border-radius: 3px;">${barcode}</code></td>
                        <td><code style="font-size: 10px;">${r.test_code}</code></td>
                        <td>${r.test_name}</td>
                        <td><strong>${r.result_value || '-'}</strong></td>
                        <td><small>${refRange}</small></td>
                        <td><span class="status-badge status-${r.status}">${statusMap[r.status] || r.status}</span></td>
                        <td>${r.source === 'internal' ? `<button class="action-btn" onclick="deleteResult(${r.id})" title="Sil">✕</button>` : '-'}</td>
                    </tr>
                `;
            }).join('');
        }

        async function deleteResult(resultId) {
            if (!confirm('Silmek istediğinizden emin misiniz?')) return;

            const formData = new FormData();
            formData.append('action', 'delete_result');
            formData.append('result_id', resultId);

            try {
                const response = await fetch('<?= $currentFile ?>', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();

                if (data.success) {
                    loadResults();
                }
            } catch (error) {
                console.error('Hata:', error);
            }
        }

        function queryDislab() {
            if (!currentPatientId) {
                alert('Hasta seçin');
                return;
            }
            
            // Dış lab sorgusu için modal açmayın, direkt dislabIzle.php'ye yönlendirin
            // ya da ayrı bir tab açın
            const patientName = document.getElementById('infoName').textContent;
            alert(`${patientName} için dış lab sonuçları dislabIzle.php üzerinden sorgulanabilir.`);
        }

        function showAddTestPanel() {
            if (!currentPatientId) {
                alert('Lütfen hasta seçin');
                return;
            }
            
            openAddTestModal();
        }
        
        // Test Ekleme Modalı
        function openAddTestModal() {
            const modal = document.getElementById('addTestModal');
            if (!modal) {
                createAddTestModal();
            }
            document.getElementById('addTestModal').style.display = 'flex';
            loadTestDefinitions();
        }
        
        function closeAddTestModal() {
            const modal = document.getElementById('addTestModal');
            if (modal) modal.style.display = 'none';
        }
        
        function createAddTestModal() {
            const html = `
                <div id="addTestModal" class="modal">
                    <div class="modal-content" style="max-width: 1000px;">
                        <div class="modal-header">
                            <h2><i class="bi bi-plus-circle-fill"></i> Test Ekle</h2>
                            <button class="modal-close" onclick="closeAddTestModal()">&times;</button>
                        </div>
                        
                        <div style="display: grid; grid-template-columns: 350px 1fr; height: 600px; gap: 0;">
                            <!-- Sol Panel: Test Seçimi -->
                            <div style="border-right: 1px solid #e5e7eb; overflow-y: auto;">
                                <div style="padding: 16px; border-bottom: 1px solid #e5e7eb;">
                                    <input type="text" id="testSearchInput" placeholder="Test adı veya kodu ara..." 
                                           style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px;">
                                </div>
                                
                                <div style="padding: 16px;">
                                    <div id="testsList" style="display: grid; gap: 8px;"></div>
                                </div>
                            </div>
                            
                            <!-- Sağ Panel: Test Detayları & Sonuç Girişi -->
                            <div id="testDetailsPanel" style="padding: 20px; background: #f9fafb; overflow-y: auto; display: none;">
                                <div id="testDetailsContent"></div>
                            </div>
                            
                            <div id="noTestSelectedPanel" style="padding: 40px 20px; text-align: center; color: #999;">
                                <i class="bi bi-inbox" style="font-size: 40px; display: block; margin-bottom: 12px;"></i>
                                <p>Sol taraftan test seçin</p>
                            </div>
                        </div>
                        
                        <div class="modal-footer" style="padding: 16px 24px; background: #f9fafb; border-top: 1px solid #e5e7eb; display: flex; justify-content: flex-end; gap: 8px;">
                            <button class="btn btn-secondary" onclick="closeAddTestModal()" style="padding: 8px 16px;">İptal</button>
                            <button class="btn btn-primary" id="btnSaveTest" onclick="saveTest()" style="padding: 8px 16px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 6px; cursor: pointer; display: none;">
                                <i class="bi bi-check-circle"></i> Kaydet
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', html);
        }
        
        let selectedTestData = null;
        let allTestDefinitions = [];
        
        async function loadTestDefinitions() {
            try {
                const response = await fetch('<?= $currentFile ?>?action=get_test_definitions');
                const data = await response.json();
                
                if (data.success) {
                    allTestDefinitions = data.tests;
                    displayTests(data.tests);
                }
            } catch (error) {
                console.error('Test tanımları yüklenemedi:', error);
            }
        }
        
        function displayTests(tests) {
            const list = document.getElementById('testsList');
            const grouped = {};
            
            // Kategoriye göre grupla
            tests.forEach(test => {
                const cat = test.category || 'Diğer';
                if (!grouped[cat]) grouped[cat] = [];
                grouped[cat].push(test);
            });
            
            let html = '';
            for (const [category, categoryTests] of Object.entries(grouped)) {
                html += `<div style="margin-bottom: 12px;">`;
                html += `<div style="font-weight: 600; font-size: 11px; color: #666; padding: 6px 0; text-transform: uppercase;">${category}</div>`;
                
                categoryTests.forEach(test => {
                    html += `
                        <div class="test-item" onclick="selectTestForAdd(${JSON.stringify(test).replace(/'/g, '&#39;')})" 
                             style="padding: 10px; margin-bottom: 6px; background: white; border: 1px solid #e5e7eb; border-radius: 6px; cursor: pointer; transition: all 0.2s;">
                            <div style="font-weight: 600; font-size: 12px; color: #333;">${test.name}</div>
                            <div style="font-size: 10px; color: #666; font-family: monospace;">${test.code}</div>
                        </div>
                    `;
                });
                html += '</div>';
            }
            
            list.innerHTML = html;
        }
        
        function filterTests(query) {
            const filtered = allTestDefinitions.filter(t => 
                t.name.toLowerCase().includes(query.toLowerCase()) ||
                t.code.toLowerCase().includes(query.toLowerCase())
            );
            displayTests(filtered);
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                const searchInput = document.getElementById('testSearchInput');
                if (searchInput) {
                    searchInput.addEventListener('input', (e) => filterTests(e.target.value));
                }
            }, 100);
        });
        
        function selectTestForAdd(test) {
            selectedTestData = test;
            
            const panel = document.getElementById('testDetailsPanel');
            const noPanel = document.getElementById('noTestSelectedPanel');
            const content = document.getElementById('testDetailsContent');
            
            // Test bilgisi gir
            const isExternal = test.code.startsWith('DISLAB-');
            
            let html = `
                <div style="margin-bottom: 20px;">
                    <h4 style="margin: 0 0 12px 0; color: #333;">${test.name}</h4>
                    <div style="padding: 12px; background: white; border-left: 4px solid #667eea; border-radius: 4px;">
                        <div style="margin-bottom: 8px;">
                            <span style="font-weight: 600; color: #666;">Kod:</span> 
                            <code style="font-size: 12px; color: #333;">${test.code}</code>
                        </div>
                        <div>
                            <span style="font-weight: 600; color: #666;">Kategori:</span> 
                            <span style="color: #333;">${test.category || 'Diğer'}</span>
                        </div>
                        <div style="margin-top: 8px;">
                            <span style="display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; background: ${isExternal ? '#fee2e2' : '#d1fae5'}; color: ${isExternal ? '#991b1b' : '#065f46'};">
                                ${isExternal ? 'Dış Lab' : 'İç Lab'}
                            </span>
                        </div>
                    </div>
                </div>
            `;
            
            if (!isExternal) {
                // İç lab - sonuç girişi
                html += `
                    <div class="form-group">
                        <label style="font-weight: 600; margin-bottom: 8px; display: block;">Sonuç Değeri</label>
                        <input type="text" id="resultValue" placeholder="Örn: 95.5" 
                               style="width: 100%; padding: 10px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px; margin-bottom: 8px;">
                        
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 8px;">
                            <input type="text" id="referenceMin" placeholder="Min aralık" 
                                   style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px;">
                            <input type="text" id="referenceMax" placeholder="Max aralık" 
                                   style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px;">
                        </div>
                        
                        <input type="text" id="resultUnit" placeholder="Birim (mg/dL, vb.)" 
                               style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px; margin-bottom: 8px;">
                    </div>
                    
                    <div class="form-group">
                        <label style="font-weight: 600; margin-bottom: 8px; display: block;">Notlar</label>
                        <textarea id="resultNotes" placeholder="Opsiyonel notlar..." 
                                  style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 6px; font-size: 12px; height: 80px; resize: none;"></textarea>
                    </div>
                `;
            } else {
                // Dış lab - sadece bilgi
                html += `
                    <div style="padding: 12px; background: #fef3c7; border-left: 4px solid #f59e0b; border-radius: 4px; margin-bottom: 20px;">
                        <p style="margin: 0; font-size: 13px; color: #92400e;">
                            <i class="bi bi-info-circle"></i> Bu dış lab testidir. Sonuçlar "Dışlab Sorgula" butonundan alınacaktır.
                        </p>
                    </div>
                `;
            }
            
            content.innerHTML = html;
            panel.style.display = 'block';
            noPanel.style.display = 'none';
            document.getElementById('btnSaveTest').style.display = 'flex';
        }
        
        async function saveTest() {
            if (!selectedTestData || !currentPatientId) return;
            
            const btn = document.getElementById('btnSaveTest');
            btn.disabled = true;
            btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Kaydediliyor...';
            
            const isExternal = selectedTestData.code.startsWith('DISLAB-');
            
            const formData = new FormData();
            formData.append('action', 'save_test');
            formData.append('patient_id', currentPatientId);
            formData.append('test_code', selectedTestData.code);
            formData.append('test_name', selectedTestData.name);
            formData.append('test_source', isExternal ? 'external' : 'internal');
            
            if (!isExternal) {
                formData.append('result_value', document.getElementById('resultValue')?.value || '');
                formData.append('reference_min', document.getElementById('referenceMin')?.value || '');
                formData.append('reference_max', document.getElementById('referenceMax')?.value || '');
                formData.append('unit', document.getElementById('resultUnit')?.value || '');
                formData.append('notes', document.getElementById('resultNotes')?.value || '');
            }
            
            try {
                const response = await fetch('<?= $currentFile ?>', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert(`✓ Test kaydedildi\nBarkod: ${data.barcode}`);
                    closeAddTestModal();
                    selectedTestData = null;
                    loadResults();
                } else {
                    alert(`✗ Hata: ${data.error}`);
                }
            } catch (error) {
                alert(`✗ Hata: ${error.message}`);
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-check-circle"></i> Kaydet';
            }
        }
    </script>
</body>
</html>
