<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

/* -----------------------------
   1) DB include: core/db.php
------------------------------ */
$dbFile = __DIR__ . '/core/db.php';
if (!is_file($dbFile)) $dbFile = __DIR__ . '/../core/db.php';
if (!is_file($dbFile)) {
  http_response_code(500);
  die("Sistem hatası: core/db.php bulunamadı.");
}
require_once $dbFile;

/* -----------------------------
   2) DB helper (mysqli / PDO)
------------------------------ */
function db_is_pdo(): bool    { return isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO; }
function db_is_mysqli(): bool { return isset($GLOBALS['db']) && $GLOBALS['db'] instanceof mysqli; }

function db_fetch_one(string $sql, array $params = []): ?array {
  if (db_is_pdo()) {
    $pdo = $GLOBALS['pdo'];
    $st = $pdo->prepare($sql);
    $st->execute($params);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
  }
  if (db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return null;
    if ($params) {
      $types = str_repeat('s', count($params)); // burada hepsini string basıyoruz (safe enough)
      $st->bind_param($types, ...$params);
    }
    $st->execute();
    $res = $st->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $st->close();
    return $row ?: null;
  }
  die("DB bağlantısı bulunamadı. core/db.php içinde \$db (mysqli) veya \$pdo (PDO) olmalı.");
}

function db_exec(string $sql, array $params = []): bool {
  if (db_is_pdo()) {
    $pdo = $GLOBALS['pdo'];
    $st = $pdo->prepare($sql);
    return $st->execute($params);
  }
  if (db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return false;
    if ($params) {
      $types = str_repeat('s', count($params));
      $st->bind_param($types, ...$params);
    }
    $ok = $st->execute();
    $st->close();
    return (bool)$ok;
  }
  return false;
}

/* -----------------------------
   3) Dil seçimi (cookie + session)
------------------------------ */
$supportedLangs = ['tr','en'];
$lang = $_GET['lang'] ?? $_POST['lang'] ?? $_SESSION['lang'] ?? ($_COOKIE['lang'] ?? 'tr');
$lang = in_array($lang, $supportedLangs, true) ? $lang : 'tr';
$_SESSION['lang'] = $lang;
setcookie('lang', $lang, time() + (86400 * 365), "/");

$T = [
  'tr' => [
    'title' => 'Nephro Link - Giriş',
    'subtitle' => 'Yetkili erişim ve hasta seans arşivi.',
    'tab_staff' => 'Personel Girişi',
    'tab_patient' => 'Seans Arşivi',
    'staff_user' => 'Kullanıcı Adı',
    'staff_pass' => 'Şifre',
    'btn_login'  => 'Giriş Yap',
    'patient_tc' => 'TC Kimlik No',
    'patient_birth' => 'Doğum Tarihi',
    'patient_enter' => 'Portal’a Gir',
    'captcha_label' => 'Güvenlik Doğrulaması',
    'captcha_hint'  => 'Sonucu yazın',
    'captcha_err'   => 'Güvenlik doğrulaması hatalı. Lütfen tekrar deneyin.',
    'login_err'     => 'Kullanıcı adı veya şifre hatalı.',
    'passive_err'   => 'Hesap pasif durumda. Yönetici ile görüşün.',
    'tc_err'        => 'TC No 11 haneli olmalı.',
    'patient_err'   => 'Bilgiler doğrulanamadı.',
    'patient_no_table' => 'Hasta doğrulama altyapısı hazır. (Hasta tablosu/alanları projeye bağlanacak.)',
    'log_info' => 'Güvenlik: Erişim verileri loglanır.',
    'log_toast' => 'Log record: erişim verileri loglandı.',
  ],
  'en' => [
    'title' => 'Nephro Link - Sign In',
    'subtitle' => 'Authorized access and patient session archive.',
    'tab_staff' => 'Staff Login',
    'tab_patient' => 'Session Archive',
    'staff_user' => 'Username',
    'staff_pass' => 'Password',
    'btn_login'  => 'Sign In',
    'patient_tc' => 'National ID',
    'patient_birth' => 'Date of Birth',
    'patient_enter' => 'Enter Portal',
    'captcha_label' => 'Security Check',
    'captcha_hint'  => 'Enter result',
    'captcha_err'   => 'Security check failed. Please try again.',
    'login_err'     => 'Invalid username or password.',
    'passive_err'   => 'Account is inactive. Contact admin.',
    'tc_err'        => 'National ID must be 11 digits.',
    'patient_err'   => 'Verification failed.',
    'patient_no_table' => 'Patient verification UI is ready. (Connect patient table/fields in project.)',
    'log_info' => 'Security: Access metadata is logged.',
    'log_toast' => 'Log record: access metadata captured.',
  ],
];
function t(string $k, array $T, string $lang): string {
  return htmlspecialchars($T[$lang][$k] ?? $k, ENT_QUOTES, 'UTF-8');
}

/* -----------------------------
   4) Basit rate-limit (session)
------------------------------ */
$_SESSION['fail_count'] = (int)($_SESSION['fail_count'] ?? 0);
$_SESSION['fail_ts']    = (int)($_SESSION['fail_ts'] ?? time());
if (time() - $_SESSION['fail_ts'] > 600) { // 10 dk reset
  $_SESSION['fail_count'] = 0;
  $_SESSION['fail_ts'] = time();
}

/* -----------------------------
   5) Captcha: matematik
------------------------------ */
if (!isset($_SESSION['cap_a'], $_SESSION['cap_b'])) {
  $_SESSION['cap_a'] = random_int(2, 9);
  $_SESSION['cap_b'] = random_int(1, 9);
}
$capA = (int)$_SESSION['cap_a'];
$capB = (int)$_SESSION['cap_b'];
$capAns = $capA + $capB;

/* -----------------------------
   6) Log (opsiyonel)
   access_logs tablosu varsa yazar, yoksa sessiz geçer
------------------------------ */
function log_access(string $action, int $success, string $detail = '', ?int $userId = null, ?string $tcNo = null): void {
  $ip = $_SERVER['REMOTE_ADDR'] ?? '';
  $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
  // access_logs yoksa prepare fail olur, biz de sessiz geçiyoruz
  @db_exec(
    "INSERT INTO access_logs (action, success, detail, user_id, tc_no, ip, user_agent, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, NOW())",
    [$action, (string)$success, $detail, (string)($userId ?? ''), (string)($tcNo ?? ''), $ip, $ua]
  );
}

/* -----------------------------
   7) Role redirect mapping
   (kendi yapına göre düzenle)
------------------------------ */
$ROLE_REDIRECT = [
  'admin'      => 'dashboard.php',
  'doctor'     => 'dashboard.php',
  'nurse'      => 'dashboard.php',
  'secretary'  => 'dashboard.php',
  'ik'         => 'dashboard.php',
  'idari_amir' => 'dashboard.php',
];

/* -----------------------------
   8) Aktif sekme
------------------------------ */
$error = '';
$info  = '';
$active_tab = $_GET['active_tab'] ?? ($_SESSION['active_tab'] ?? 'login');
unset($_SESSION['active_tab']);

/* -----------------------------
   9) POST işlemleri
------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = (string)($_POST['action'] ?? '');
  $userCap = (int)($_POST['captcha_answer'] ?? -999);

  // çok fazla hata varsa kısa bloke
  if ($_SESSION['fail_count'] >= 20) {
    $error = "Çok fazla deneme. Bir süre sonra tekrar deneyin.";
    $_SESSION['active_tab'] = $action === 'patient' ? 'portal' : 'login';
  } elseif ($userCap !== $capAns) {
    $error = t('captcha_err', $T, $lang);
    $_SESSION['fail_count']++;
    $_SESSION['active_tab'] = $action === 'patient' ? 'portal' : 'login';
    log_access($action === 'patient' ? 'patient_login' : 'staff_login', 0, 'captcha_failed');
  } else {
    // captcha doğru -> yenile
    unset($_SESSION['cap_a'], $_SESSION['cap_b']);

    if ($action === 'login') {
      $username = trim((string)($_POST['username'] ?? ''));
      $password = (string)($_POST['password'] ?? '');

      $u = db_fetch_one(
        "SELECT id, username, password_hash, full_name, status, role
         FROM users WHERE username = ? LIMIT 1",
        [$username]
      );

      if (!$u) {
        $error = t('login_err', $T, $lang);
        $_SESSION['fail_count']++;
        $_SESSION['active_tab'] = 'login';
        log_access('staff_login', 0, 'user_not_found');
      } elseif (($u['status'] ?? '') !== 'active') {
        $error = t('passive_err', $T, $lang);
        $_SESSION['fail_count']++;
        $_SESSION['active_tab'] = 'login';
        log_access('staff_login', 0, 'user_passive', (int)$u['id']);
      } else {
        $hash = (string)($u['password_hash'] ?? '');
        $ok = password_verify($password, $hash);

        if (!$ok) {
          $error = t('login_err', $T, $lang);
          $_SESSION['fail_count']++;
          $_SESSION['active_tab'] = 'login';
          log_access('staff_login', 0, 'wrong_password', (int)$u['id']);
        } else {
          // başarılı login
          session_regenerate_id(true);
          $_SESSION['user_id']   = (int)$u['id'];
          $_SESSION['username']  = (string)$u['username'];
          $_SESSION['full_name'] = (string)$u['full_name'];
          $_SESSION['role']      = (string)$u['role'];

          // last login güncelle
          $ip = $_SERVER['REMOTE_ADDR'] ?? '';
          db_exec("UPDATE users SET last_login_at = NOW(), last_login_ip = ? WHERE id = ?", [$ip, (string)$u['id']]);

          $_SESSION['fail_count'] = 0;
          log_access('staff_login', 1, 'ok', (int)$u['id']);

          $role = (string)$u['role'];
          $to = $ROLE_REDIRECT[$role] ?? 'dashboard.php';
          header("Location: " . $to);
          exit;
        }
      }
    }

    if ($action === 'patient') {
      $tc = preg_replace('/\D+/', '', (string)($_POST['tc_no'] ?? ''));
      $birth = (string)($_POST['dogum_tarihi'] ?? '');

      if (strlen($tc) !== 11) {
        $error = t('tc_err', $T, $lang);
        $_SESSION['fail_count']++;
        $_SESSION['active_tab'] = 'portal';
        log_access('patient_login', 0, 'tc_invalid', null, $tc);
      } else {
        /**
         * Hasta doğrulama:
         * - Projede hasta tablon hangisiyse burayı bağlarız.
         * Şimdilik iki olası tabloyu deniyoruz:
         * 1) patients (tc_no, birth_date)
         * 2) hastalar (tc_no, dogum_tarihi)
         */
        $patient = null;

        // Aday 1
        $patient = db_fetch_one(
          "SELECT id, tc_no FROM patients WHERE tc_no = ? AND birth_date = ? LIMIT 1",
          [$tc, $birth]
        );

        // Aday 2 (ilk yoksa)
        if (!$patient) {
          $patient = db_fetch_one(
            "SELECT id, tc_no FROM hastalar WHERE tc_no = ? AND dogum_tarihi = ? LIMIT 1",
            [$tc, $birth]
          );
        }

        if (!$patient) {
          // tablo yoksa / alanlar farklıysa burası false döner; kullanıcıya nazik bilgi
          $info = t('patient_no_table', $T, $lang);
          $error = t('patient_err', $T, $lang);
          $_SESSION['fail_count']++;
          $_SESSION['active_tab'] = 'portal';
          log_access('patient_login', 0, 'patient_not_found_or_schema_mismatch', null, $tc);
        } else {
          session_regenerate_id(true);
          $_SESSION['patient_id'] = (int)$patient['id'];
          $_SESSION['patient_tc'] = (string)$tc;

          $_SESSION['fail_count'] = 0;
          log_access('patient_login', 1, 'ok', null, $tc);

          header("Location: hasta-portal.php");
          exit;
        }
      }
    }
  }

  // POST sonrası sekmeyi geri aç
  $active_tab = $_SESSION['active_tab'] ?? $active_tab;
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head>
  <meta charset="utf-8">
  <title><?= t('title', $T, $lang) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

  <style>
    :root {
      --primary-color: #4361ee;
      --primary-hover: #3a56d4;
      --border-color: #e2e8f0;
      --input-focus-shadow: rgba(67,97,238,0.22);
    }
    body{
      background: linear-gradient(135deg, #f0f4f8 0%, #eef1f6 100%);
      min-height:100vh;
      display:flex;
      justify-content:center;
      align-items:center;
      padding:20px;
      font-family:'Inter', sans-serif;
    }
    .login-card{
      width:100%;
      max-width:520px;
      background:#fff;
      padding:38px 38px 26px;
      border-radius:20px;
      border:1px solid var(--border-color);
      box-shadow:0 10px 25px rgba(0,0,0,0.06);
      position:relative;
    }
    .lang-box{
      position:absolute;
      top:14px;
      right:14px;
      z-index:5;
    }
    .brand-header img{
      height:70px;
      margin-bottom:12px;
      object-fit:contain;
    }
    .brand-name{
      font-size:34px;
      font-weight:800;
      color:var(--primary-color);
      letter-spacing:.2px;
    }
    .sub{
      color:#64748b;
      font-size:14px;
      margin-top:6px;
    }

    /* mobilde üst üste düşmesin */
    .nav-tabs{
      display:grid !important;
      grid-template-columns: 1fr 1fr;
      gap: 8px;
      border-bottom:1px solid var(--border-color);
      margin-top: 18px;
    }
    .nav-tabs .nav-item{ width:100%; }
    .nav-tabs .nav-link{
      width:100%;
      border:none;
      border-bottom:2px solid transparent;
      color:#475569;
      font-weight:700;
      padding:12px 10px;
      display:flex;
      align-items:center;
      justify-content:center;
      gap:8px;
      border-radius:12px 12px 0 0;
      white-space:nowrap;
    }
    .nav-tabs .nav-link.active{
      color:var(--primary-color);
      border-bottom-color:var(--primary-color);
      background:transparent;
    }

    .form-control{
      padding:12px;
      border-radius:12px;
      border:1px solid var(--border-color);
    }
    .form-control:focus{
      border-color:var(--primary-color);
      box-shadow:0 0 0 4px var(--input-focus-shadow);
    }
    .btn-primary{
      padding:12px;
      border-radius:12px;
      background:var(--primary-color);
      border-color:var(--primary-color);
      font-weight:700;
    }
    .btn-primary:hover{
      background:var(--primary-hover);
      border-color:var(--primary-hover);
    }

    .captcha-box{
      padding:12px;
      border:1px dashed var(--border-color);
      border-radius:12px;
      background:#fafcff;
      margin-top:14px;
    }
    .security-note{
      display:flex;
      align-items:center;
      justify-content:center;
      gap:8px;
      color:#64748b;
      font-size:12.5px;
      margin-top:14px;
    }
    .tab-content{ margin-top:18px; }
    .footer{
      margin-top:16px;
      padding-top:12px;
      border-top:1px solid #eef2f7;
      text-align:center;
      color:#64748b;
      font-size:12.5px;
    }
  </style>
</head>

<body>
<div class="login-card">

  <!-- Dil -->
  <div class="lang-box">
    <div class="dropdown">
      <button class="btn btn-sm btn-light border dropdown-toggle" data-bs-toggle="dropdown" type="button">
        <i class="bi bi-translate me-1"></i> <?= strtoupper($lang) ?>
      </button>
      <ul class="dropdown-menu dropdown-menu-end">
        <li><a class="dropdown-item" href="?lang=tr">Türkçe</a></li>
        <li><a class="dropdown-item" href="?lang=en">English</a></li>
      </ul>
    </div>
  </div>

  <div class="brand-header text-center">
    <img src="includes/logo.png" alt="Logo">
    <div class="brand-name">Nephro Link</div>
    <div class="sub"><?= t('subtitle', $T, $lang) ?></div>
  </div>

  <ul class="nav nav-tabs" role="tablist">
    <li class="nav-item" role="presentation">
      <button class="nav-link <?= $active_tab=='login'?'active':'' ?>"
              id="login-tab" data-bs-toggle="tab" data-bs-target="#login-pane" type="button" role="tab">
        <i class="bi bi-person"></i> <?= t('tab_staff', $T, $lang) ?>
      </button>
    </li>
    <li class="nav-item" role="presentation">
      <button class="nav-link <?= $active_tab=='portal'?'active':'' ?>"
              id="portal-tab" data-bs-toggle="tab" data-bs-target="#portal-pane" type="button" role="tab">
        <i class="bi bi-folder2"></i> <?= t('tab_patient', $T, $lang) ?>
      </button>
    </li>
  </ul>

  <div class="tab-content">

    <?php if (!empty($error)): ?>
      <div class="alert alert-danger py-2 mt-3 mb-0" style="border-radius:12px;">
        <i class="bi bi-exclamation-triangle me-1"></i> <?= htmlspecialchars($error) ?>
      </div>
    <?php endif; ?>

    <?php if (!empty($info)): ?>
      <div class="alert alert-warning py-2 mt-2 mb-0" style="border-radius:12px;">
        <i class="bi bi-info-circle me-1"></i> <?= htmlspecialchars($info) ?>
      </div>
    <?php endif; ?>

    <!-- PERSONEL -->
    <div class="tab-pane fade <?= $active_tab=='login'?'show active':'' ?>" id="login-pane" role="tabpanel">
      <form method="post" class="mt-3" autocomplete="on">
        <input type="hidden" name="action" value="login">
        <input type="hidden" name="lang" value="<?= htmlspecialchars($lang) ?>">

        <div class="input-group mt-2">
          <span class="input-group-text bg-white"><i class="bi bi-person"></i></span>
          <input type="text" name="username" class="form-control" placeholder="<?= t('staff_user', $T, $lang) ?>" required>
        </div>

        <div class="input-group mt-3">
          <span class="input-group-text bg-white"><i class="bi bi-lock"></i></span>
          <input type="password" name="password" class="form-control" placeholder="<?= t('staff_pass', $T, $lang) ?>" required>
        </div>

        <div class="captcha-box">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
            <div class="fw-semibold">
              <i class="bi bi-shield-check me-1"></i> <?= t('captcha_label', $T, $lang) ?>
            </div>
            <div class="text-muted" style="font-size:12.5px;">
              <?= $capA ?> + <?= $capB ?> = ?
            </div>
          </div>
          <input type="number" name="captcha_answer" class="form-control mt-2" placeholder="<?= t('captcha_hint', $T, $lang) ?>" required>
        </div>

        <button class="btn btn-primary w-100 mt-3">
          <i class="bi bi-box-arrow-in-right me-1"></i> <?= t('btn_login', $T, $lang) ?>
        </button>

        <div class="security-note">
          <i class="bi bi-activity"></i> <?= t('log_info', $T, $lang) ?>
        </div>
      </form>
    </div>

    <!-- HASTA PORTALI -->
    <div class="tab-pane fade <?= $active_tab=='portal'?'show active':'' ?>" id="portal-pane" role="tabpanel">
      <form method="post" class="mt-3" autocomplete="off">
        <input type="hidden" name="action" value="patient">
        <input type="hidden" name="lang" value="<?= htmlspecialchars($lang) ?>">

        <div class="input-group mt-2">
          <span class="input-group-text bg-white"><i class="bi bi-person-vcard"></i></span>
          <input type="text" name="tc_no" class="form-control" inputmode="numeric" maxlength="11"
                 placeholder="<?= t('patient_tc', $T, $lang) ?> (11)" required>
        </div>

        <div class="input-group mt-3">
          <span class="input-group-text bg-white"><i class="bi bi-calendar-event"></i></span>
          <input type="date" name="dogum_tarihi" class="form-control" placeholder="<?= t('patient_birth', $T, $lang) ?>" required>
        </div>

        <div class="captcha-box">
          <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
            <div class="fw-semibold">
              <i class="bi bi-shield-check me-1"></i> <?= t('captcha_label', $T, $lang) ?>
            </div>
            <div class="text-muted" style="font-size:12.5px;">
              <?= $capA ?> + <?= $capB ?> = ?
            </div>
          </div>
          <input type="number" name="captcha_answer" class="form-control mt-2" placeholder="<?= t('captcha_hint', $T, $lang) ?>" required>
        </div>

        <button class="btn btn-primary w-100 mt-3">
          <i class="bi bi-folder2-open me-1"></i> <?= t('patient_enter', $T, $lang) ?>
        </button>

        <div class="security-note">
          <i class="bi bi-activity"></i> <?= t('log_info', $T, $lang) ?>
        </div>
      </form>
    </div>

  </div>

  <div class="footer">
    © <?= date('Y') ?> Nephro Link • Abdul Baki Kuzucu
  </div>
</div>

<!-- Log toast -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
  <div id="logToast" class="toast" role="alert" aria-live="polite" aria-atomic="true">
    <div class="toast-header">
      <i class="bi bi-activity me-2"></i>
      <strong class="me-auto">Nephro Link</strong>
      <small><?= strtoupper($lang) ?></small>
      <button type="button" class="btn-close ms-2 mb-1" data-bs-dismiss="toast"></button>
    </div>
    <div class="toast-body">
      <?= t('log_toast', $T, $lang) ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // URL’de active_tab varsa ilgili sekmeyi aç
  const params = new URLSearchParams(location.search);
  const active = params.get('active_tab');
  if (active) {
    const tab = document.getElementById(active + '-tab');
    if (tab) new bootstrap.Tab(tab).show();
  }

  // Log toast
  window.addEventListener('load', () => {
    const toastEl = document.getElementById('logToast');
    if (toastEl) new bootstrap.Toast(toastEl, { delay: 2800 }).show();
  });
</script>
</body>
</html>
