<?php
/**
 * NEPHRO ERP - HEMŞİRE SEYİR DEFTERİ (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"); }
}
function idify($s){
    $map = ['İ'=>'I','ı'=>'i','Ş'=>'S','ş'=>'s','Ğ'=>'G','ğ'=>'g','Ü'=>'U','ü'=>'u','Ö'=>'O','ö'=>'o','Ç'=>'C','ç'=>'c'];
    $s = strtr((string)$s, $map);
    $s = preg_replace('/[^A-Za-z0-9]+/', '', $s);
    return $s ?: 'Genel';
}

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

// Filtre
$filtre_arama = trim($_GET['arama'] ?? '');

// 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) {
        $sql_where = "WHERE n.hasta_id = ?";
        $params = [$hasta_id];

        if ($filtre_arama !== '') {
            $sql_where .= " AND n.not_icerigi LIKE ?";
            $params[] = "%{$filtre_arama}%";
        }

        $n_stmt = $pdo->prepare("
            SELECT n.*, k.ad_soyad as hemsire_adi
            FROM hemsire_notlari n
            LEFT JOIN kullanicilar k ON n.hemsire_id = k.id
            $sql_where
            ORDER BY n.kayit_vakti DESC
        ");
        $n_stmt->execute($params);
        $notlar = $n_stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

// Not tipleri ve renkleri
$tipler = [
    "Genel"     => ["#4b5563", "#f3f4f6"],
    "Giriş"     => ["#3b82f6", "#eff6ff"],
    "Seans İçi" => ["#10b981", "#ecfdf5"],
    "Çıkış"     => ["#8b5cf6", "#faf5ff"],
    "Acil"      => ["#ef4444", "#fef2f2"],
];
?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Hemşire Seyir Defteri - 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;
            --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);
        }

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

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

        .note-type-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 8px;
        }

        .note-type-btn {
            padding: 10px 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;
            justify-content: center;
            gap: 6px;
            transition: all 0.2s;
        }

        .note-type-btn:hover {
            border-color: var(--primary);
        }

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

        .textarea {
            width: 100%;
            min-height: 120px;
            padding: 12px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            color: var(--text);
            font-family: inherit;
            font-size: 14px;
            line-height: 1.5;
            resize: vertical;
            outline: none;
            transition: border-color 0.2s;
        }

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

        .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-secondary {
            background: var(--surface);
            color: var(--text);
            border: 1px solid var(--border);
        }

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

        /* Notes List */
        .notes-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .search-box {
            position: relative;
            flex: 1;
            max-width: 300px;
        }

        .search-box i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--text-muted);
            font-size: 14px;
        }

        .search-input {
            width: 100%;
            padding: 10px 10px 10px 36px;
            border: 1px solid var(--border);
            border-radius: var(--radius);
            background: var(--surface);
            color: var(--text);
            font-size: 14px;
            outline: none;
        }

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

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

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

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

        .note-card::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            width: 4px;
            border-radius: var(--radius) 0 0 var(--radius);
            background: var(--note-color, #4b5563);
        }

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

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

        .note-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);
        }

        .note-content {
            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);
        }

        .note-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 12px;
            color: var(--text-muted);
        }

        .note-author, .note-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-clipboard-medical"></i>
                <h1>Hemşire Seyir Defteri</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=hemsire-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: ?>
            <?php
                $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';
            ?>

            <!-- Mobile Tabs -->
            <div class="mobile-tabs">
                <button class="tab-btn active" data-tab="form">
                    <i class="fas fa-pen-to-square"></i>
                    <span>Not 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-user-nurse"></i> Hasta Bilgileri ve Not 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 Not</div>
                                <div class="stat-value"><?= (int)count($notlar) ?></div>
                            </div>
                        </div>

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

                            <!-- Note Type -->
                            <div class="form-group">
                                <label class="form-label">Not Türü</label>
                                <div class="note-type-grid">
                                    <?php foreach ($tipler as $tip => $colors): 
                                        $rid = idify($tip);
                                        $icon = match($tip){
                                            'Genel'=>'fa-solid fa-note-sticky',
                                            'Giriş'=>'fa-solid fa-right-to-bracket',
                                            'Seans İçi'=>'fa-solid fa-heart-pulse',
                                            'Çıkış'=>'fa-solid fa-right-from-bracket',
                                            'Acil'=>'fa-solid fa-triangle-exclamation',
                                            default=>'fa-solid fa-note-sticky'
                                        };
                                    ?>
                                        <button type="button" class="note-type-btn <?= $tip==='Genel'?'active':'' ?>" 
                                                data-type="<?= h($tip) ?>"
                                                style="--note-color:<?= h($colors[0]) ?>;--note-bg:<?= h($colors[1]) ?>">
                                            <i class="<?= h($icon) ?>"></i>
                                            <?= h($tip) ?>
                                        </button>
                                        <input type="radio" name="not_tipi" id="radio_<?= h($rid) ?>" 
                                               value="<?= h($tip) ?>" <?= $tip==='Genel'?'checked':'' ?> hidden>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Note Content -->
                            <div class="form-group">
                                <label class="form-label" for="v_not">Not İçeriği</label>
                                <textarea class="textarea" name="not_icerigi" id="v_not" required 
                                          placeholder="Vizit notunu net ve açık bir şekilde yazınız..."></textarea>
                                <div class="text-muted mt-2">En az 10 karakter gereklidir.</div>
                            </div>

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

                <!-- Right Panel - Notes History -->
                <div class="panel mobile-section" id="sec-list">
                    <div class="panel-header">
                        <h2><i class="fas fa-history"></i> Not Geçmişi</h2>
                    </div>
                    <div class="panel-body">
                        <!-- Search and Filter -->
                        <div class="notes-header">
                            <div class="search-box">
                                <i class="fas fa-search"></i>
                                <form method="GET">
                                    <input type="hidden" name="sayfa" value="hemsire-notlari">
                                    <input type="hidden" name="id" value="<?= (int)$hasta_id ?>">
                                    <input class="search-input" type="text" name="arama" 
                                           placeholder="Notlarda ara..." value="<?= h($filtre_arama) ?>">
                                </form>
                            </div>
                            <div class="notes-count">
                                <?= (int)count($notlar) ?> not
                                <?php if ($filtre_arama !== ''): ?>
                                    <span class="text-muted">(filtrelendi)</span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Notes List -->
                        <?php if (empty($notlar)): ?>
                            <div class="empty-state">
                                <i class="fas fa-clipboard-list"></i>
                                <h3>Henüz not bulunmuyor</h3>
                                <p>Bu hasta için henüz hiç not eklenmemiş.</p>
                            </div>
                        <?php else: ?>
                            <div class="notes-list">
                                <?php foreach ($notlar as $n):
                                    $tip = (string)($n['not_tipi'] ?? 'Genel');
                                    $tip_renk = $tipler[$tip] ?? ['#4b5563','#f3f4f6'];
                                    
                                    $payload = [
                                        'id' => (int)($n['id'] ?? 0),
                                        'tip' => $tip,
                                        'icerik' => (string)($n['not_icerigi'] ?? ''),
                                    ];
                                    $json = htmlspecialchars(json_encode($payload, JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');
                                    
                                    $icon = match($tip){
                                        'Genel'=>'fa-solid fa-note-sticky',
                                        'Giriş'=>'fa-solid fa-right-to-bracket',
                                        'Seans İçi'=>'fa-solid fa-heart-pulse',
                                        'Çıkış'=>'fa-solid fa-right-from-bracket',
                                        'Acil'=>'fa-solid fa-triangle-exclamation',
                                        default=>'fa-solid fa-note-sticky'
                                    };
                                ?>
                                    <div class="note-card" style="--note-color:<?= h($tip_renk[0]) ?>;--note-bg:<?= h($tip_renk[1]) ?>">
                                        <div class="note-header">
                                            <div class="note-type">
                                                <i class="<?= h($icon) ?>"></i>
                                                <?= h($tip) ?>
                                            </div>
                                            <div class="note-actions">
                                                <button type="button" class="icon-btn edit" data-edit="<?= $json ?>" title="Düzenle">
                                                    <i class="fas fa-pen"></i>
                                                </button>
                                                <a class="icon-btn delete" 
                                                   href="islem.php?islem=not_sil&tip=hemsire&id=<?= (int)$n['id'] ?>&hasta_id=<?= (int)$hasta_id ?>"
                                                   onclick="return confirm('Bu notu silmek istediğinize emin misiniz?')"
                                                   title="Sil">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </div>
                                        <div class="note-content">
                                            <?= nl2br(h((string)($n['not_icerigi'] ?? ''))) ?>
                                        </div>
                                        <div class="note-footer">
                                            <div class="note-author">
                                                <i class="fas fa-user-nurse"></i>
                                                <?= h((string)($n['hemsire_adi'] ?: 'Sistem')) ?>
                                            </div>
                                            <div class="note-date">
                                                <i class="fas fa-clock"></i>
                                                <?php
                                                    $kv = $n['kayit_vakti'] ?? '';
                                                    echo $kv ? h(date('d.m.Y H:i', strtotime($kv))) : '-';
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script>
        // 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');
            });
        });

        // Note Type Selection
        document.querySelectorAll('.note-type-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                // Remove active class from all buttons
                document.querySelectorAll('.note-type-btn').forEach(b => b.classList.remove('active'));
                
                // Add active class to clicked button
                btn.classList.add('active');
                
                // Update corresponding radio button
                const type = btn.getAttribute('data-type');
                document.querySelector(`input[value="${type}"]`).checked = true;
            });
        });

        // Edit Note
        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 = 'Güncelle';
                cancelBtn.style.display = 'flex';
            } else {
                submitIcon.className = 'fas fa-save';
                submitText.textContent = 'Kaydet';
                cancelBtn.style.display = 'none';
            }
        }

        function resetHemsireForm() {
            document.getElementById('form_not_id').value = '0';
            document.getElementById('v_not').value = '';
            
            // Reset note type to General
            document.querySelectorAll('.note-type-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelector('.note-type-btn[data-type="Genel"]').classList.add('active');
            document.querySelector('input[value="Genel"]').checked = true;
            
            setEditMode(false);
        }

        // Edit Button Click
        document.querySelectorAll('[data-edit]').forEach(btn => {
            btn.addEventListener('click', () => {
                try {
                    const data = JSON.parse(btn.getAttribute('data-edit'));
                    
                    // Set form values
                    document.getElementById('form_not_id').value = data.id;
                    document.getElementById('v_not').value = data.icerik;
                    
                    // Set note type
                    document.querySelectorAll('.note-type-btn').forEach(b => b.classList.remove('active'));
                    document.querySelector(`.note-type-btn[data-type="${data.tip}"]`).classList.add('active');
                    document.querySelector(`input[value="${data.tip}"]`).checked = true;
                    
                    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('hemsireForm').scrollIntoView({ behavior: 'smooth' });
                } catch (e) {
                    console.error(e);
                    alert('Not düzenleme verisi okunamadı.');
                }
            });
        });

        // Form Validation
        const form = document.getElementById('hemsireForm');
        if (form) {
            form.addEventListener('submit', (e) => {
                const content = document.getElementById('v_not').value.trim();
                if (content.length < 10) {
                    e.preventDefault();
                    alert('Not içeriği en az 10 karakter olmalıdır.');
                    document.getElementById('v_not').focus();
                }
            });
        }

        // ESC Key to Cancel Edit
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                resetHemsireForm();
            }
        });

        // Real-time search on input
        const searchInput = document.querySelector('.search-input');
        if (searchInput) {
            let timeout;
            searchInput.addEventListener('input', () => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    searchInput.closest('form').submit();
                }, 500);
            });
        }
    </script>
</body>
</html>