<?php
/**
 * NEPHRO ERP - Doküman & Onam Yönetimi (Refactor v2 - Layout+Size)
 * - Arama (datalist) efsane
 * - Listeye Dön butonu hizalı
 * - Upload hint satırı kaldırıldı
 * - Hasta doküman toplam boyutu + arşiv toplam boyutu eklendi
 */
global $pdo;

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

$hid = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

/** doküman ikon */
function docIcon($path) {
    $ext = strtolower(pathinfo((string)$path, PATHINFO_EXTENSION));
    return match ($ext) {
        'pdf' => ['fas fa-file-pdf', '#ef4444'],
        'jpg', 'jpeg', 'png', 'webp' => ['fas fa-file-image', '#10b981'],
        'doc', 'docx' => ['fas fa-file-word', '#2563eb'],
        'xls', 'xlsx' => ['fas fa-file-excel', '#16a34a'],
        default => ['fas fa-file', '#64748b'],
    };
}

/** bytes format */
function fmtBytes(int $bytes): string {
    if ($bytes <= 0) return '0 B';
    $units = ['B','KB','MB','GB','TB'];
    $i = (int)floor(log($bytes, 1024));
    $i = max(0, min($i, count($units)-1));
    $v = $bytes / (1024 ** $i);
    return rtrim(rtrim(number_format($v, 2, '.', ''), '0'), '.') . ' ' . $units[$i];
}

/** güvenli path -> fs path */
function toFsPath(string $relOrUrlPath): ?string {
    $p = trim($relOrUrlPath);
    if ($p === '') return null;

    // sadece uploads altına izin ver (path traversal riskini azalt)
    // örn: uploads/hasta_dokumanlar/abc.pdf
    $pNorm = str_replace('\\','/',$p);
    if (!str_starts_with($pNorm, 'uploads/')) return null;

    $docRoot = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
    if ($docRoot === '') return null;

    $full = $docRoot . '/' . ltrim($pNorm, '/');
    $real = realpath($full);
    if (!$real) return null;

    // docRoot içinde mi?
    if (!str_starts_with(str_replace('\\','/',$real), str_replace('\\','/',$docRoot.'/'))) return null;

    return $real;
}

/** klasör boyutu (rekürsif) */
function folderSize(string $absDir): int {
    if (!is_dir($absDir)) return 0;
    $size = 0;

    $it = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($absDir, FilesystemIterator::SKIP_DOTS)
    );

    foreach ($it as $file) {
        /** @var SplFileInfo $file */
        if ($file->isFile()) $size += (int)$file->getSize();
    }
    return $size;
}

/* --- data --- */

// Hasta listesi
$hastalar = $pdo->query("SELECT id, ad, soyad, tc_no, telefon, durum FROM hastalar ORDER BY ad ASC, soyad ASC")
                ->fetchAll(PDO::FETCH_ASSOC);

// Seçili hasta
$hasta = null;
if ($hid > 0) {
    $h = $pdo->prepare("SELECT * FROM hastalar WHERE id = ? LIMIT 1");
    $h->execute([$hid]);
    $hasta = $h->fetch(PDO::FETCH_ASSOC);
}

// Arşiv toplam boyutu (sunucuda)
$archiveDirRel = 'uploads/hasta_dokumanlar'; // burası farklıysa değiştir
$archiveFs = toFsPath($archiveDirRel . '/dummy.txt'); // toFsPath sadece uploads/... ister; dosya yoksa null döner
// yukarıdaki trick yerine dir'i kendimiz oluşturuyoruz:
$docRoot = rtrim((string)($_SERVER['DOCUMENT_ROOT'] ?? ''), '/');
$archiveAbs = ($docRoot !== '') ? ($docRoot . '/' . trim($archiveDirRel, '/')) : '';
$archiveTotalBytes = ($archiveAbs && is_dir($archiveAbs)) ? folderSize($archiveAbs) : 0;

$docs = [];
$docCount = 0;
$patientTotalBytes = 0;
$initials = 'H';

if ($hasta) {
    $docsStmt = $pdo->prepare("SELECT * FROM hasta_dokumanlar WHERE hasta_id = ? ORDER BY id DESC");
    $docsStmt->execute([$hid]);
    $docs = $docsStmt->fetchAll(PDO::FETCH_ASSOC);
    $docCount = count($docs);

    // Baş harfler
    $ad = (string)($hasta['ad'] ?? '');
    $soyad = (string)($hasta['soyad'] ?? '');
    $initials = mb_strtoupper(mb_substr($ad, 0, 1, 'UTF-8') . mb_substr($soyad, 0, 1, 'UTF-8'), 'UTF-8');
    if ($initials === '') $initials = 'H';

    // Hasta doküman toplam boyutu
    $seen = [];
    foreach ($docs as $d) {
        $path = (string)($d['dokuman_yolu'] ?? '');
        if ($path === '' || isset($seen[$path])) continue;
        $seen[$path] = true;

        $fs = toFsPath($path);
        if ($fs && is_file($fs)) $patientTotalBytes += (int)filesize($fs);
    }
}
?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Doküman Yönetimi - NEPHRO ERP</title>

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <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{
            --primary:#2563eb; --primary-100:#dbeafe; --primary-700:#1d4ed8;
            --danger:#dc2626; --danger-100:#fee2e2;
            --bg:#f6f8fc; --card:#fff; --border:#e6edf7;
            --text:#0f172a; --muted:#64748b; --muted2:#94a3b8;
            --shadow:0 10px 18px -8px rgba(2,6,23,.12);
            --radius:16px; --radius-sm:12px;
            --t:.18s ease;
        }
        *{box-sizing:border-box;margin:0;padding:0}
        body{font-family:Inter,system-ui,-apple-system,Segoe UI,sans-serif;background:var(--bg);color:var(--text);line-height:1.5}
        .container{max-width:1200px;margin:0 auto;padding:22px;min-height:100vh}

        .page-header{margin-bottom:18px}
        .page-header h1{font-size:28px;letter-spacing:-.03em}
        .page-header p{color:var(--muted);margin-top:6px;font-size:15px}

        .card{
            background:var(--card);
            border:1px solid var(--border);
            border-radius:var(--radius);
            padding:18px;
            box-shadow:0 1px 2px rgba(2,6,23,.04);
        }

        /* Top bar: daha derli toplu */
        .topbar{
            display:grid;
            grid-template-columns: 1fr 420px;
            gap:14px;
            align-items:center;
        }
        .field{position:relative}
        .field i{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:var(--muted2)}
        .input{
            width:100%;
            padding:12px 14px 12px 42px;
            border:1px solid var(--border);
            border-radius:var(--radius-sm);
            font-size:15px;background:#fff;
            transition:var(--t);
        }
        .input:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.10)}

        .rightbox{
            display:flex;
            gap:10px;
            align-items:center;
        }
        .select{
            flex:1;
            width:100%;
            padding:12px 14px;
            border:1px solid var(--border);
            border-radius:var(--radius-sm);
            font-size:15px;background:#fff;
            transition:var(--t);
        }
        .select:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.10)}

        .btn{
            display:inline-flex;align-items:center;gap:8px;
            padding:11px 14px;border-radius:12px;
            font-weight:700;font-size:14px;text-decoration:none;
            border:1px solid transparent; cursor:pointer; transition:var(--t);
            background:#fff;color:var(--text);
            white-space:nowrap;
        }
        .btn-outline{border-color:var(--border)}
        .btn-outline:hover{border-color:rgba(37,99,235,.35);background:#f3f6ff}
        .btn-primary{background:var(--primary);color:#fff}
        .btn-primary:hover{background:var(--primary-700);transform:translateY(-1px);box-shadow:var(--shadow)}

        /* Patient info */
        .patient-info{
            margin-top:16px;
            display:grid;
            grid-template-columns:auto 1fr auto;
            gap:16px;
            align-items:center;
        }
        .avatar{
            width:58px;height:58px;border-radius:16px;
            background:var(--primary-100);color:var(--primary);
            display:flex;align-items:center;justify-content:center;
            font-weight:900;font-size:18px;
        }
        .pname{font-size:18px;font-weight:800;letter-spacing:-.01em}
        .chips{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
        .chip{
            display:inline-flex;align-items:center;gap:8px;
            padding:7px 12px;border-radius:999px;
            background:#f7faff;border:1px solid var(--border);
            font-size:13px;font-weight:800;color:var(--text);
        }
        .chip small{font-weight:800;color:var(--muted)}
        .count{text-align:right}
        .count .val{font-size:22px;font-weight:900;color:var(--primary)}
        .count .lbl{color:var(--muted);margin-top:3px}

        /* Sections */
        .section-title{display:flex;align-items:center;gap:10px;font-size:18px;font-weight:900;margin-bottom:8px}
        .section-sub{color:var(--muted);font-size:14px;margin-bottom:14px}

        /* Upload form */
        .formgrid{
            display:grid;
            grid-template-columns: 1fr 1fr 220px;
            gap:14px;
            align-items:end;
        }
        .label{font-size:12px;font-weight:900;color:var(--muted);text-transform:uppercase;letter-spacing:.06em;margin-bottom:6px}
        .input2{
            width:100%;
            padding:12px 14px;
            border:1px solid var(--border);
            border-radius:var(--radius-sm);
            font-size:15px;
        }
        .input2:focus{outline:none;border-color:var(--primary);box-shadow:0 0 0 3px rgba(37,99,235,.10)}

        /* Custom file picker (çirkin default görünümü toparlar) */
        .filewrap{
            display:flex;gap:10px;align-items:center;
            border:1px solid var(--border);
            border-radius:var(--radius-sm);
            padding:10px;
            background:#fff;
        }
        .filewrap input[type="file"]{display:none}
        .filebtn{
            display:inline-flex;align-items:center;gap:8px;
            padding:10px 12px;border-radius:12px;
            background:#f3f6ff;border:1px solid rgba(37,99,235,.25);
            font-weight:900;cursor:pointer;transition:var(--t);
            color:var(--primary);
            white-space:nowrap;
        }
        .filebtn:hover{background:var(--primary);color:#fff;border-color:var(--primary)}
        .filename{
            flex:1;
            color:var(--muted);
            font-weight:700;
            overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
        }

        /* Archive */
        .archive-head{
            display:flex;gap:12px;flex-wrap:wrap;align-items:center;justify-content:space-between;
            padding-bottom:12px;margin-bottom:12px;border-bottom:1px solid var(--border);
        }
        .archive-search{min-width:240px;flex:1;max-width:380px}
        .pill{
            display:inline-flex;align-items:center;gap:8px;
            padding:9px 12px;border-radius:999px;
            background:#f7faff;border:1px solid var(--border);
            color:var(--muted);font-weight:900;
        }

        .grid{
            display:grid;
            grid-template-columns:repeat(auto-fill,minmax(280px,1fr));
            gap:14px;
        }
        .doc{
            border:1px solid var(--border);
            border-radius:var(--radius);
            padding:16px;
            background:#fff;
            transition:var(--t);
            display:flex;flex-direction:column;gap:12px;
        }
        .doc:hover{border-color:rgba(37,99,235,.45);box-shadow:var(--shadow);transform:translateY(-2px)}
        .doc-top{display:flex;gap:12px;align-items:center}
        .dicon{
            width:46px;height:46px;border-radius:16px;
            display:flex;align-items:center;justify-content:center;
            font-size:20px; flex-shrink:0;
        }
        .dtitle{font-weight:900;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .dmeta{font-size:12px;color:var(--muted2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px}
        .actions{display:flex;gap:8px;margin-top:2px}
        .abtn{
            flex:1;display:inline-flex;align-items:center;justify-content:center;gap:8px;
            padding:11px;border-radius:12px;font-weight:900;font-size:13px;
            border:1px solid transparent; cursor:pointer; transition:var(--t); text-decoration:none;
        }
        .abtn-view{background:var(--primary-100);color:var(--primary)}
        .abtn-view:hover{background:var(--primary);color:#fff}
        .abtn-del{background:var(--danger-100);color:var(--danger);border-color:rgba(220,38,38,.2)}
        .abtn-del:hover{background:var(--danger);color:#fff}

        .empty{padding:46px 16px;text-align:center}
        .empty i{font-size:46px;color:#cbd5e1;margin-bottom:14px}
        .empty h3{font-size:18px;font-weight:900}
        .empty p{color:var(--muted);max-width:420px;margin:8px auto 0}

        @media(max-width:980px){
            .topbar{grid-template-columns:1fr}
            .rightbox{width:100%}
            .formgrid{grid-template-columns:1fr}
            .patient-info{grid-template-columns:1fr;text-align:center}
            .count{text-align:center}
        }
    </style>
</head>
<body>
<div class="container">

    <div class="page-header">
        <h1>Doküman ve Onam Yönetimi</h1>
        <p>Hasta dokümanlarını yükle, görüntüle ve arşivle.</p>
    </div>

    <!-- Hasta Seçimi -->
    <div class="card">
        <div class="topbar">
            <div class="field">
                <i class="fas fa-search"></i>
                <input class="input" list="hastaList" id="hastaSearch" placeholder="Hasta ara (ad, soyad, TC)...">
                <datalist id="hastaList">
                    <?php foreach($hastalar as $r): ?>
                        <option value="<?= h($r['ad'].' '.$r['soyad'].' ('.$r['tc_no'].')') ?>" data-id="<?= (int)$r['id'] ?>"></option>
                    <?php endforeach; ?>
                </datalist>
            </div>

            <div class="rightbox">
                <select class="select" id="hastaSelect">
                    <option value="">Hasta seçiniz</option>
                    <?php foreach($hastalar as $r): ?>
                        <option value="<?= (int)$r['id'] ?>" <?= $hid == (int)$r['id'] ? 'selected' : '' ?>>
                            <?= h($r['ad'].' '.$r['soyad'].' ('.$r['tc_no'].')') ?>
                        </option>
                    <?php endforeach; ?>
                </select>

                <a class="btn btn-outline" href="?sayfa=hasta-liste">
                    <i class="fas fa-arrow-left"></i> Listeye Dön
                </a>
            </div>
        </div>
    </div>

    <?php if($hasta): ?>
        <!-- Hasta Bilgisi -->
        <div class="card" style="margin-top:16px">
            <div class="patient-info">
                <div class="avatar"><?= h($initials) ?></div>

                <div>
                    <div class="pname"><?= h(mb_strtoupper(($hasta['ad'] ?? '').' '.($hasta['soyad'] ?? ''), 'UTF-8')) ?></div>
                    <div class="chips">
                        <span class="chip"><i class="fas fa-id-card"></i> <small>TC</small> <?= h($hasta['tc_no'] ?? '') ?></span>

                        <?php if(!empty($hasta['durum'])): ?>
                            <span class="chip"><i class="fas fa-circle-info"></i> <small>Durum</small> <?= h($hasta['durum']) ?></span>
                        <?php endif; ?>

                        <span class="chip"><i class="fas fa-database"></i> <small>Hasta Boyutu</small> <?= h(fmtBytes($patientTotalBytes)) ?></span>

                        <span class="chip"><i class="fas fa-server"></i> <small>Arşiv Boyutu</small> <?= h(fmtBytes($archiveTotalBytes)) ?></span>
                    </div>
                </div>

                <div class="count">
                    <div class="val"><?= (int)$docCount ?></div>
                    <div class="lbl">Toplam Doküman</div>
                </div>
            </div>
        </div>

        <!-- Upload -->
        <div class="card" style="margin-top:16px">
            <div class="section-title"><i class="fas fa-cloud-upload-alt"></i> Yeni Doküman Yükle</div>
            <div class="section-sub">Doküman adını gir, dosyanı seç, yükle. (Bitti gitti.)</div>

            <form action="islem.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="hasta_id" value="<?= (int)$hid ?>">

                <div class="formgrid">
                    <div>
                        <div class="label">Doküman Adı</div>
                        <input class="input2" type="text" name="d_adi" placeholder="Örn: 2025 Onam Formu" required>
                    </div>

                    <div>
                        <div class="label">Dosya</div>

                        <div class="filewrap">
                            <input id="dosyaInput" type="file" name="dosya" required>
                            <label class="filebtn" for="dosyaInput"><i class="fas fa-paperclip"></i> Dosya Seç</label>
                            <div class="filename" id="dosyaName">Dosya seçilmedi</div>
                        </div>

                        <!-- İSTEDİĞİN GİBİ: PDF/JPG/PNG... HINT SATIRI KALKTI ✅ -->
                    </div>

                    <div>
                        <button class="btn btn-primary" type="submit" name="dokuman_yukle" style="width:100%;justify-content:center">
                            <i class="fas fa-upload"></i> Yükle
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Archive -->
        <div class="card" style="margin-top:16px">
            <div class="archive-head">
                <div class="section-title" style="margin:0"><i class="fas fa-folder-open"></i> Doküman Arşivi</div>

                <div class="archive-search field">
                    <i class="fas fa-search"></i>
                    <input class="input" id="docSearch" placeholder="Doküman adı ile ara..." style="padding-left:42px">
                </div>

                <div class="pill"><i class="fas fa-hashtag"></i> <?= (int)$docCount ?> kayıt</div>
                <div class="pill"><i class="fas fa-weight-hanging"></i> <?= h(fmtBytes($patientTotalBytes)) ?></div>
            </div>

            <?php if($docCount === 0): ?>
                <div class="empty">
                    <i class="fas fa-folder-plus"></i>
                    <h3>Henüz doküman yok</h3>
                    <p>Bu hastaya ait doküman bulunamadı. İlk dokümanı yukarıdan yükleyebilirsin.</p>
                </div>
            <?php else: ?>
                <div class="grid" id="docsGrid">
                    <?php foreach($docs as $doc):
                        $path = (string)($doc['dokuman_yolu'] ?? '');
                        [$icon,$color] = docIcon($path);
                        $filename = basename($path ?: '');
                        $dadi = (string)($doc['dokuman_adi'] ?? '');
                        $dtarih = (string)($doc['yukleme_tarihi'] ?? '');
                    ?>
                        <div class="doc" data-name="<?= h(mb_strtolower($dadi, 'UTF-8')) ?>">
                            <div class="doc-top">
                                <div class="dicon" style="background: <?= h($color) ?>20; color: <?= h($color) ?>;">
                                    <i class="<?= h($icon) ?>"></i>
                                </div>
                                <div style="min-width:0;flex:1">
                                    <div class="dtitle" title="<?= h($dadi) ?>"><?= h($dadi) ?></div>
                                    <div class="dmeta" title="<?= h($filename) ?>"><?= h($filename) ?></div>
                                </div>
                            </div>

                            <div class="actions">
                                <a class="abtn abtn-view" href="<?= h($path) ?>" target="_blank">
                                    <i class="fas fa-eye"></i> Görüntüle
                                </a>

                                <form action="islem.php" method="POST" style="flex:1;margin:0"
                                      onsubmit="return confirm('Bu doküman silinsin mi?');">
                                    <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
                                    <input type="hidden" name="hasta_id" value="<?= (int)$hid ?>">
                                    <button class="abtn abtn-del" type="submit" name="dokuman_sil">
                                        <i class="fas fa-trash"></i> Sil
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <div class="empty" id="noDocFound" style="display:none;padding:30px 16px">
                    <i class="fas fa-magnifying-glass"></i>
                    <h3>Eşleşen doküman yok</h3>
                    <p>Arama kelimesini değiştirerek tekrar deneyebilirsin.</p>
                </div>
            <?php endif; ?>
        </div>

    <?php else: ?>
        <div class="card" style="margin-top:16px">
            <div class="empty">
                <i class="fas fa-user-injured"></i>
                <h3>Hasta seçilmedi</h3>
                <p>Yukarıdan bir hasta seç, sonra doküman yükleme ve arşiv kısmı burada görünsün.</p>
            </div>
        </div>
    <?php endif; ?>

</div>

<script>
    // Select ile yönlendir
    const hastaSelect = document.getElementById('hastaSelect');
    if (hastaSelect) {
        hastaSelect.addEventListener('change', () => {
            const id = hastaSelect.value;
            if (!id) return;
            window.location.href = '?sayfa=hasta-onam&id=' + encodeURIComponent(id);
        });
    }

    // Datalist arama
    const hastaSearch = document.getElementById('hastaSearch');
    const hastaList = document.getElementById('hastaList');
    if (hastaSearch && hastaList) {
        hastaSearch.addEventListener('change', () => {
            const val = hastaSearch.value.trim();
            if (!val) return;
            const opts = hastaList.querySelectorAll('option');
            for (const o of opts) {
                if (o.value === val) {
                    const id = o.getAttribute('data-id');
                    if (id) window.location.href = '?sayfa=hasta-onam&id=' + encodeURIComponent(id);
                    return;
                }
            }
        });
    }

    // Doküman arama
    const docSearch = document.getElementById('docSearch');
    const docsGrid = document.getElementById('docsGrid');
    const noDocFound = document.getElementById('noDocFound');

    if (docSearch && docsGrid) {
        docSearch.addEventListener('input', () => {
            const q = docSearch.value.toLowerCase().trim();
            let shown = 0;
            docsGrid.querySelectorAll('.doc').forEach(card => {
                const name = (card.getAttribute('data-name') || '');
                const ok = name.includes(q);
                card.style.display = ok ? '' : 'none';
                if (ok) shown++;
            });
            if (noDocFound) noDocFound.style.display = (shown === 0) ? '' : 'none';
        });
    }

    // Custom file name
    const fileInput = document.getElementById('dosyaInput');
    const fileName  = document.getElementById('dosyaName');
    if (fileInput && fileName) {
        fileInput.addEventListener('change', () => {
            const f = fileInput.files && fileInput.files[0] ? fileInput.files[0].name : 'Dosya seçilmedi';
            fileName.textContent = f;
        });
    }

    // ESC temizle
    document.addEventListener('keydown', (e) => {
        if (e.key !== 'Escape') return;
        if (docSearch && document.activeElement === docSearch) {
            docSearch.value = '';
            docSearch.dispatchEvent(new Event('input'));
        }
        if (hastaSearch && document.activeElement === hastaSearch) {
            hastaSearch.value = '';
        }
    });
</script>
</body>
</html>
