<?php
require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..' . '/../');
$dotenv->safeLoad();
require_once __DIR__ . '/../i18n.php';

use App\Auth;
use App\Csrf;
use App\Database;

Auth::init();
Auth::requireRole(['admin','staff']);
$pdo = Database::getConnection();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
  http_response_code(400);
  echo 'Geçersiz hasta';
  exit;
}

// Hasta bilgisi
$st = $pdo->prepare('SELECT first_name, last_name FROM patients WHERE id = :id');
$st->execute([':id' => $id]);
$patient = $st->fetch();
if (!$patient) { echo 'Hasta bulunamadı'; exit; }

$errors = [];
$info = '';
$currentUser = Auth::user();

// Dosya yükleme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload'])) {
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    $document_type = trim($_POST['document_type'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    
    if (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
      $errors[] = 'Dosya yükleme hatası';
    } else {
      $file = $_FILES['document'];
      $originalName = basename($file['name']);
      $fileSize = $file['size'];
      $fileTmp = $file['tmp_name'];
      
      // Dosya türü kontrolü
      $allowedTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
      $finfo = finfo_open(FILEINFO_MIME_TYPE);
      $mimeType = finfo_file($finfo, $fileTmp);
      finfo_close($finfo);
      
      if (!in_array($mimeType, $allowedTypes)) {
        $errors[] = 'Desteklenmeyen dosya türü. (PDF, JPG, PNG, DOC, DOCX izinli)';
      } elseif ($fileSize > 10 * 1024 * 1024) { // 10MB limit
        $errors[] = 'Dosya çok büyük (Max: 10MB)';
      } else {
        // Güvenli dosya adı oluştur
        $ext = pathinfo($originalName, PATHINFO_EXTENSION);
        $fileName = uniqid('doc_', true) . '_' . $id . '.' . $ext;
        $uploadPath = __DIR__ . '/../uploads/documents/' . $fileName;
        
        if (move_uploaded_file($fileTmp, $uploadPath)) {
          $ins = $pdo->prepare('INSERT INTO patient_documents (patient_id, file_name, original_name, file_type, file_size, document_type, notes, uploaded_by) VALUES (:patient_id, :file_name, :original_name, :file_type, :file_size, :document_type, :notes, :uploaded_by)');
          $ins->execute([
            ':patient_id' => $id,
            ':file_name' => $fileName,
            ':original_name' => $originalName,
            ':file_type' => $mimeType,
            ':file_size' => $fileSize,
            ':document_type' => $document_type ?: null,
            ':notes' => $notes ?: null,
            ':uploaded_by' => $currentUser['id'] ?? null,
          ]);
          $info = 'Dosya başarıyla yüklendi.';
        } else {
          $errors[] = 'Dosya kaydedilemedi.';
        }
      }
    }
  }
}

// Dosya silme
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    $doc_id = (int)($_POST['doc_id'] ?? 0);
    $st = $pdo->prepare('SELECT file_name FROM patient_documents WHERE id = :id AND patient_id = :patient_id');
    $st->execute([':id' => $doc_id, ':patient_id' => $id]);
    $doc = $st->fetch();
    
    if ($doc) {
      $filePath = __DIR__ . '/../uploads/documents/' . $doc['file_name'];
      if (file_exists($filePath)) {
        unlink($filePath);
      }
      $del = $pdo->prepare('DELETE FROM patient_documents WHERE id = :id');
      $del->execute([':id' => $doc_id]);
      $info = 'Dosya silindi.';
    } else {
      $errors[] = 'Dosya bulunamadı.';
    }
  }
}

$csrf = Csrf::token();

// Belgeleri listele
$docs = $pdo->prepare('SELECT d.*, u.username AS uploaded_by_name FROM patient_documents d LEFT JOIN users u ON u.id = d.uploaded_by WHERE d.patient_id = :id ORDER BY d.created_at DESC');
$docs->execute([':id' => $id]);
$documents = $docs->fetchAll();

include __DIR__ . '/../header.php';
?>
<style>
  .container{max-width:100%;margin:0;padding:0}
  .page{padding:20px 24px;font-family:'Segoe UI','Helvetica Neue',Arial,sans-serif;background:linear-gradient(135deg,#f5f7fa 0%,#e4edf5 100%);min-height:100vh}
  .page-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px;background:#fff;padding:24px;border-radius:16px;box-shadow:0 6px 20px rgba(12,20,40,.06)}
  .page-title{display:flex;align-items:center;gap:14px}
  .page-title h1{font-weight:800;font-size:26px;color:#0f172a;margin:0}
  .page-title .icon{width:56px;height:56px;background:linear-gradient(135deg,#4361ee,#3a56d4);border-radius:14px;display:flex;align-items:center;justify-content:center;box-shadow:0 10px 25px rgba(67,97,238,.3)}
  .page-title .icon i{font-size:24px;color:#fff}
  .patient-info{font-size:14px;color:#64748b;margin-top:6px}
  .page-actions{display:flex;gap:10px;flex-wrap:wrap}
  .btn{height:40px;padding:0 20px;border-radius:10px;font-weight:600;font-size:14px;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:8px;transition:all .3s ease;text-decoration:none;box-shadow:0 2px 8px rgba(0,0,0,.05)}
  .btn:hover{transform:translateY(-2px);box-shadow:0 4px 16px rgba(0,0,0,.12)}
  .btn-outline{background:#fff;color:#4361ee;border:2px solid #e2e8f0}
  .btn-primary{background:linear-gradient(135deg,#4361ee,#3a56d4);color:#fff}
  .btn-danger{background:linear-gradient(135deg,#ef476f,#d62d54);color:#fff}
  .btn-success{background:linear-gradient(135deg,#06d6a0,#05a37a);color:#fff}
  .alert-info{background:#e0f2fe;border:2px solid #7dd3fc;color:#0c4a6e;padding:14px 18px;border-radius:10px;margin-bottom:16px;font-weight:600}
  .alert-errors{background:#fee;border:2px solid #fca5a5;color:#991b1b;padding:14px 18px;border-radius:10px;margin-bottom:16px}
  .grid{display:grid;gap:20px;margin-bottom:20px}
  .card{background:#fff;border:1px solid #e6eef6;border-radius:14px;box-shadow:0 6px 20px rgba(12,20,40,.06);padding:20px}
  .card h3{font-size:18px;font-weight:700;color:#0f172a;margin:0 0 16px 0;display:flex;align-items:center;gap:10px;padding-bottom:12px;border-bottom:2px solid #f1f5f9}
  .card h3 i{color:#4361ee}
  .form-row{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:12px}
  .form-group{margin-bottom:12px}
  .form-group label{display:block;font-size:13px;color:#334155;margin-bottom:6px;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
  .form-group input,.form-group select,.form-group textarea{width:100%;padding:12px;border:2px solid #e2e8f0;border-radius:10px;background:#fbfdff;font-size:14px;transition:all .3s ease}
  .form-group input:focus,.form-group select:focus,.form-group textarea:focus{outline:none;border-color:#4361ee;box-shadow:0 0 0 3px rgba(67,97,238,.15)}
  .form-group textarea{resize:vertical;min-height:80px}
  .form-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:16px;padding-top:16px;border-top:2px solid #f1f5f9}
  .documents-list{display:grid;gap:12px}
  .doc-item{background:linear-gradient(135deg,#f8fafc,#f1f5f9);border:2px solid #e2e8f0;border-radius:12px;padding:16px;transition:all .3s ease;display:flex;align-items:center;gap:16px}
  .doc-item:hover{border-color:#4361ee;box-shadow:0 4px 12px rgba(67,97,238,.1);transform:translateX(4px)}
  .doc-icon{width:56px;height:56px;background:linear-gradient(135deg,#4361ee,#3a56d4);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0}
  .doc-icon i{font-size:26px;color:#fff}
  .doc-info{flex:1}
  .doc-name{font-weight:700;font-size:15px;color:#0f172a;margin-bottom:6px}
  .doc-meta{font-size:13px;color:#64748b;display:flex;flex-wrap:wrap;gap:12px}
  .doc-meta span{display:flex;align-items:center;gap:4px}
  .doc-actions{display:flex;gap:8px}
  .doc-actions .btn{height:36px;padding:0 16px;font-size:13px}
  .badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.5px}
  .badge-pdf{background:rgba(239,68,68,.1);color:#dc2626;border:1px solid rgba(239,68,68,.2)}
  .badge-image{background:rgba(34,197,94,.1);color:#16a34a;border:1px solid rgba(34,197,94,.2)}
  .badge-doc{background:rgba(59,130,246,.1);color:#2563eb;border:1px solid rgba(59,130,246,.2)}
  .empty-state{text-align:center;padding:60px 20px;color:#94a3b8}
  .empty-state i{font-size:64px;margin-bottom:16px;opacity:.5}
  .empty-state p{font-size:16px}
  @media (max-width:768px){
    .form-row{grid-template-columns:1fr}
    .doc-item{flex-direction:column;text-align:center}
    .doc-actions{width:100%;justify-content:center}
    .page-head{flex-direction:column;align-items:flex-start}
    .page-actions{width:100%}
  }
</style>

<div class="page">
  <div class="page-head">
    <div class="page-title">
      <div class="icon"><i class="bi bi-file-earmark-medical"></i></div>
      <div>
        <h1>Hasta Belgeleri</h1>
        <div class="patient-info">
          <i class="bi bi-person-fill"></i> <?= htmlspecialchars($patient['first_name'] . ' ' . $patient['last_name']) ?>
          <span style="margin:0 8px">•</span>
          <i class="bi bi-files"></i> <?= count($documents) ?> Belge
        </div>
      </div>
    </div>
    <div class="page-actions">
      <a href="/HastaModulu/hastaListe.php" class="btn btn-outline"><i class="bi bi-card-checklist"></i> Liste</a>
      <a href="/HastaModulu/hastaDetay.php?id=<?= $id ?>" class="btn btn-outline"><i class="bi bi-card-text"></i> Detay</a>
      <a href="/HastaModulu/hastaDuzenle.php?id=<?= $id ?>" class="btn btn-outline"><i class="bi bi-pencil-square"></i> Düzenle</a>
    </div>
  </div>

  <?php if($info): ?><div class="alert-info"><i class="bi bi-check-circle"></i> <?= htmlspecialchars($info) ?></div><?php endif; ?>
  <?php if($errors): ?><div class="alert-errors"><?php foreach($errors as $e) echo '<div><i class="bi bi-x-circle"></i> '.htmlspecialchars($e).'</div>'; ?></div><?php endif; ?>

  <div class="grid">
    <!-- Dosya Yükleme Formu -->
    <div class="card">
      <h3><i class="bi bi-cloud-upload"></i> Yeni Belge Yükle</h3>
      <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
        
        <div class="form-row">
          <div class="form-group">
            <label>Belge Türü</label>
            <select name="document_type">
              <option value="">Seçiniz</option>
              <option value="Onam Formu">Onam Formu</option>
              <option value="Tetkik Sonucu">Tetkik Sonucu</option>
              <option value="Rapor">Rapor</option>
              <option value="Reçete">Reçete</option>
              <option value="Görüntüleme">Görüntüleme (Röntgen, MR, vb.)</option>
              <option value="Laboratuvar">Laboratuvar Sonucu</option>
              <option value="Kimlik">Kimlik Belgesi</option>
              <option value="Diğer">Diğer</option>
            </select>
          </div>
          
          <div class="form-group">
            <label>Dosya Seç (PDF, JPG, PNG, DOC, DOCX - Max 10MB)</label>
            <input type="file" name="document" required accept=".pdf,.jpg,.jpeg,.png,.doc,.docx">
          </div>
        </div>
        
        <div class="form-group">
          <label>Notlar (Opsiyonel)</label>
          <textarea name="notes" placeholder="Belge hakkında ek bilgiler..."></textarea>
        </div>
        
        <div class="form-actions">
          <button type="submit" name="upload" class="btn btn-success">
            <i class="bi bi-upload"></i> Dosyayı Yükle
          </button>
        </div>
      </form>
    </div>

    <!-- Belgeler Listesi -->
    <div class="card">
      <h3><i class="bi bi-files"></i> Yüklenmiş Belgeler</h3>
      
      <?php if(!$documents): ?>
        <div class="empty-state">
          <i class="bi bi-inbox"></i>
          <p>Henüz yüklenmiş belge bulunmuyor.</p>
        </div>
      <?php else: ?>
        <div class="documents-list">
          <?php foreach($documents as $doc): 
            // Dosya uzantısından badge belirleme
            $ext = strtolower(pathinfo($doc['original_name'], PATHINFO_EXTENSION));
            $badgeClass = 'badge-doc';
            $iconClass = 'bi-file-earmark';
            if ($ext === 'pdf') {
              $badgeClass = 'badge-pdf';
              $iconClass = 'bi-file-earmark-pdf';
            } elseif (in_array($ext, ['jpg','jpeg','png'])) {
              $badgeClass = 'badge-image';
              $iconClass = 'bi-file-earmark-image';
            }
            
            $fileSize = round($doc['file_size'] / 1024, 1) . ' KB';
            if ($doc['file_size'] > 1024*1024) {
              $fileSize = round($doc['file_size'] / (1024*1024), 2) . ' MB';
            }
          ?>
            <div class="doc-item">
              <div class="doc-icon">
                <i class="bi <?= $iconClass ?>"></i>
              </div>
              <div class="doc-info">
                <div class="doc-name">
                  <?= htmlspecialchars($doc['original_name']) ?>
                  <?php if($doc['document_type']): ?>
                    <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($doc['document_type']) ?></span>
                  <?php endif; ?>
                </div>
                <div class="doc-meta">
                  <span><i class="bi bi-hdd"></i> <?= $fileSize ?></span>
                  <span><i class="bi bi-calendar"></i> <?= date('d.m.Y H:i', strtotime($doc['created_at'])) ?></span>
                  <?php if($doc['uploaded_by_name']): ?>
                    <span><i class="bi bi-person"></i> <?= htmlspecialchars($doc['uploaded_by_name']) ?></span>
                  <?php endif; ?>
                </div>
                <?php if($doc['notes']): ?>
                  <div style="margin-top:8px;font-size:13px;color:#64748b;font-style:italic">
                    <i class="bi bi-chat-left-text"></i> <?= htmlspecialchars($doc['notes']) ?>
                  </div>
                <?php endif; ?>
              </div>
              <div class="doc-actions">
                <a href="/HastaModulu/downloadDocument.php?id=<?= (int)$doc['id'] ?>" class="btn btn-primary" target="_blank">
                  <i class="bi bi-download"></i> İndir
                </a>
                <form method="post" style="display:inline" onsubmit="return confirm('Bu dosyayı silmek istediğinize emin misiniz?')">
                  <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                  <input type="hidden" name="doc_id" value="<?= (int)$doc['id'] ?>">
                  <button type="submit" name="delete" class="btn btn-danger">
                    <i class="bi bi-trash"></i> Sil
                  </button>
                </form>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../footer.php'; ?>
