<?php
/**
 * NEPHRO ERP - TANIMLAR (v33.3 - Sync)
 */
global $pdo;

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

// UI Konfigürasyonu - islem.php ile BİREBİR AYNI OLMALI
$TANIM_UI = [
  'kurumlar' => [
    'title' => 'Kurumlar',
    'table' => 'kurumlar',
    'fields' => [
      ['name'=>'kurum_adi','label'=>'Kurum Adı','type'=>'text','required'=>true],
      ['name'=>'kurum_tipi','label'=>'Kurum Tipi','type'=>'select','required'=>true,'options'=>['SGK','Özel','Diğer']],
    ],
    'list_cols' => [
      ['col'=>'kurum_adi','label'=>'Kurum'],
      ['col'=>'kurum_tipi','label'=>'Tip'],
    ],
  ],
  'sgk_tipleri' => [
    'title' => 'SGK Tipleri',
    'table' => 'sgk_tipleri',
    'fields' => [
      ['name'=>'ad','label'=>'SGK Tipi','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
  'hepatit_tanimlari' => [
    'title' => 'Hepatit Tanımları',
    'table' => 'hepatit_tanimlari',
    'fields' => [
      ['name'=>'ad','label'=>'Tanım','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
  'damar_yolu_tanimlari' => [
    'title' => 'Damar Yolu Tanımları',
    'table' => 'damar_yolu_tanimlari',
    'fields' => [
      ['name'=>'ad','label'=>'Tanım','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
  'alerji_tanimlari' => [
    'title' => 'Alerji Tanımları',
    'table' => 'alerji_tanimlari',
    'fields' => [
      ['name'=>'ad','label'=>'Tanım','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
  'kronik_hastalik_tanimlari' => [
    'title' => 'Kronik Hastalık Tanımları',
    'table' => 'kronik_hastalik_tanimlari',
    'fields' => [
      ['name'=>'ad','label'=>'Tanım','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
  'risk_uyari_tanimlari' => [
    'title' => 'Risk Uyarı Tanımları',
    'table' => 'risk_uyari_tanimlari',
    'fields' => [
      ['name'=>'ad','label'=>'Tanım','type'=>'text','required'=>true],
    ],
    'list_cols' => [['col'=>'ad','label'=>'Ad']],
  ],
];

$data = [];
foreach ($TANIM_UI as $key=>$cfg) {
  $stmt = $pdo->query("SELECT * FROM {$cfg['table']} ORDER BY id DESC");
  $data[$key] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$durum = $_GET['durum'] ?? '';
$toast = [
  'eklendi' => ['ok','Kayıt eklendi.'],
  'guncellendi' => ['ok','Kayıt güncellendi.'],
  'silindi' => ['ok','Kayıt silindi.'],
  'hata' => ['err','İşlem sırasında hata oluştu.'],
];
?>
<style>
  :root{ --bg:#f6f8fc; --card:#ffffff; --line:#e7edf7; --text:#0f172a; --muted:#64748b; --primary:#2f5bff; --danger:#e11d48; --r:18px; }
  .tanim-wrap{max-width:1200px;margin:0 auto; padding:20px;}
  .tanim-header{display:flex;align-items:flex-end;justify-content:space-between;gap:16px;margin-bottom:20px;}
  .tanim-header h2{margin:0;font-weight:900;color:var(--text); font-size:1.8rem;}
  .tanim-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;}
  @media (max-width: 980px){ .tanim-grid{grid-template-columns:1fr;} }
  .box{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:20px; box-shadow:0 4px 6px -1px rgba(0,0,0,0.05);}
  .box-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px; border-bottom:1px solid var(--line); padding-bottom:10px;}
  .box-title{font-weight:900;color:var(--text);font-size:1.1rem;margin:0;}
  .pill{background:rgba(47,91,255,.10);color:var(--primary);font-weight:900;border-radius:999px;padding:4px 12px;font-size:.8rem;}
  .form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
  .form-row.one{grid-template-columns:1fr;}
  .field label{display:block;font-size:.75rem;color:var(--muted);font-weight:800;margin-bottom:5px; text-transform:uppercase;}
  .inp, .sel{ width:100%; padding:12px; border:1px solid var(--line); border-radius:12px; outline:none; font-weight:700; color:var(--text); background:#fdfeff; transition:0.2s;}
  .inp:focus, .sel:focus{border-color:var(--primary); box-shadow:0 0 0 3px rgba(47,91,255,.1);}
  .actions{display:flex;gap:10px;margin-top:15px;}
  .btn{ border:1px solid transparent; border-radius:12px; padding:10px 16px; font-weight:800; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; gap:8px; transition:0.2s;}
  .btn-primary{background:var(--primary);color:#fff;}
  .btn-soft{background:#f0f4ff;color:var(--primary);border-color:#dbe5ff;}
  .btn-danger{background:#fff1f2;color:var(--danger);border-color:#ffd1da;}
  .btn:hover{filter:brightness(0.95); transform:translateY(-1px);}
  .list{margin-top:20px; display:flex; flex-direction:column; gap:12px;}
  .rowitem{border:1px solid var(--line);border-radius:16px;padding:15px;background:#fff; transition:0.3s;}
  .rowitem.editing{border-color:var(--primary); background:#fafbff;}
  .meta{display:flex;gap:20px;flex:1;}
  .meta b{font-size:0.95rem;}
  .edit-area{margin-top:15px; display:none; border-top:1px dashed var(--line); padding-top:15px;}
  .rowitem.editing .edit-area{display:block;}
  .toast{ border-radius:12px;padding:12px 16px;margin-bottom:20px; border:1px solid var(--line); font-weight:700;}
  .toast.ok{background:#f0fdf4; color:#166534; border-color:#bbf7d0;}
</style>

<div class="tanim-wrap">
  <div class="tanim-header">
    <div>
      <h2>Tanımlar</h2>
      <p style="color:var(--muted); font-weight:600;">Hasta kartı ve sistem seçeneklerini yönetin.</p>
    </div>
    <a class="btn btn-soft" href="index.php?sayfa=ayarlar">← Ayarlara Dön</a>
  </div>

  <?php if (isset($toast[$durum])): [$cls,$txt] = $toast[$durum]; ?>
    <div class="toast <?=h($cls)?>"><?=h($txt)?></div>
  <?php endif; ?>

  <div class="tanim-grid">
    <?php foreach($TANIM_UI as $key=>$cfg): ?>
      <div class="box" id="<?=h($key)?>">
        <div class="box-top">
          <p class="box-title"><?=h($cfg['title'])?></p>
          <span class="pill"><?=count($data[$key])?> Kayıt</span>
        </div>

        <form method="post" action="islem.php" autocomplete="off">
          <input type="hidden" name="tanim_ekle" value="1">
          <input type="hidden" name="tanim_key" value="<?=h($key)?>">
          <div class="form-row <?= (count($cfg['fields'])>1) ? '' : 'one' ?>">
            <?php foreach($cfg['fields'] as $f): ?>
              <div class="field">
                <label><?=h($f['label'])?></label>
                <?php if(($f['type'] ?? 'text') === 'select'): ?>
                  <select class="sel" name="<?=h($f['name'])?>" <?=!empty($f['required'])?'required':''?>>
                    <?php foreach(($f['options'] ?? []) as $opt): ?>
                      <option value="<?=h($opt)?>"><?=h($opt)?></option>
                    <?php endforeach; ?>
                  </select>
                <?php else: ?>
                  <input class="inp" type="text" name="<?=h($f['name'])?>" placeholder="<?=h($f['label'])?> giriniz..." <?=!empty($f['required'])?'required':''?>>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>
          <div class="actions">
            <button class="btn btn-primary" type="submit"><b>+</b> Yeni Ekle</button>
          </div>
        </form>

        <div class="list">
          <?php if(empty($data[$key])): ?>
            <div style="text-align:center; padding:20px; color:var(--muted); font-style:italic; font-size:0.9rem;">Henüz veri girişi yapılmamış.</div>
          <?php else: ?>
            <?php foreach($data[$key] as $row): $rid=(int)$row['id']; ?>
              <div class="rowitem" data-row="<?=h($key)?>-<?= $rid ?>">
                <div style="display:flex; justify-content:space-between; align-items:center;">
                  <div class="meta">
                    <?php foreach($cfg['list_cols'] as $lc): ?>
                      <div>
                        <small style="display:block; font-size:0.7rem; color:var(--muted);"><?=h($lc['label'])?></small>
                        <b><?=h($row[$lc['col']] ?? '')?></b>
                      </div>
                    <?php endforeach; ?>
                  </div>
                  <div style="display:flex; gap:8px;">
                    <button class="btn btn-soft" type="button" onclick="toggleEdit('<?=h($key)?>-<?= $rid ?>')" style="padding:6px 12px; font-size:0.8rem;">Düzenle</button>
                    <a class="btn btn-danger" href="islem.php?islem=tanim_sil&key=<?=urlencode($key)?>&id=<?=$rid?>" 
                       onclick="return confirm('Bu tanım silinecektir, onaylıyor musunuz?');" style="padding:6px 12px; font-size:0.8rem;">Sil</a>
                  </div>
                </div>

                <div class="edit-area" id="edit-<?=h($key)?>-<?= $rid ?>">
                  <form method="post" action="islem.php" autocomplete="off">
                    <input type="hidden" name="tanim_guncelle" value="1">
                    <input type="hidden" name="tanim_key" value="<?=h($key)?>">
                    <input type="hidden" name="id" value="<?=$rid?>">
                    <div class="form-row <?= (count($cfg['fields'])>1) ? '' : 'one' ?>">
                      <?php foreach($cfg['fields'] as $f): $fname = $f['name']; ?>
                        <div class="field">
                          <label><?=h($f['label'])?></label>
                          <?php if(($f['type'] ?? 'text') === 'select'): ?>
                            <select class="sel" name="<?=h($fname)?>" required>
                              <?php foreach(($f['options'] ?? []) as $opt): ?>
                                <option value="<?=h($opt)?>" <?= (($row[$fname] ?? '')===$opt ? 'selected':'') ?>><?=h($opt)?></option>
                              <?php endforeach; ?>
                            </select>
                          <?php else: ?>
                            <input class="inp" type="text" name="<?=h($fname)?>" value="<?=h($row[$fname] ?? '')?>" required>
                          <?php endif; ?>
                        </div>
                      <?php endforeach; ?>
                    </div>
                    <div class="actions">
                      <button class="btn btn-primary" type="submit">Güncelle</button>
                      <button class="btn btn-soft" type="button" onclick="toggleEdit('<?=h($key)?>-<?= $rid ?>')">Vazgeç</button>
                    </div>
                  </form>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>

<script>
function toggleEdit(id){
  const row = document.querySelector('[data-row="'+id+'"]');
  if(!row) return;
  row.classList.toggle('editing');
}
</script>