<?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') {
        // Tarih aralığında sonuç alan hastaları getir
        $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 === 'send_to_dislab') {
        // Hastayı dışlab'a gönder
        $patientId = (int)($_POST['patient_id'] ?? 0);
        $testCodes = $_POST['test_codes'] ?? [];
        
        if (!$patientId || empty($testCodes)) {
            echo json_encode(['success' => false, 'error' => 'Hasta ve test seçimi gerekli']);
            exit;
        }
        
        try {
            // Hastanın bilgilerini al
            $pStmt = $db_obj->prepare('SELECT * FROM patients WHERE id = :id');
            $pStmt->execute([':id' => $patientId]);
            $patient = $pStmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$patient) {
                echo json_encode(['success' => false, 'error' => 'Hasta bulunamadı']);
                exit;
            }
            
            // Referans oluştur
            $refId = time();
            
            // dislab_records'e kaydet
            $dStmt = $db_obj->prepare('
                INSERT INTO dislab_records 
                (patient_id, first_name, last_name, national_id, status, created_at)
                VALUES (:pid, :fname, :lname, :nid, :status, NOW())
            ');
            
            $dStmt->execute([
                ':pid' => $patientId,
                ':fname' => $patient['first_name'],
                ':lname' => $patient['last_name'],
                ':nid' => $patient['national_id'] ?? null,
                ':status' => 'pending'
            ]);
            
            $recordId = $db_obj->lastInsertId();
            
            // Testleri kaydet
            $tStmt = $db_obj->prepare('
                INSERT INTO dislab_records_tests (record_id, test_code, test_name)
                VALUES (:rid, :code, :name)
            ');
            
            foreach ($testCodes as $code) {
                // Test adını bul
                $tDefStmt = $db_obj->prepare('SELECT name FROM local_test_definitions WHERE code = :code');
                $tDefStmt->execute([':code' => $code]);
                $testDef = $tDefStmt->fetch(PDO::FETCH_ASSOC);
                
                $tStmt->execute([
                    ':rid' => $recordId,
                    ':code' => $code,
                    ':name' => $testDef['name'] ?? $code
                ]);
            }
            
            echo json_encode([
                'success' => true, 
                'message' => 'Hasta dışlab\'a gönderildi',
                'record_id' => $recordId
            ], JSON_UNESCAPED_UNICODE);
            exit;
            
        } catch (Throwable $e) {
            echo json_encode(['success' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
    
    // Hasta ID kontrolü
    $patientId = (int)($_GET['patient_id'] ?? $_POST['patient_id'] ?? 0);
    
    if ($action === 'get_patient_results') {
        // Hastanın tüm lab sonuçlarını getir (iç + dış)
        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 === 'save_result') {
        // Manuel test sonucu kaydet
        if (!$patientId) {
            echo json_encode(['success' => false, 'error' => 'Hasta ID gerekli']);
            exit;
        }
        
        $testCode = trim($_POST['test_code'] ?? '');
        $testName = trim($_POST['test_name'] ?? '');
        $resultValue = trim($_POST['result_value'] ?? '');
        $refMin = trim($_POST['reference_min'] ?? '');
        $refMax = trim($_POST['reference_max'] ?? '');
        $unit = trim($_POST['unit'] ?? '');
        $resultDate = trim($_POST['result_date'] ?? date('Y-m-d H:i:s'));
        $notes = trim($_POST['notes'] ?? '');
        
        if (!$testCode || !$testName) {
            echo json_encode(['success' => false, 'error' => 'Test kodu ve adı gerekli']);
            exit;
        }
        
        // Status hesapla
        $status = 'normal';
        if ($resultValue !== '' && is_numeric($resultValue)) {
            if ($refMin !== '' && is_numeric($refMin) && floatval($resultValue) < floatval($refMin)) {
                $status = 'low';
            } elseif ($refMax !== '' && is_numeric($refMax) && floatval($resultValue) > floatval($refMax)) {
                $status = 'high';
            }
        }
        
        $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, notes, created_by)
            VALUES 
            (:pid, :code, :name, :value, :min, :max, :unit, :status, :date, :source, :notes, :user)
        ');
        
        $stmt->execute([
            ':pid' => $patientId,
            ':code' => $testCode,
            ':name' => $testName,
            ':value' => $resultValue !== '' ? $resultValue : null,
            ':min' => $refMin !== '' ? $refMin : null,
            ':max' => $refMax !== '' ? $refMax : null,
            ':unit' => $unit !== '' ? $unit : null,
            ':status' => $status,
            ':date' => $resultDate,
            ':source' => 'internal',
            ':notes' => $notes !== '' ? $notes : null,
            ':user' => $_SESSION['user_id'] ?? null
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Test sonucu kaydedildi', 'result_id' => $db_obj->lastInsertId()], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'delete_result') {
        // Test sonucunu sil
        $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') {
        // Test tanımlarını getir (dropdown için)
        $search = trim($_GET['search'] ?? '');
        
        $sql = 'SELECT code, name, unit, min_ref, max_ref, category FROM local_test_definitions WHERE is_active = 1';
        if ($search !== '') {
            $sql .= ' AND (code LIKE :search OR name LIKE :search)';
        }
        $sql .= ' ORDER BY name ASC LIMIT 100';
        
        $stmt = $db_obj->prepare($sql);
        if ($search !== '') {
            $stmt->execute([':search' => '%' . $search . '%']);
        } else {
            $stmt->execute();
        }
        
        $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'tests' => $tests], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_test_packages') {
        // Test paketlerini getir
        $stmt = $db_obj->prepare('
            SELECT p.id, p.name, p.description, p.package_type,
                   COUNT(i.id) as test_count
            FROM test_packages p
            LEFT JOIN test_package_items i ON p.id = i.package_id
            WHERE p.is_active = 1
            GROUP BY p.id
            ORDER BY p.name ASC
        ');
        $stmt->execute();
        $packages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'packages' => $packages], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    if ($action === 'get_package_tests') {
        // Paketin testlerini getir
        $packageId = (int)($_GET['package_id'] ?? 0);
        if (!$packageId) {
            echo json_encode(['success' => false, 'error' => 'Paket ID gerekli']);
            exit;
        }
        
        $stmt = $db_obj->prepare('
            SELECT i.test_code, i.test_name, i.sort_order,
                   d.unit, d.min_ref, d.max_ref
            FROM test_package_items i
            LEFT JOIN local_test_definitions d ON i.test_code = d.code
            WHERE i.package_id = :pid
            ORDER BY i.sort_order ASC, i.test_name ASC
        ');
        $stmt->execute([':pid' => $packageId]);
        $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'tests' => $tests], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    echo json_encode(['success' => false, 'error' => 'Geçersiz action'], JSON_UNESCAPED_UNICODE);
    exit;
}

// Hasta listesi
$patients = $db_obj->query('
    SELECT id, CONCAT(first_name, " ", last_name) as full_name, national_id, birth_date
    FROM patients
    ORDER BY first_name, last_name
')->fetchAll(PDO::FETCH_ASSOC);

?>
<!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>
        .status-badge {
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .status-normal { background: #d4edda; color: #155724; }
        .status-low { background: #fff3cd; color: #856404; }
        .status-high { background: #f8d7da; color: #721c24; }
        .status-critical { background: #dc3545; color: white; }
        
        .source-badge {
            padding: 3px 8px;
            border-radius: 8px;
            font-size: 11px;
            font-weight: 500;
        }
        .source-internal { background: #d1ecf1; color: #0c5460; }
        .source-external { background: #e2e3e5; color: #383d41; }
        
        .result-table th { background: #f8f9fa; font-weight: 600; font-size: 14px; }
        .result-table td { vertical-align: middle; font-size: 14px; }
        
        .form-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .test-selector {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
        }
        
        .test-item {
            padding: 8px;
            margin-bottom: 5px;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .test-item:hover {
            background: #e3f2fd;
            border-color: #2196F3;
        }
        .test-item.selected {
            background: #2196F3;
            color: white;
            border-color: #2196F3;
        }
        
        .quick-add-btn {
            margin: 5px;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <?php include __DIR__ . '/../../layout/topbar.php'; ?>
    
    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="bi bi-heart-pulse-fill text-danger"></i> Laboratuvar Sonuçları</h2>
                    <a href="../dashboard.php" class="btn btn-outline-secondary">
                        <i class="bi bi-arrow-left"></i> Dashboard
                    </a>
                </div>
                
                <!-- Tarih Filtresi -->
                <div class="form-section">
                    <h5><i class="bi bi-calendar-range"></i> Tarih Aralığı ile Hasta Listele</h5>
                    <div class="row align-items-end">
                        <div class="col-md-2">
                            <label class="form-label">Başlangıç Tarihi</label>
                            <input type="date" id="startDate" class="form-control">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Bitiş Tarihi</label>
                            <input type="date" id="endDate" class="form-control">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Hızlı Filtre</label>
                            <div class="btn-group w-100" role="group">
                                <button class="btn btn-sm btn-outline-primary" onclick="setThisMonth()">Bu Ay</button>
                                <button class="btn btn-sm btn-outline-primary" onclick="setLastMonth()">Geçen Ay</button>
                                <button class="btn btn-sm btn-outline-primary" onclick="setThisYear()">Bu Yıl</button>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary w-100" onclick="loadPatientsByDateRange()">
                                <i class="bi bi-search"></i> Listele
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Hasta Seçimi -->
                <div class="form-section">
                    <h5><i class="bi bi-person-fill"></i> Hasta Seçimi</h5>
                    <div class="row">
                        <div class="col-md-12">
                            <div class="table-responsive">
                                <table class="table table-hover table-sm" id="patientsTable">
                                    <thead>
                                        <tr>
                                            <th style="width: 50px;"></th>
                                            <th>Adı Soyadı</th>
                                            <th>TC Kimlik</th>
                                            <th style="width: 120px;">Sonuç Sayısı</th>
                                            <th style="width: 150px;">Son Sonuç</th>
                                            <th style="width: 150px;">İşlem</th>
                                        </tr>
                                    </thead>
                                    <tbody id="patientsList">
                                        <tr>
                                            <td colspan="6" class="text-center text-muted">
                                                <i class="bi bi-inbox"></i> Tarih aralığı seçin ve listele butonuna tıklayın
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Seçilen Hasta Detayları -->
                <div id="selectedPatientPanel" style="display: none;" class="form-section">
                    <h5><i class="bi bi-person-badge"></i> Seçilen Hasta</h5>
                    <div class="alert alert-info">
                        <strong id="selPatientName"></strong><br>
                        <small id="selPatientInfo"></small>
                    </div>
                    <div class="row">
                        <div class="col-md-3">
                            <button class="btn btn-primary w-100" onclick="showManualEntry()">
                                <i class="bi bi-plus-circle"></i> Test Ekle
                            </button>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-success w-100" onclick="showDisLabSendPanel()">
                                <i class="bi bi-cloud-arrow-up"></i> Dışlab'a Gönder
                            </button>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-secondary w-100" onclick="clearPatientSelection()">
                                İptal
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Dışlab Gönderimi -->
                <div id="disLabSendPanel" class="card mb-3" style="display: none;">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="bi bi-cloud-arrow-up"></i> Dışlab'a Hasta Gönderimi</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Mevcut Testler</h6>
                                <div class="test-selector" id="availableTestsList">
                                    <p class="text-muted">Yükleniyor...</p>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6>Gönderilecek Testler</h6>
                                <div class="test-selector" id="selectedTestsList">
                                    <p class="text-muted">Yukarıdan test seçin</p>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3">
                            <button class="btn btn-success" onclick="sendToDislabConfirm()">
                                <i class="bi bi-check-circle"></i> Gönder
                            </button>
                            <button class="btn btn-secondary" onclick="hideDisLabSendPanel()">
                                <i class="bi bi-x-circle"></i> İptal
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Eski Hasta Seçimi (gizli) -->
                <div id="singlePatientSection" style="display: none;">
                    <div class="form-section">
                        <h5><i class="bi bi-person-fill"></i> Doğrudan Hasta Seçimi</h5>
                        <div class="row">
                            <div class="col-md-6">
                                <select id="patientSelect" class="form-select form-select-lg">
                                    <option value="">-- Hasta Seçin --</option>
                                    <?php foreach ($patients as $p): ?>
                                        <option value="<?= $p['id'] ?>" 
                                                data-name="<?= htmlspecialchars($p['full_name']) ?>"
                                                data-tc="<?= htmlspecialchars($p['national_id'] ?? '') ?>"
                                                data-birth="<?= htmlspecialchars($p['birth_date'] ?? '') ?>">
                                            <?= htmlspecialchars($p['full_name']) ?> 
                                            <?php if ($p['national_id']): ?>
                                                - TC: <?= htmlspecialchars($p['national_id']) ?>
                                            <?php endif; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <div id="patientInfo" class="alert alert-info d-none">
                                    <strong id="patientName"></strong><br>
                                    <small id="patientDetails"></small>
                                </div>
                            </div>
                        </div>
                    </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div id="labContent" style="display: none;">
                    <!-- Hızlı İşlemler -->
                    <div class="card mb-3">
                        <div class="card-body">
                            <h6 class="card-title mb-3"><i class="bi bi-lightning-fill text-warning"></i> Hızlı İşlemler</h6>
                            <button class="btn btn-primary quick-add-btn" onclick="showManualEntry()">
                                <i class="bi bi-plus-circle"></i> Tek Test Ekle
                            </button>
                            <button class="btn btn-success quick-add-btn" onclick="showPackageEntry()">
                                <i class="bi bi-box-seam"></i> Paket Test Ekle
                            </button>
                            <button class="btn btn-info quick-add-btn" onclick="showExternalLabImport()">
                                <i class="bi bi-cloud-download"></i> Dış Lab'dan Çek
                            </button>
                            <button class="btn btn-secondary quick-add-btn" onclick="loadResults()">
                                <i class="bi bi-arrow-clockwise"></i> Yenile
                            </button>
                        </div>
                    </div>
                    
                    <!-- Manuel Test Girişi -->
                    <div id="manualEntryPanel" class="card mb-3" style="display: none;">
                        <div class="card-header bg-primary text-white">
                            <h5 class="mb-0"><i class="bi bi-pencil-square"></i> Manuel Test Sonucu Girişi</h5>
                        </div>
                        <div class="card-body">
                            <form id="manualEntryForm">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Test Kodu</label>
                                        <input type="text" class="form-control" id="testCode" list="testCodeList" required>
                                        <datalist id="testCodeList"></datalist>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Test Adı</label>
                                        <input type="text" class="form-control" id="testName" required>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Sonuç</label>
                                        <input type="text" class="form-control" id="resultValue">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">Min Referans</label>
                                        <input type="text" class="form-control" id="refMin">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">Max Referans</label>
                                        <input type="text" class="form-control" id="refMax">
                                    </div>
                                    <div class="col-md-2 mb-3">
                                        <label class="form-label">Birim</label>
                                        <input type="text" class="form-control" id="unit">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Tarih/Saat</label>
                                        <input type="datetime-local" class="form-control" id="resultDate">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Notlar</label>
                                        <textarea class="form-control" id="notes" rows="2"></textarea>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-success">
                                    <i class="bi bi-save"></i> Kaydet
                                </button>
                                <button type="button" class="btn btn-secondary" onclick="hideManualEntry()">
                                    İptal
                                </button>
                            </form>
                        </div>
                    </div>
                    
                    <!-- Paket Test Girişi -->
                    <div id="packageEntryPanel" class="card mb-3" style="display: none;">
                        <div class="card-header bg-success text-white">
                            <h5 class="mb-0"><i class="bi bi-box-seam"></i> Paket Test Girişi</h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Paket Seç</label>
                                    <select id="packageSelect" class="form-select">
                                        <option value="">-- Paket Seçin --</option>
                                    </select>
                                </div>
                                <div class="col-md-8">
                                    <div id="packageTests" class="test-selector" style="display: none;">
                                        <div id="packageTestList"></div>
                                    </div>
                                </div>
                            </div>
                            <div id="packageTestForms" style="display: none;">
                                <hr>
                                <form id="packageTestForm">
                                    <div id="packageTestInputs"></div>
                                    <button type="submit" class="btn btn-success">
                                        <i class="bi bi-save"></i> Tümünü Kaydet
                                    </button>
                                    <button type="button" class="btn btn-secondary" onclick="hidePackageEntry()">
                                        İptal
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Sonuçlar Tablosu -->
                    <div class="card">
                        <div class="card-header bg-dark text-white">
                            <h5 class="mb-0"><i class="bi bi-table"></i> Test Sonuçları</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover result-table">
                                    <thead>
                                        <tr>
                                            <th style="width: 120px;">Tarih</th>
                                            <th style="width: 100px;">Test Kodu</th>
                                            <th>Test Adı</th>
                                            <th style="width: 100px;">Sonuç</th>
                                            <th style="width: 150px;">Referans</th>
                                            <th style="width: 80px;">Durum</th>
                                            <th style="width: 100px;">Kaynak</th>
                                            <th style="width: 100px;">İşlem</th>
                                        </tr>
                                    </thead>
                                    <tbody id="resultsTableBody">
                                        <tr>
                                            <td colspan="8" class="text-center text-muted">
                                                <i class="bi bi-inbox"></i> Henüz test sonucu yok
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </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 testDefinitions = [];
        
        // Sayfa yüklendiğinde
        document.addEventListener('DOMContentLoaded', function() {
            // Test tanımlarını yükle
            loadTestDefinitions();
            
            // Paketleri yükle
            loadPackages();
            
            // Tarih aralığını ayarla - Bu ay
            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];
            
            // Eski hasta seçim event
            const patSelect = document.getElementById('patientSelect');
            if (patSelect) {
                patSelect.addEventListener('change', function() {
                    const patientId = this.value;
                    if (patientId) {
                        selectPatientFromDropdown(parseInt(patientId));
                    }
                });
            }
                } else {
                    currentPatientId = null;
                    document.getElementById('patientInfo').classList.add('d-none');
                    document.getElementById('labContent').style.display = 'none';
                }
            });
            
            // Test kodu değiştiğinde otomatik doldur
            document.getElementById('testCode').addEventListener('input', function() {
                const code = this.value.toUpperCase();
                const test = testDefinitions.find(t => t.code === code);
                if (test) {
                    document.getElementById('testName').value = test.name;
                    document.getElementById('refMin').value = test.min_ref || '';
                    document.getElementById('refMax').value = test.max_ref || '';
                    document.getElementById('unit').value = test.unit || '';
                }
            });
            
            // Manuel giriş form submit
            document.getElementById('manualEntryForm').addEventListener('submit', function(e) {
                e.preventDefault();
                saveManualResult();
            });
            
            // Paket seçim event
            document.getElementById('packageSelect').addEventListener('change', function() {
                if (this.value) {
                    loadPackageTests(this.value);
                } else {
                    document.getElementById('packageTests').style.display = 'none';
                    document.getElementById('packageTestForms').style.display = 'none';
                }
            });
            
            // Paket test form submit
            document.getElementById('packageTestForm').addEventListener('submit', function(e) {
                e.preventDefault();
                savePackageTests();
            });
            
            // Tarih default değer
            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
            document.getElementById('resultDate').value = now.toISOString().slice(0, 16);
        });
        
        // Test tanımlarını yükle
        async function loadTestDefinitions() {
            try {
                const response = await fetch('<?= $currentFile ?>?action=get_test_definitions');
                const data = await response.json();
                if (data.success) {
                    testDefinitions = data.tests;
                    
                    // Datalist doldur
                    const datalist = document.getElementById('testCodeList');
                    datalist.innerHTML = data.tests.map(t => 
                        `<option value="${t.code}">${t.name}</option>`
                    ).join('');
                }
            } catch (error) {
                console.error('Test tanımları yüklenemedi:', error);
            }
        }
        
        // Paketleri yükle
        async function loadPackages() {
            try {
                const response = await fetch('<?= $currentFile ?>?action=get_test_packages');
                const data = await response.json();
                if (data.success) {
                    const select = document.getElementById('packageSelect');
                    select.innerHTML = '<option value="">-- Paket Seçin --</option>' +
                        data.packages.map(p => 
                            `<option value="${p.id}">${p.name} (${p.test_count} test)</option>`
                        ).join('');
                }
            } catch (error) {
                console.error('Paketler yüklenemedi:', error);
            }
        }
        
        // Paketin testlerini yükle
        async function loadPackageTests(packageId) {
            try {
                const response = await fetch(`<?= $currentFile ?>?action=get_package_tests&package_id=${packageId}`);
                const data = await response.json();
                if (data.success && data.tests.length > 0) {
                    document.getElementById('packageTests').style.display = 'block';
                    document.getElementById('packageTestForms').style.display = 'block';
                    
                    // Test input formları oluştur
                    const inputsHtml = data.tests.map((test, index) => `
                        <div class="row mb-2 pb-2 border-bottom">
                            <div class="col-md-4">
                                <strong>${test.test_name}</strong><br>
                                <small class="text-muted">Kod: ${test.test_code}</small>
                                <input type="hidden" name="tests[${index}][code]" value="${test.test_code}">
                                <input type="hidden" name="tests[${index}][name]" value="${test.test_name}">
                                <input type="hidden" name="tests[${index}][unit]" value="${test.unit || ''}">
                                <input type="hidden" name="tests[${index}][min]" value="${test.min_ref || ''}">
                                <input type="hidden" name="tests[${index}][max]" value="${test.max_ref || ''}">
                            </div>
                            <div class="col-md-3">
                                <input type="text" name="tests[${index}][value]" class="form-control" 
                                       placeholder="Sonuç" required>
                            </div>
                            <div class="col-md-3">
                                <small class="text-muted">
                                    ${test.min_ref || '-'} - ${test.max_ref || '-'} ${test.unit || ''}
                                </small>
                            </div>
                        </div>
                    `).join('');
                    
                    document.getElementById('packageTestInputs').innerHTML = inputsHtml;
                }
            } catch (error) {
                console.error('Paket testleri yüklenemedi:', error);
            }
        }
        
        // Sonuçları yükle
        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) {
                    const tbody = document.getElementById('resultsTableBody');
                    
                    if (data.results.length === 0) {
                        tbody.innerHTML = `
                            <tr>
                                <td colspan="8" class="text-center text-muted">
                                    <i class="bi bi-inbox"></i> Henüz test sonucu yok
                                </td>
                            </tr>
                        `;
                        return;
                    }
                    
                    tbody.innerHTML = data.results.map(r => {
                        const date = new Date(r.result_date);
                        const dateStr = date.toLocaleDateString('tr-TR') + ' ' + date.toLocaleTimeString('tr-TR', {hour: '2-digit', minute: '2-digit'});
                        
                        const statusMap = {
                            'normal': 'Normal',
                            'low': 'Düşük',
                            'high': 'Yüksek',
                            'critical': 'Kritik'
                        };
                        
                        const sourceMap = {
                            'internal': 'İç Lab',
                            'external': r.external_lab_name || 'Dış Lab'
                        };
                        
                        const refRange = (r.reference_min || r.reference_max) ? 
                            `${r.reference_min || '-'} - ${r.reference_max || '-'} ${r.unit || ''}` : '-';
                        
                        return `
                            <tr>
                                <td><small>${dateStr}</small></td>
                                <td><code>${r.test_code}</code></td>
                                <td>${r.test_name}</td>
                                <td><strong>${r.result_value || '-'}</strong> ${r.unit || ''}</td>
                                <td><small>${refRange}</small></td>
                                <td><span class="status-badge status-${r.status}">${statusMap[r.status] || r.status}</span></td>
                                <td><span class="source-badge source-${r.source}">${sourceMap[r.source]}</span></td>
                                <td>
                                    ${r.source === 'internal' ? `
                                        <button class="btn btn-sm btn-danger" onclick="deleteResult(${r.id})">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    ` : '-'}
                                </td>
                            </tr>
                        `;
                    }).join('');
                }
            } catch (error) {
                console.error('Sonuçlar yüklenemedi:', error);
                alert('Sonuçlar yüklenirken hata oluştu');
            }
        }
        
        // Manuel sonuç kaydet
        async function saveManualResult() {
            if (!currentPatientId) {
                alert('Önce hasta seçin');
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'save_result');
            formData.append('patient_id', currentPatientId);
            formData.append('test_code', document.getElementById('testCode').value.toUpperCase());
            formData.append('test_name', document.getElementById('testName').value);
            formData.append('result_value', document.getElementById('resultValue').value);
            formData.append('reference_min', document.getElementById('refMin').value);
            formData.append('reference_max', document.getElementById('refMax').value);
            formData.append('unit', document.getElementById('unit').value);
            formData.append('result_date', document.getElementById('resultDate').value.replace('T', ' ') + ':00');
            formData.append('notes', document.getElementById('notes').value);
            
            try {
                const response = await fetch('<?= $currentFile ?>', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('Test sonucu kaydedildi');
                    document.getElementById('manualEntryForm').reset();
                    hideManualEntry();
                    loadResults();
                } else {
                    alert('Hata: ' + data.error);
                }
            } catch (error) {
                console.error('Kayıt hatası:', error);
                alert('Kayıt yapılırken hata oluştu');
            }
        }
        
        // Paket testlerini kaydet
        async function savePackageTests() {
            if (!currentPatientId) {
                alert('Önce hasta seçin');
                return;
            }
            
            const form = document.getElementById('packageTestForm');
            const formData = new FormData(form);
            
            const tests = [];
            let index = 0;
            while (formData.has(`tests[${index}][code]`)) {
                tests.push({
                    code: formData.get(`tests[${index}][code]`),
                    name: formData.get(`tests[${index}][name]`),
                    value: formData.get(`tests[${index}][value]`),
                    min: formData.get(`tests[${index}][min]`),
                    max: formData.get(`tests[${index}][max]`),
                    unit: formData.get(`tests[${index}][unit]`)
                });
                index++;
            }
            
            // Her testi ayrı ayrı kaydet
            let savedCount = 0;
            for (const test of tests) {
                const saveData = new FormData();
                saveData.append('action', 'save_result');
                saveData.append('patient_id', currentPatientId);
                saveData.append('test_code', test.code);
                saveData.append('test_name', test.name);
                saveData.append('result_value', test.value);
                saveData.append('reference_min', test.min);
                saveData.append('reference_max', test.max);
                saveData.append('unit', test.unit);
                saveData.append('result_date', new Date().toISOString().slice(0, 19).replace('T', ' '));
                
                try {
                    const response = await fetch('<?= $currentFile ?>', {
                        method: 'POST',
                        body: saveData
                    });
                    const data = await response.json();
                    if (data.success) savedCount++;
                } catch (error) {
                    console.error('Test kayıt hatası:', error);
                }
            }
            
            alert(`${savedCount} / ${tests.length} test kaydedildi`);
            hidePackageEntry();
            loadResults();
        }
        
        // Sonuç sil
        async function deleteResult(resultId) {
            if (!confirm('Bu test sonucunu 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();
                } else {
                    alert('Hata: ' + data.error);
                }
            } catch (error) {
                console.error('Silme hatası:', error);
                alert('Silme işlemi yapılırken hata oluştu');
            }
        }
        
        // Tarih filtresi fonksiyonları
        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();
        }
        
        // Tarih aralığına göre hastaları yükle
        async function loadPatientsByDateRange() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (!startDate || !endDate) {
                alert('Tarih aralığı seçin');
                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) {
                    const tbody = document.getElementById('patientsList');
                    
                    if (data.patients.length === 0) {
                        tbody.innerHTML = `
                            <tr>
                                <td colspan="6" class="text-center text-muted">
                                    <i class="bi bi-inbox"></i> Bu tarih aralığında sonuç bulunamadı
                                </td>
                            </tr>
                        `;
                        return;
                    }
                    
                    tbody.innerHTML = data.patients.map(p => {
                        const lastDate = p.last_result_date ? new Date(p.last_result_date).toLocaleDateString('tr-TR') : '-';
                        return `
                            <tr onclick="selectPatientFromList(${p.id}, '${p.full_name}', '${p.national_id}', '${p.birth_date}')">
                                <td><i class="bi bi-check-circle-fill text-success" style="cursor:pointer;"></i></td>
                                <td><strong>${p.full_name}</strong></td>
                                <td>${p.national_id || '-'}</td>
                                <td><span class="badge bg-info">${p.result_count}</span></td>
                                <td><small>${lastDate}</small></td>
                                <td>
                                    <button class="btn btn-sm btn-primary" onclick="selectPatientFromList(${p.id}, '${p.full_name}', '${p.national_id}', '${p.birth_date}'); event.stopPropagation();">
                                        Seç
                                    </button>
                                </td>
                            </tr>
                        `;
                    }).join('');
                } else {
                    alert('Hata: ' + data.error);
                }
            } catch (error) {
                console.error('Hasta listesi yüklenemedi:', error);
                alert('Hasta listesi yüklenirken hata oluştu');
            }
        }
        
        // Listeden hasta seç
        function selectPatientFromList(patientId, fullName, nationalId, birthDate) {
            currentPatientId = patientId;
            
            document.getElementById('selPatientName').textContent = fullName;
            document.getElementById('selPatientInfo').textContent = 
                'TC: ' + (nationalId || 'Yok') + ' | Doğum: ' + (birthDate || 'Yok');
            document.getElementById('selectedPatientPanel').style.display = 'block';
            document.getElementById('labContent').style.display = 'block';
            
            loadResults();
        }
        
        // Dropdown'dan hasta seç
        function selectPatientFromDropdown(patientId) {
            const option = document.querySelector(`#patientSelect option[value="${patientId}"]`);
            if (option) {
                selectPatientFromList(patientId, option.dataset.name, option.dataset.tc, option.dataset.birth);
            }
        }
        
        // Hasta seçimini temizle
        function clearPatientSelection() {
            currentPatientId = null;
            document.getElementById('selectedPatientPanel').style.display = 'none';
            document.getElementById('labContent').style.display = 'none';
            document.getElementById('disLabSendPanel').style.display = 'none';
        }
        
        // Dışlab gönderi panelini göster
        async function showDisLabSendPanel() {
            if (!currentPatientId) {
                alert('Hasta seçin');
                return;
            }
            
            document.getElementById('disLabSendPanel').style.display = 'block';
            
            // Mevcut testleri yükle
            try {
                const response = await fetch('<?= $currentFile ?>?action=get_test_definitions');
                const data = await response.json();
                
                if (data.success) {
                    const listDiv = document.getElementById('availableTestsList');
                    listDiv.innerHTML = data.tests.map(t => `
                        <div class="test-item" onclick="addTestToDislab('${t.code}', '${t.name}'); event.stopPropagation();">
                            <strong>${t.name}</strong><br>
                            <small class="text-muted">Kod: ${t.code}</small>
                        </div>
                    `).join('');
                }
            } catch (error) {
                console.error('Testler yüklenemedi:', error);
            }
        }
        
        // Dışlab gönderim panelini gizle
        function hideDisLabSendPanel() {
            document.getElementById('disLabSendPanel').style.display = 'none';
            document.getElementById('selectedTestsList').innerHTML = '<p class="text-muted">Yukarıdan test seçin</p>';
        }
        
        // Dışlab'a test ekle
        let selectedDisLabTests = [];
        function addTestToDislab(code, name) {
            if (!selectedDisLabTests.find(t => t.code === code)) {
                selectedDisLabTests.push({code, name});
                updateDisLabTestsList();
            }
        }
        
        // Dışlab seçili testler listesini güncelle
        function updateDisLabTestsList() {
            const listDiv = document.getElementById('selectedTestsList');
            if (selectedDisLabTests.length === 0) {
                listDiv.innerHTML = '<p class="text-muted">Yukarıdan test seçin</p>';
                return;
            }
            
            listDiv.innerHTML = selectedDisLabTests.map((t, idx) => `
                <div class="test-item">
                    <strong>${t.name}</strong><br>
                    <small class="text-muted">Kod: ${t.code}</small>
                    <button class="btn btn-xs btn-danger float-end" onclick="removeTestFromDislab(${idx}); event.stopPropagation();">
                        <i class="bi bi-x"></i>
                    </button>
                </div>
            `).join('');
        }
        
        // Dışlab testini kaldır
        function removeTestFromDislab(idx) {
            selectedDisLabTests.splice(idx, 1);
            updateDisLabTestsList();
        }
        
        // Dışlab'a gönder onayla
        async function sendToDislabConfirm() {
            if (selectedDisLabTests.length === 0) {
                alert('En az bir test seçin');
                return;
            }
            
            if (!confirm(`${selectedDisLabTests.length} test seçildi. Dışlab'a göndermek istediğinizden emin misiniz?`)) {
                return;
            }
            
            const formData = new FormData();
            formData.append('action', 'send_to_dislab');
            formData.append('patient_id', currentPatientId);
            selectedDisLabTests.forEach(t => {
                formData.append('test_codes[]', t.code);
            });
            
            try {
                const response = await fetch('<?= $currentFile ?>', {
                    method: 'POST',
                    body: formData
                });
                const data = await response.json();
                
                if (data.success) {
                    alert('Hasta dışlab\'a gönderildi');
                    selectedDisLabTests = [];
                    hideDisLabSendPanel();
                } else {
                    alert('Hata: ' + data.error);
                }
            } catch (error) {
                console.error('Gönderme hatası:', error);
                alert('Gönderme işlemi yapılırken hata oluştu');
            }
        }
        
        // Panel göster/gizle fonksiyonları
        function showManualEntry() {
            document.getElementById('manualEntryPanel').style.display = 'block';
            document.getElementById('packageEntryPanel').style.display = 'none';
            document.getElementById('testCode').focus();
        }
        
        function hideManualEntry() {
            document.getElementById('manualEntryPanel').style.display = 'none';
            document.getElementById('manualEntryForm').reset();
        }
        
        function showPackageEntry() {
            document.getElementById('packageEntryPanel').style.display = 'block';
            document.getElementById('manualEntryPanel').style.display = 'none';
        }
        
        function hidePackageEntry() {
            document.getElementById('packageEntryPanel').style.display = 'none';
            document.getElementById('packageSelect').value = '';
            document.getElementById('packageTests').style.display = 'none';
            document.getElementById('packageTestForms').style.display = 'none';
        }
        
        function showExternalLabImport() {
            alert('Dış lab entegrasyonu yakında eklenecek...');
            // TODO: Mevcut dislabIzle.php entegrasyonunu kullan
        }
    </script>
</body>
</html>
