<?php
/**
 * NEPHRO ERP - DOKTOR VİZİT PANELİ (Modern & Minimalist Tasarım)
 */
global $pdo;
if (session_status() === PHP_SESSION_NONE) { session_start(); }

if (!isset($pdo) || !($pdo instanceof PDO)) { die("Erişim yasak."); }

if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }
}

$user_id  = (int)($_SESSION['user_id'] ?? 0);
$hasta_id = (int)($_GET['id'] ?? 0);

$hasta     = null;
$vizitler  = [];
$sablonlar = [];

// Aktif hastalar
$hastalar = $pdo->query("SELECT id, ad, soyad FROM hastalar WHERE durum='aktif' ORDER BY ad ASC")->fetchAll(PDO::FETCH_ASSOC);

if ($hasta_id > 0) {
    $h_stmt = $pdo->prepare("SELECT *, FLOOR(DATEDIFF(NOW(), dogum_tarihi) / 365.25) as yas FROM hastalar WHERE id = ? LIMIT 1");
    $h_stmt->execute([$hasta_id]);
    $hasta = $h_stmt->fetch(PDO::FETCH_ASSOC);

    if ($hasta) {
        $v_stmt = $pdo->prepare("
            SELECT v.*, k.ad_soyad as doktor_adi
            FROM vizit_notlari v
            LEFT JOIN kullanicilar k ON v.doktor_id = k.id
            WHERE v.hasta_id = ?
            ORDER BY v.kayit_tarihi DESC
        ");
        $v_stmt->execute([$hasta_id]);
        $vizitler = $v_stmt->fetchAll(PDO::FETCH_ASSOC);

        // Şablonları getir
        try {
            $s_stmt = $pdo->prepare("
                SELECT * FROM vizit_sablonlari
                WHERE kullanici_id = ? OR genel = 1
                ORDER BY sablon_adi ASC
            ");
            $s_stmt->execute([$user_id]);
            $sablonlar = $s_stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            $sablonlar = [];
        }
    }
}

// Varsayılan şablonlar
$defaultSablonlar = [
    'stabil' => [
        'ad' => 'Stabil Hasta',
        'not' => 'Genel durum iyi, stabil seyir. Hasta şikayeti yok.',
        'fizik' => 'S1 S2 doğal, ödem (-), nabız ve tansiyon normal sınırlarda.',
        'plan' => 'Mevcut tedavi programına devam.'
    ],
    'odem' => [
        'ad' => 'Ödemli Hasta',
        'not' => 'Aşırı sıvı yükü mevcut, ödem (+)',
        'fizik' => 'Ödem (+++), dispne mevcut, çift basma (+).',
        'plan' => 'UF hedefi artırılacak, sıvı kısıtlaması tekrar anlatılacak.'
    ],
    'hipertansif' => [
        'ad' => 'Hipertansif Hasta',
        'not' => 'Kan basıncı yüksek seyrediyor.',
        'fizik' => 'Tansiyon yüksek, ödem (+/-).',
        'plan' => 'Antihipertansif tedavi gözden geçirilecek.'
    ]
];

// Hasta initials
$initials = 'H';
if ($hasta) {
    $ad = (string)($hasta['ad'] ?? '');
    $soyad = (string)($hasta['soyad'] ?? '');
    $initials = trim(mb_strtoupper(mb_substr($ad,0,1,'UTF-8').mb_substr($soyad,0,1,'UTF-8'),'UTF-8'));
    if ($initials === '') $initials = 'H';
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doktor Vizit Paneli - NEPHRO ERP</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg: #f9fafb;
            --surface: #ffffff;
            --border: #e5e7eb;
            --border-light: #f3f4f6;
            --text: #111827;
            --text-secondary: #6b7280;
            --text-muted: #9ca3af;
            --primary: #3b82f6;
            --primary-dark: #2563eb;
            --primary-light: #eff6ff;
            --success: #10b981;
            --danger: #ef4444;
            --danger-light: #fef2f2;
            --warning: #f59e0b;
            --info: #8b5cf6;
            --radius: 8px;
            --radius-lg: 12px;
            --shadow: 0 1px 3px rgba(0,0,0,0.1);
            --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 15px -3px rgba(0,0,0,0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: var(--bg);
            color: var(--text);
            line-height: 1.5;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .container {
            max-width: 1280px;
            margin: 0 auto;
            padding: 20px;
        }

        /* Header */
        .header {
            background: var(--surface);
            border-radius: var(--radius-lg);
            padding: 24px;
            margin-bottom: 20px;
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
        }

        .header-title {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 16px;
        }

        .header-title h1 {
            font-size: 24px;
            font-weight: 600;
            color: var(--text);
        }

        .header-title i {
            color: var(--primary);
            font-size: 20px;
        }

        .header-subtitle {
            color: var(--text-secondary);
            font-size: 14px;
            margin-bottom: 20px;
        }

        /* Patient Selector */
        .patient-selector {
            display: grid;
            grid-template-columns: 1fr auto;
            gap: 12px;
            align-items: center;
        }

        @media (max-width: 768px) {
            .patient-selector {
                grid-template-columns: 1fr;
            }
        }

        .select-patient {
            width: 100%;
            padding: 10px 16px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            color: var(--text);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            outline: none;
            transition: border-color 0.2s;
        }

        .select-patient:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .selected-patient {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            background: var(--primary-light);
            border: 1px solid rgba(59, 130, 246, 0.2);
            border-radius: var(--radius);
            color: var(--primary-dark);
            font-weight: 500;
            font-size: 14px;
        }

        .selected-patient i {
            font-size: 16px;
        }

        /* Main Layout */
        .main-layout {
            display: grid;
            grid-template-columns: 400px 1fr;
            gap: 20px;
            margin-top: 20px;
        }

        @media (max-width: 1024px) {
            .main-layout {
                grid-template-columns: 1fr;
            }
        }

        /* Panel */
        .panel {
            background: var(--surface);
            border-radius: var(--radius-lg);
            border: 1px solid var(--border);
            overflow: hidden;
        }

        .panel-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-light);
            background: var(--surface);
        }

        .panel-header h2 {
            font-size: 18px;
            font-weight: 600;
            color: var(--text);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .panel-header h2 i {
            color: var(--primary);
        }

        .panel-body {
            padding: 20px;
        }

        /* Patient Info */
        .patient-info {
            display: flex;
            gap: 16px;
            align-items: center;
            padding: 16px;
            background: var(--bg);
            border-radius: var(--radius);
            margin-bottom: 20px;
        }

        .patient-avatar {
            width: 64px;
            height: 64px;
            border-radius: var(--radius);
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            font-weight: 600;
        }

        .patient-details h3 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .patient-meta {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
            margin-top: 8px;
        }

        .meta-item {
            font-size: 13px;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .meta-item i {
            color: var(--text-muted);
            font-size: 12px;
        }

        /* Stats */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
            margin-bottom: 24px;
        }

        .stat-card {
            padding: 12px;
            border: 1px solid var(--border-light);
            border-radius: var(--radius);
            background: var(--surface);
        }

        .stat-label {
            font-size: 12px;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 4px;
        }

        .stat-value {
            font-size: 16px;
            font-weight: 600;
            color: var(--text);
        }

        /* Templates */
        .templates-section {
            margin-bottom: 24px;
        }

        .templates-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--text);
            margin-bottom: 12px;
        }

        .templates-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 10px;
        }

        @media (max-width: 768px) {
            .templates-grid {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
            }
        }

        .template-btn {
            padding: 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            color: var(--text-secondary);
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
            text-align: left;
        }

        .template-btn:hover {
            border-color: var(--primary);
            background: var(--primary-light);
        }

        .template-btn i {
            color: var(--primary);
        }

        /* Form */
        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            color: var(--text);
            margin-bottom: 8px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

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

        .form-input, .form-select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            color: var(--text);
            font-family: inherit;
            font-size: 14px;
            outline: none;
            transition: border-color 0.2s;
        }

        .form-input:focus, .form-select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        textarea.form-input {
            min-height: 100px;
            resize: vertical;
            line-height: 1.5;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            margin-top: 24px;
        }

        @media (max-width: 640px) {
            .form-actions {
                flex-direction: column;
            }
        }

        .btn {
            padding: 10px 20px;
            border-radius: var(--radius);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            border: none;
            outline: none;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            flex: 1;
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .btn-primary.edit-mode {
            background: var(--success);
        }

        .btn-primary.edit-mode:hover {
            background: #047857;
        }

        .btn-secondary {
            background: var(--surface);
            color: var(--text);
            border: 1px solid var(--border);
        }

        .btn-secondary:hover {
            background: var(--bg);
        }

        /* Visits History */
        .visits-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .visits-count {
            font-size: 14px;
            color: var(--text-secondary);
            font-weight: 500;
        }

        .visits-list {
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .visit-card {
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            padding: 16px;
            position: relative;
        }

        .visit-card::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            border-radius: var(--radius) 0 0 var(--radius);
        }

        .visit-card.rutin::before {
            background: var(--primary);
        }

        .visit-card.acil::before {
            background: var(--danger);
        }

        .visit-card.konsültasyon::before {
            background: var(--info);
        }

        .visit-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }

        .visit-type {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: var(--bg);
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .visit-type.rutin {
            color: var(--primary);
            background: var(--primary-light);
        }

        .visit-type.acil {
            color: var(--danger);
            background: var(--danger-light);
        }

        .visit-type.konsültasyon {
            color: var(--info);
            background: #faf5ff;
        }

        .visit-actions {
            display: flex;
            gap: 8px;
        }

        .icon-btn {
            width: 32px;
            height: 32px;
            border-radius: 6px;
            border: 1px solid var(--border);
            background: var(--surface);
            color: var(--text-secondary);
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .icon-btn:hover {
            background: var(--bg);
        }

        .icon-btn.edit:hover {
            color: var(--primary);
            border-color: var(--primary);
        }

        .icon-btn.delete:hover {
            color: var(--danger);
            border-color: var(--danger);
        }

        .visit-summary {
            color: var(--text);
            font-size: 14px;
            line-height: 1.6;
            white-space: pre-line;
            margin-bottom: 12px;
            padding: 12px;
            background: var(--bg);
            border-radius: var(--radius);
        }

        .visit-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
            margin-bottom: 12px;
        }

        @media (max-width: 768px) {
            .visit-details {
                grid-template-columns: 1fr;
            }
        }

        .detail-box {
            background: var(--bg);
            border-radius: var(--radius);
            padding: 12px;
        }

        .detail-label {
            font-size: 12px;
            color: var(--text-muted);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .detail-content {
            font-size: 14px;
            line-height: 1.5;
            white-space: pre-line;
        }

        .visit-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: var(--text-muted);
            padding-top: 12px;
            border-top: 1px solid var(--border-light);
        }

        .visit-author, .visit-date {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 48px;
            color: var(--border);
            margin-bottom: 16px;
        }

        .empty-state h3 {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 8px;
            color: var(--text);
        }

        .empty-state p {
            font-size: 14px;
            max-width: 400px;
            margin: 0 auto;
        }

        /* Mobile Tabs */
        .mobile-tabs {
            display: none;
            background: var(--surface);
            border-radius: var(--radius);
            border: 1px solid var(--border);
            overflow: hidden;
            margin-bottom: 20px;
        }

        @media (max-width: 1024px) {
            .mobile-tabs {
                display: flex;
            }
        }

        .tab-btn {
            flex: 1;
            padding: 14px;
            border: none;
            background: none;
            color: var(--text-secondary);
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .tab-btn.active {
            background: var(--primary-light);
            color: var(--primary-dark);
        }

        .mobile-section {
            display: block;
        }

        @media (max-width: 1024px) {
            .mobile-section {
                display: none;
            }
            
            .mobile-section.active {
                display: block;
            }
        }

        /* Utility Classes */
        .text-muted {
            color: var(--text-muted);
        }

        .mt-4 { margin-top: 16px; }
        .mb-4 { margin-bottom: 16px; }
        .mt-2 { margin-top: 8px; }
        .mb-2 { margin-bottom: 8px; }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="header-title">
                <i class="fas fa-user-md"></i>
                <h1>Doktor Vizit Paneli</h1>
            </div>
            <div class="header-subtitle">
                NEPHRO ERP - Hasta vizit notları ve takip sistemi
            </div>
            
            <!-- Patient Selector -->
            <div class="patient-selector">
                <select class="select-patient" onchange="if(this.value){window.location.href='?sayfa=vizit-notlari&id='+encodeURIComponent(this.value)}">
                    <option value="">Hasta seçiniz...</option>
                    <?php foreach ($hastalar as $h): ?>
                        <option value="<?= (int)$h['id'] ?>" <?= $hasta_id == (int)$h['id'] ? 'selected' : '' ?>>
                            <?= h(mb_strtoupper($h['ad'].' '.$h['soyad'],'UTF-8')) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <?php if ($hasta): ?>
                    <div class="selected-patient">
                        <i class="fas fa-user-check"></i>
                        <span><?= h(mb_strtoupper(($hasta['ad'] ?? '').' '.($hasta['soyad'] ?? ''),'UTF-8')) ?></span>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!$hasta): ?>
            <!-- Empty State -->
            <div class="empty-state">
                <i class="fas fa-user-injured"></i>
                <h3>Hasta Seçimi</h3>
                <p>Yukarıdaki listeden bir hasta seçerek vizit notları eklemeye başlayabilirsiniz.</p>
            </div>
        <?php else: ?>
            <!-- Mobile Tabs -->
            <div class="mobile-tabs">
                <button class="tab-btn active" data-tab="form">
                    <i class="fas fa-pen-to-square"></i>
                    <span>Vizit Ekle</span>
                </button>
                <button class="tab-btn" data-tab="list">
                    <i class="fas fa-history"></i>
                    <span>Geçmiş</span>
                </button>
            </div>

            <div class="main-layout">
                <!-- Left Panel - Form -->
                <div class="panel mobile-section active" id="sec-form">
                    <div class="panel-header">
                        <h2><i class="fas fa-file-medical"></i> Hasta Bilgileri ve Vizit Ekle</h2>
                    </div>
                    <div class="panel-body">
                        <!-- Patient Info -->
                        <div class="patient-info">
                            <div class="patient-avatar"><?= h($initials) ?></div>
                            <div class="patient-details">
                                <h3><?= h(mb_strtoupper($ad.' '.$soyad,'UTF-8')) ?></h3>
                                <div class="patient-meta">
                                    <span class="meta-item"><i class="fas fa-id-card"></i> ID: <?= (int)$hasta_id ?></span>
                                    <span class="meta-item"><i class="fas fa-user"></i> <?= h((string)($hasta['yas'] ?? '')) ?> yaş</span>
                                    <span class="meta-item"><i class="fas fa-venus-mars"></i> <?= h((string)($hasta['cinsiyet'] ?? '')) ?></span>
                                </div>
                            </div>
                        </div>

                        <!-- Stats -->
                        <div class="stats-grid">
                            <div class="stat-card">
                                <div class="stat-label">Kuru Ağırlık</div>
                                <div class="stat-value"><?= h((string)($hasta['kuru_agirlik'] ?? '')) ?> kg</div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-label">Hepatit</div>
                                <div class="stat-value"><?= h((string)($hasta['hepatit_durumu'] ?? '')) ?></div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-label">Damar Yolu</div>
                                <div class="stat-value"><?= h((string)($hasta['damar_yolu'] ?? '')) ?></div>
                            </div>
                            <div class="stat-card">
                                <div class="stat-label">Toplam Vizit</div>
                                <div class="stat-value"><?= (int)count($vizitler) ?></div>
                            </div>
                        </div>

                        <!-- Templates -->
                        <div class="templates-section">
                            <label class="templates-label">Hızlı Şablonlar</label>
                            <div class="templates-grid">
                                <?php foreach ($defaultSablonlar as $key => $sablon): ?>
                                    <button type="button" class="template-btn"
                                            onclick="applyTemplate('<?= h($key) ?>')">
                                        <i class="fas fa-wand-magic-sparkles"></i>
                                        <?= h($sablon['ad']) ?>
                                    </button>
                                <?php endforeach; ?>

                                <?php foreach ($sablonlar as $s): ?>
                                    <?php
                                        $payload = [
                                            'not'   => (string)($s['not_icerigi'] ?? ''),
                                            'fizik' => (string)($s['fizik_muayene'] ?? ''),
                                            'plan'  => (string)($s['tedavi_plani'] ?? ''),
                                        ];
                                        $json = htmlspecialchars(json_encode($payload, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <button type="button" class="template-btn" data-dbtemplate="<?= $json ?>">
                                        <i class="fas fa-database"></i>
                                        <?= h((string)($s['sablon_adi'] ?? 'Şablon')) ?>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Form -->
                        <form action="islem.php" method="POST" id="vizitForm" autocomplete="off">
                            <input type="hidden" name="hasta_id" value="<?= (int)$hasta_id ?>">
                            <input type="hidden" name="not_id" id="form_not_id" value="0">

                            <div class="form-group">
                                <div class="form-grid">
                                    <div>
                                        <label class="form-label" for="v_tipi">Vizit Tipi</label>
                                        <select name="vizit_tipi" id="v_tipi" class="form-select">
                                            <option value="Rutin">Rutin Vizit</option>
                                            <option value="Acil">Acil Vizit</option>
                                            <option value="Konsültasyon">Konsültasyon</option>
                                        </select>
                                    </div>
                                    <div>
                                        <label class="form-label" for="v_not">Vizit Özeti</label>
                                        <input type="text" name="not_icerigi" id="v_not" class="form-input"
                                               placeholder="Vizit özetini buraya yazın..." required>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="v_fizik">Fizik Muayene Bulguları</label>
                                <textarea name="fizik_muayene" id="v_fizik" class="form-input"
                                          placeholder="Fizik muayene bulgularınızı yazın..." rows="3"></textarea>
                            </div>

                            <div class="form-group">
                                <label class="form-label" for="v_plan">Tedavi Planı ve Öneriler</label>
                                <textarea name="tedavi_plani" id="v_plan" class="form-input"
                                          placeholder="Tedavi planı ve öneriler..." rows="3"></textarea>
                            </div>

                            <div class="form-actions">
                                <button type="submit" name="vizit_kaydet_pro" id="submitBtn" class="btn btn-primary">
                                    <i class="fas fa-save"></i>
                                    <span>Viziti Kaydet</span>
                                </button>
                                <button type="button" id="cancelBtn" onclick="resetVizitForm()" class="btn btn-secondary" style="display:none;">
                                    <i class="fas fa-times"></i>
                                    <span>İptal</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Right Panel - Visits History -->
                <div class="panel mobile-section" id="sec-list">
                    <div class="panel-header">
                        <h2><i class="fas fa-history"></i> Vizit Geçmişi</h2>
                    </div>
                    <div class="panel-body">
                        <!-- Visits Count -->
                        <div class="visits-header">
                            <div class="visits-count">
                                <i class="fas fa-file-medical-alt"></i>
                                <?= (int)count($vizitler) ?> vizit
                            </div>
                        </div>

                        <!-- Visits List -->
                        <?php if (empty($vizitler)): ?>
                            <div class="empty-state">
                                <i class="fas fa-file-medical"></i>
                                <h3>Henüz Vizit Yok</h3>
                                <p>Bu hastaya ait henüz vizit kaydı yok. İlk viziti yukarıdan ekleyebilirsiniz.</p>
                            </div>
                        <?php else: ?>
                            <div class="visits-list">
                                <?php foreach ($vizitler as $v): ?>
                                    <?php
                                        $tip = (string)($v['vizit_tipi'] ?? 'Rutin');
                                        $tipClass = mb_strtolower($tip, 'UTF-8');
                                        if ($tipClass === 'konsültasyon' || $tipClass === 'konsultasyon') $tipClass = 'konsültasyon';

                                        $editPayload = [
                                            'id'    => (int)$v['id'],
                                            'tipi'  => (string)($v['vizit_tipi'] ?? 'Rutin'),
                                            'not'   => (string)($v['not_icerigi'] ?? ''),
                                            'fizik' => (string)($v['fizik_muayene'] ?? ''),
                                            'plan'  => (string)($v['tedavi_plani'] ?? ''),
                                        ];
                                        $editJson = htmlspecialchars(json_encode($editPayload, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
                                    ?>
                                    <div class="visit-card <?= h($tipClass) ?>">
                                        <div class="visit-header">
                                            <div class="visit-type <?= h($tipClass) ?>">
                                                <i class="fas fa-<?= ($tip === 'Acil') ? 'triangle-exclamation' : 'stethoscope' ?>"></i>
                                                <?= h($tip) ?>
                                            </div>

                                            <div class="visit-actions">
                                                <button type="button"
                                                        class="icon-btn edit"
                                                        data-edit="<?= $editJson ?>"
                                                        title="Viziti Düzenle">
                                                    <i class="fas fa-edit"></i>
                                                </button>

                                                <a href="islem.php?islem=not_sil&tip=vizit&id=<?= (int)$v['id'] ?>&hasta_id=<?= (int)$hasta_id ?>"
                                                   class="icon-btn delete"
                                                   onclick="return confirm('Bu vizit notunu silmek istediğinize emin misiniz?')"
                                                   title="Viziti Sil">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </div>
                                        </div>

                                        <div class="visit-summary">
                                            <?= nl2br(h((string)($v['not_icerigi'] ?? ''))) ?>
                                        </div>

                                        <?php if (!empty($v['fizik_muayene']) || !empty($v['tedavi_plani'])): ?>
                                            <div class="visit-details">
                                                <?php if (!empty($v['fizik_muayene'])): ?>
                                                    <div class="detail-box">
                                                        <div class="detail-label"><i class="fas fa-heartbeat"></i> Fizik Muayene</div>
                                                        <div class="detail-content"><?= nl2br(h((string)$v['fizik_muayene'])) ?></div>
                                                    </div>
                                                <?php endif; ?>

                                                <?php if (!empty($v['tedavi_plani'])): ?>
                                                    <div class="detail-box">
                                                        <div class="detail-label"><i class="fas fa-clipboard-list"></i> Tedavi Planı</div>
                                                        <div class="detail-content"><?= nl2br(h((string)$v['tedavi_plani'])) ?></div>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        <?php endif; ?>

                                        <div class="visit-footer">
                                            <div class="visit-author">
                                                <i class="fas fa-user-md"></i>
                                                Dr. <?= h((string)($v['doktor_adi'] ?: 'Sistem')) ?>
                                            </div>
                                            <div class="visit-date">
                                                <i class="far fa-clock"></i>
                                                <?php
                                                    $t = $v['kayit_tarihi'] ?? '';
                                                    echo $t ? h(date('d.m.Y H:i', strtotime($t))) : '-';
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // Default templates
        const templates = {
            stabil: {
                not: 'Genel durum iyi, stabil seyir. Hasta şikayeti yok.',
                fizik: 'S1 S2 doğal, ödem (-), nabız ve tansiyon normal sınırlarda.',
                plan: 'Mevcut tedavi programına devam.'
            },
            odem: {
                not: 'Aşırı sıvı yükü mevcut, ödem (+)',
                fizik: 'Ödem (+++), dispne mevcut, çift basma (+).',
                plan: 'UF hedefi artırılacak, sıvı kısıtlaması tekrar anlatılacak.'
            },
            hipertansif: {
                not: 'Kan basıncı yüksek seyrediyor.',
                fizik: 'Tansiyon yüksek, ödem (+/-).',
                plan: 'Antihipertansif tedavi gözden geçirilecek.'
            }
        };

        function showToast(message) {
            // Create toast element
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.innerHTML = `
                <div style="
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    background: var(--primary);
                    color: white;
                    padding: 12px 20px;
                    border-radius: var(--radius);
                    font-weight: 500;
                    box-shadow: var(--shadow-lg);
                    animation: slideIn 0.3s ease;
                    z-index: 1000;
                ">
                    ${message}
                </div>
            `;
            
            document.body.appendChild(toast);
            
            // Remove after 3 seconds
            setTimeout(() => {
                toast.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        function applyTemplate(key) {
            if (!templates[key]) return;
            document.getElementById('v_not').value   = templates[key].not;
            document.getElementById('v_fizik').value = templates[key].fizik;
            document.getElementById('v_plan').value  = templates[key].plan;
            showToast('Şablon uygulandı');
        }

        // DB şablon butonları
        document.querySelectorAll('.template-btn[data-dbtemplate]').forEach(btn => {
            btn.addEventListener('click', () => {
                try {
                    const d = JSON.parse(btn.getAttribute('data-dbtemplate'));
                    document.getElementById('v_not').value   = d.not || '';
                    document.getElementById('v_fizik').value = d.fizik || '';
                    document.getElementById('v_plan').value  = d.plan || '';
                    showToast('Özel şablon uygulandı');
                } catch (e) {
                    console.error(e);
                    alert('Şablon okunamadı.');
                }
            });
        });

        function setEditMode(on) {
            const submitBtn = document.getElementById('submitBtn');
            const cancelBtn = document.getElementById('cancelBtn');
            const submitIcon = submitBtn.querySelector('i');
            const submitText = submitBtn.querySelector('span');
            
            if (on) {
                submitIcon.className = 'fas fa-sync-alt';
                submitText.textContent = 'Viziti Güncelle';
                submitBtn.classList.add('edit-mode');
                cancelBtn.style.display = 'flex';
            } else {
                submitIcon.className = 'fas fa-save';
                submitText.textContent = 'Viziti Kaydet';
                submitBtn.classList.remove('edit-mode');
                cancelBtn.style.display = 'none';
            }
        }

        function resetVizitForm() {
            document.getElementById('form_not_id').value = '0';
            document.getElementById('vizitForm').reset();
            setEditMode(false);
            showToast('Form sıfırlandı');
        }

        // EDIT: data-edit ile
        document.querySelectorAll('.icon-btn.edit[data-edit]').forEach(btn => {
            btn.addEventListener('click', () => {
                try {
                    const v = JSON.parse(btn.getAttribute('data-edit'));
                    document.getElementById('form_not_id').value = v.id || 0;
                    document.getElementById('v_tipi').value = v.tipi || 'Rutin';
                    document.getElementById('v_not').value = v.not || '';
                    document.getElementById('v_fizik').value = v.fizik || '';
                    document.getElementById('v_plan').value = v.plan || '';
                    setEditMode(true);

                    // Switch to form tab on mobile
                    const formTab = document.querySelector('.tab-btn[data-tab="form"]');
                    if (formTab && !formTab.classList.contains('active')) {
                        formTab.click();
                    }

                    // Scroll to form
                    document.getElementById('sec-form').scrollIntoView({ behavior: 'smooth' });

                    showToast('Düzenleme moduna geçildi');
                } catch (e) {
                    console.error('Edit parse hatası:', e);
                    alert('Düzenleme verisi okunamadı.');
                }
            });
        });

        // ESC ile sıfırla
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') resetVizitForm();
        });

        // Form validation
        const form = document.getElementById('vizitForm');
        if (form) {
            form.addEventListener('submit', function(e) {
                const notIcerigi = (document.getElementById('v_not').value || '').trim();
                if (notIcerigi.length < 5) {
                    e.preventDefault();
                    alert('Vizit özeti en az 5 karakter olmalıdır.');
                    document.getElementById('v_not').focus();
                }
            });
        }

        // Mobile Tab Switching
        const tabButtons = document.querySelectorAll('.tab-btn');
        const sections = document.querySelectorAll('.mobile-section');
        
        tabButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                const tab = btn.getAttribute('data-tab');
                
                // Update active tab
                tabButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                // Show corresponding section
                sections.forEach(section => section.classList.remove('active'));
                document.getElementById(`sec-${tab}`).classList.add('active');
            });
        });

        // Add CSS for toast animations
        const style = document.createElement('style');
        style.textContent = `
            @keyframes slideIn {
                from { transform: translateX(100%); opacity: 0; }
                to { transform: translateX(0); opacity: 1; }
            }
            
            @keyframes slideOut {
                from { transform: translateX(0); opacity: 1; }
                to { transform: translateX(100%); opacity: 0; }
            }
        `;
        document.head.appendChild(style);
    </script>
</body>
</html>