<?php
/**
 * NEPHRO ERP - SETTINGS + DEFINITIONS (v1)
 */
global $pdo;

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

$user_id = $_SESSION['user_id'] ?? 0;

// Profil
$profil = false;
if ($user_id > 0) {
  $me = $pdo->prepare("SELECT * FROM kullanicilar WHERE id=?");
  $me->execute([$user_id]);
  $profil = $me->fetch(PDO::FETCH_ASSOC);
}

// Kullanıcılar
$users = $pdo->query("SELECT * FROM kullanicilar ORDER BY ad_soyad ASC")->fetchAll(PDO::FETCH_ASSOC);

// Ayarlar tek satır
$ay = $pdo->query("SELECT * FROM ayarlar WHERE id=1")->fetch(PDO::FETCH_ASSOC);
if (!$ay) { $pdo->exec("INSERT INTO ayarlar (id) VALUES (1)"); $ay = $pdo->query("SELECT * FROM ayarlar WHERE id=1")->fetch(PDO::FETCH_ASSOC); }

// Tanımlar
$hepatitler = $pdo->query("SELECT * FROM hepatit_tanimlari ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$damarlar   = $pdo->query("SELECT * FROM damar_yolu_tanimlari ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$alerjiler  = $pdo->query("SELECT * FROM alerji_tanimlari ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$kronikler  = $pdo->query("SELECT * FROM kronik_hastalik_tanimlari ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$riskler    = $pdo->query("SELECT * FROM risk_uyari_tanimlari ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$sgkler     = $pdo->query("SELECT * FROM sgk_tipleri ORDER BY sira, ad")->fetchAll(PDO::FETCH_ASSOC);
$kurumlar   = $pdo->query("SELECT * FROM kurumlar ORDER BY kurum_tipi, kurum_adi")->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
  :root { --p:#4361ee; --s:#64748b; --bg:#f8fafc; --card:#ffffff; --dark:#0f172a; --danger:#ef4444; --success:#10b981; --warning:#f59e0b; }
  .settings-wrapper{max-width:1100px;margin:0 auto;padding:15px;}
  .settings-nav{display:flex;gap:10px;margin-bottom:25px;background:#fff;padding:10px;border-radius:20px;border:1px solid #e2e8f0;overflow-x:auto;}
  .nav-link{padding:12px 22px;border-radius:15px;color:var(--s);text-decoration:none;font-weight:800;font-size:.9rem;transition:.2s;white-space:nowrap;cursor:pointer;border:none;background:none;}
  .nav-link.active{background:var(--p);color:#fff;box-shadow:0 10px 15px -3px rgba(67,97,238,.3);}
  .settings-panel{display:none;background:#fff;border-radius:30px;padding:30px;border:1px solid #e2e8f0;box-shadow:0 10px 25px -5px rgba(0,0,0,.05);}
  .settings-panel.active{display:block;animation:fadeIn .25s ease-out;}
  @keyframes fadeIn{from{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}
  .form-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:18px;}
  .input-lux{width:100%;padding:14px;border-radius:15px;border:1px solid #e2e8f0;background:#f8fafc;outline:none;font-size:.95rem;}
  .input-lux:focus{border-color:var(--p);background:#fff;box-shadow:0 0 0 4px rgba(67,97,238,.1);}
  label{display:block;font-size:11px;font-weight:900;color:var(--s);margin-bottom:8px;text-transform:uppercase;}
  .btn-save{background:var(--p);color:#fff;border:none;padding:16px 30px;border-radius:18px;font-weight:900;cursor:pointer;width:100%;}
  .btn-mini{background:#0ea5e9;color:#fff;border:none;padding:10px 14px;border-radius:14px;font-weight:900;cursor:pointer;}
  .btn-danger{color:var(--danger);text-decoration:none;font-weight:900;}
  .muted{color:var(--s);font-size:.9rem;margin-top:6px}
  .cards{display:grid;grid-template-columns:1fr 1fr;gap:18px;}
  .box{border:1px solid #e2e8f0;border-radius:20px;padding:18px;background:#fff;}
  .list-item{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border:1px solid #f1f5f9;border-radius:16px;background:#f8fafc;margin-bottom:8px;}
  .tag{font-size:.75rem;font-weight:900;color:#fff;background:var(--p);padding:6px 10px;border-radius:999px;}
  @media(max-width:900px){.form-grid{grid-template-columns:1fr}.settings-panel{padding:20px}.cards{grid-template-columns:1fr}}
</style>

<div class="settings-wrapper">
  <div class="settings-nav">
    <button class="nav-link active" onclick="showTab(event,'merkez')"><i class="fas fa-hospital"></i> Merkez</button>
    <button class="nav-link" onclick="showTab(event,'entegrasyon')"><i class="fas fa-plug"></i> Entegrasyon</button>
    <button class="nav-link" onclick="showTab(event,'tanimlar')"><i class="fas fa-sliders-h"></i> Tanımlar</button>
    <button class="nav-link" onclick="showTab(event,'profil')"><i class="fas fa-user-circle"></i> Profilim</button>
    <button class="nav-link" onclick="showTab(event,'kullanicilar')"><i class="fas fa-users-cog"></i> Personel</button>
  </div>

  <!-- MERKEZ -->
  <div id="merkez" class="settings-panel active">
    <h3 style="margin-bottom:10px;"><i class="fas fa-id-card" style="color:var(--p)"></i> Merkez Bilgileri</h3>
    <div class="muted">Bu bilgiler rapor/PDF ve entegrasyonlarda kullanılabilir.</div>

    <form action="islem.php" method="POST" style="margin-top:18px;">
      <div class="form-grid">
        <div><label>Merkez Adı</label><input type="text" name="merkez_adi" class="input-lux" value="<?= h($ay['merkez_adi'] ?? '') ?>"></div>
        <div><label>E-Posta</label><input type="email" name="merkez_eposta" class="input-lux" value="<?= h($ay['merkez_eposta'] ?? '') ?>"></div>
        <div><label>Telefon</label><input type="text" name="merkez_tel" class="input-lux" value="<?= h($ay['merkez_tel'] ?? '') ?>"></div>
        <div><label>SGK Anlaşma No</label><input type="text" name="sgk_anlasma_no" class="input-lux" value="<?= h($ay['sgk_anlasma_no'] ?? '') ?>"></div>
      </div>
      <div class="f-group">
        <label>Adres</label>
        <textarea name="merkez_adres" class="input-lux" style="min-height:90px;"><?= h($ay['merkez_adres'] ?? '') ?></textarea>
      </div>

      <button type="submit" name="ayarlar_merkez_kaydet" class="btn-save">KAYDET</button>
    </form>
  </div>

  <!-- ENTEGRASYON -->
  <div id="entegrasyon" class="settings-panel">
    <h3 style="margin-bottom:10px;"><i class="fas fa-plug" style="color:var(--warning)"></i> SMS & Dış Lab Entegrasyonu</h3>
    <div class="muted">Kimlik bilgilerini güvenli tut. Şifreleri mümkünse çevresel değişkende saklamak ideal.</div>

    <form action="islem.php" method="POST" style="margin-top:18px;">
      <div class="cards">
        <div class="box">
          <h4 style="margin:0 0 10px 0;">SMS</h4>
          <div class="form-grid">
            <div><label>Provider</label><input name="sms_provider" class="input-lux" value="<?= h($ay['sms_provider'] ?? '') ?>"></div>
            <div><label>Sender</label><input name="sms_sender" class="input-lux" value="<?= h($ay['sms_sender'] ?? '') ?>"></div>
          </div>
          <div class="f-group"><label>API URL</label><input name="sms_api_url" class="input-lux" value="<?= h($ay['sms_api_url'] ?? '') ?>"></div>
          <div class="form-grid">
            <div><label>Kullanıcı Adı</label><input name="sms_username" class="input-lux" value="<?= h($ay['sms_username'] ?? '') ?>"></div>
            <div><label>Şifre</label><input name="sms_password" class="input-lux" value="<?= h($ay['sms_password'] ?? '') ?>"></div>
          </div>
        </div>

        <div class="box">
          <h4 style="margin:0 0 10px 0;">Dış Lab</h4>
          <div class="f-group"><label>API URL</label><input name="dislab_api_url" class="input-lux" value="<?= h($ay['dislab_api_url'] ?? '') ?>"></div>
          <div class="form-grid">
            <div><label>Kullanıcı</label><input name="dislab_username" class="input-lux" value="<?= h($ay['dislab_username'] ?? '') ?>"></div>
            <div><label>Şifre</label><input name="dislab_password" class="input-lux" value="<?= h($ay['dislab_password'] ?? '') ?>"></div>
          </div>
          <div class="f-group"><label>API Key (varsa)</label><input name="dislab_api_key" class="input-lux" value="<?= h($ay['dislab_api_key'] ?? '') ?>"></div>
        </div>
      </div>

      <button type="submit" name="ayarlar_entegrasyon_kaydet" class="btn-save" style="margin-top:16px;">KAYDET</button>
    </form>
  </div>

  <!-- TANIMLAR -->
  <div id="tanimlar" class="settings-panel">
    <h3 style="margin-bottom:10px;"><i class="fas fa-sliders-h" style="color:var(--success)"></i> Tanımlar</h3>
    <div class="muted">Hasta kaydındaki seçenekler buradan yönetilir.</div>

    <div class="cards" style="margin-top:18px;">
      <!-- KURUM -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Kurumlar</h4>
          <span class="tag"><?= count($kurumlar) ?></span>
        </div>

        <?php foreach($kurumlar as $k): ?>
          <div class="list-item">
            <div>
              <b><?= h($k['kurum_adi']) ?></b>
              <div class="muted" style="margin:2px 0 0;"><?= h($k['kurum_tipi']) ?> <?= ((int)$k['aktif']===1 ? '' : ' • pasif') ?></div>
            </div>
            <a class="btn-danger" href="islem.php?islem=kurum_sil&id=<?= (int)$k['id'] ?>" onclick="return confirm('Kurum silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>

        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="kurum">
          <div class="form-grid">
            <div><label>Kurum Adı</label><input name="kurum_adi" class="input-lux" required></div>
            <div>
              <label>Kurum Tipi</label>
              <select name="kurum_tipi" class="input-lux">
                <option>SGK</option><option>Özel</option><option>Diğer</option>
              </select>
            </div>
          </div>
          <button class="btn-mini" type="submit" name="tanim_ekle">+ Kurum Ekle</button>
        </form>
      </div>

      <!-- SGK -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">SGK Tipleri</h4>
          <span class="tag"><?= count($sgkler) ?></span>
        </div>

        <?php foreach($sgkler as $s): ?>
          <div class="list-item">
            <div><b><?= h($s['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=sgk_tipleri&id=<?= (int)$s['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>

        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="sgk_tipleri">
          <label>Yeni SGK Tipi</label>
          <input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>

      <!-- Hepatit -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Hepatit Tanımları</h4>
          <span class="tag"><?= count($hepatitler) ?></span>
        </div>
        <?php foreach($hepatitler as $t): ?>
          <div class="list-item">
            <div><b><?= h($t['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=hepatit_tanimlari&id=<?= (int)$t['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>
        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="hepatit_tanimlari">
          <label>Yeni Tanım</label><input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>

      <!-- Damar -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Damar Yolu Tanımları</h4>
          <span class="tag"><?= count($damarlar) ?></span>
        </div>
        <?php foreach($damarlar as $t): ?>
          <div class="list-item">
            <div><b><?= h($t['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=damar_yolu_tanimlari&id=<?= (int)$t['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>
        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="damar_yolu_tanimlari">
          <label>Yeni Tanım</label><input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>

      <!-- Alerji -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Alerji Tanımları</h4>
          <span class="tag"><?= count($alerjiler) ?></span>
        </div>
        <?php foreach($alerjiler as $t): ?>
          <div class="list-item">
            <div><b><?= h($t['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=alerji_tanimlari&id=<?= (int)$t['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>
        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="alerji_tanimlari">
          <label>Yeni Tanım</label><input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>

      <!-- Kronik -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Kronik Hastalık Tanımları</h4>
          <span class="tag"><?= count($kronikler) ?></span>
        </div>
        <?php foreach($kronikler as $t): ?>
          <div class="list-item">
            <div><b><?= h($t['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=kronik_hastalik_tanimlari&id=<?= (int)$t['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>
        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="kronik_hastalik_tanimlari">
          <label>Yeni Tanım</label><input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>

      <!-- Risk -->
      <div class="box">
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;">
          <h4 style="margin:0;">Risk Uyarı Tanımları</h4>
          <span class="tag"><?= count($riskler) ?></span>
        </div>
        <?php foreach($riskler as $t): ?>
          <div class="list-item">
            <div><b><?= h($t['ad']) ?></b></div>
            <a class="btn-danger" href="islem.php?islem=tanim_sil&tablo=risk_uyari_tanimlari&id=<?= (int)$t['id'] ?>" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash-alt"></i></a>
          </div>
        <?php endforeach; ?>
        <form action="islem.php" method="POST" style="margin-top:10px;">
          <input type="hidden" name="tanim_tip" value="risk_uyari_tanimlari">
          <label>Yeni Tanım</label><input name="ad" class="input-lux" required>
          <button class="btn-mini" type="submit" name="tanim_ekle" style="margin-top:10px;">+ Ekle</button>
        </form>
      </div>
    </div>
  </div>

  <!-- PROFIL -->
  <div id="profil" class="settings-panel">
    <h3 style="margin-bottom:25px;"><i class="fas fa-lock" style="color:var(--warning)"></i> Kişisel Bilgiler</h3>
    <form action="islem.php" method="POST">
      <div class="form-grid">
        <div>
          <label>Adınız Soyadınız</label>
          <input type="text" name="ad_soyad" class="input-lux" value="<?= h($profil['ad_soyad'] ?? '') ?>">
        </div>
        <div>
          <label>Kullanıcı Adı</label>
          <input type="text" class="input-lux" value="<?= h($profil['kullanici_adi'] ?? '') ?>" disabled style="opacity:.6">
        </div>
        <div>
          <label>Yeni Şifre</label>
          <input type="password" name="yeni_sifre" class="input-lux" placeholder="Değiştirmeyecekseniz boş bırakın">
        </div>
        <div>
          <label>Şifre Tekrar</label>
          <input type="password" name="yeni_sifre_tekrar" class="input-lux" placeholder="Şifreyi onaylayın">
        </div>
      </div>
      <button type="submit" name="profil_guncelle" class="btn-save">BİLGİLERİMİ GÜNCELLE</button>
    </form>
  </div>

  <!-- KULLANICILAR -->
  <div id="kullanicilar" class="settings-panel">
    <h3 style="margin-bottom:15px;"><i class="fas fa-user-shield" style="color:var(--success)"></i> Sistem Kullanıcıları</h3>

    <?php foreach($users as $u): ?>
      <div class="list-item">
        <div style="display:flex;gap:12px;align-items:center;">
          <div style="width:38px;height:38px;background:var(--p);color:#fff;border-radius:12px;display:flex;align-items:center;justify-content:center;font-weight:900;">
            <?= h(mb_substr($u['ad_soyad'],0,1)) ?>
          </div>
          <div>
            <b style="display:block;"><?= h($u['ad_soyad']) ?></b>
            <div class="muted" style="margin:2px 0 0;"><?= h($u['rol']) ?></div>
          </div>
        </div>
        <a class="btn-danger" href="islem.php?islem=kullanici_sil&id=<?= (int)$u['id'] ?>" onclick="return confirm('Kullanıcı silinsin mi?')">
          <i class="fas fa-trash-alt"></i>
        </a>
      </div>
    <?php endforeach; ?>

    <!-- (Senin yeni kullanıcı modal/ekleme yapın varsa burada bırakabiliriz) -->
  </div>
</div>

<script>
  function showTab(evt, tabId){
    const panels = document.getElementsByClassName("settings-panel");
    for(let i=0;i<panels.length;i++) panels[i].classList.remove("active");
    const nav = document.getElementsByClassName("nav-link");
    for(let i=0;i<nav.length;i++) nav[i].classList.remove("active");
    document.getElementById(tabId).classList.add("active");
    evt.currentTarget.classList.add("active");
  }
</script>
