<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->safeLoad();

require_once __DIR__ . '/../core/db.php';
require_once __DIR__ . '/i18n.php';

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

function t_local(string $k){ return t($k); }

// 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) { // reset after 10min
  $_SESSION['fail_count'] = 0;
  $_SESSION['fail_ts'] = time();
}

// captcha
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;

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'] ?? '';
  @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]
  );
}

$ROLE_REDIRECT = [
  'admin' => '/dashboard.php',
  'manager' => '/dashboard.php',
  'user' => '/dashboard.php',
];

$error = '';
$info = '';
$active_tab = $_GET['active_tab'] ?? $_SESSION['active_tab'] ?? 'login';
unset($_SESSION['active_tab']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = (string)($_POST['action'] ?? '');
  $userCap = (int)($_POST['captcha_answer'] ?? -999);

  if ($_SESSION['fail_count'] >= 20) {
    $error = "Too many attempts. Try later.";
    $_SESSION['active_tab'] = $action === 'patient' ? 'portal' : 'login';
  } elseif ($userCap !== $capAns) {
    $error = t('captcha_err');
    $_SESSION['fail_count']++;
    $_SESSION['active_tab'] = $action === 'patient' ? 'portal' : 'login';
    log_access($action === 'patient' ? 'patient_login' : 'staff_login', 0, 'captcha_failed');
  } else {
    unset($_SESSION['cap_a'], $_SESSION['cap_b']);

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

      $u = db_fetch_one("SELECT u.id,u.username,u.password_hash,u.full_name,u.status,r.name AS role FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.username = ? LIMIT 1", [$username]);
      if (!$u) {
        $error = t('login_err');
        $_SESSION['fail_count']++;
        $_SESSION['active_tab'] = 'login';
        log_access('staff_login', 0, 'user_not_found');
      } elseif (($u['status'] ?? '') !== 'active') {
        $error = t('inactive_err');
        $_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');
          $_SESSION['fail_count']++;
          $_SESSION['active_tab'] = 'login';
          log_access('staff_login', 0, 'wrong_password', (int)$u['id']);
        } else {
          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'];

          $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') {
      // left as placeholder; project-specific
      $error = t('patient_no_table');
      $_SESSION['active_tab'] = 'portal';
    }
  }

  $active_tab = $_SESSION['active_tab'] ?? $active_tab;
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head>
  <meta charset="utf-8">
  <title><?= t('title') ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <div class="container">
    <div class="auth-card">
      <div class="auth-logo"><img src="/images/logo.svg" alt="NephroLink" style="height:42px"></div>
      <h2><?= t('tab_staff') ?></h2>
      <div class="sub"><?= t('subtitle') ?></div>

      <?php if (!empty($error)): ?>
        <div class="errors" style="margin-top:12px"><?=htmlspecialchars($error)?></div>
      <?php endif; ?>
      <?php if (!empty($info)): ?>
        <div class="errors" style="margin-top:12px"><?=htmlspecialchars($info)?></div>
      <?php endif; ?>

      <form method="post" class="mt-3">
        <input type="hidden" name="action" value="login">
        <input type="hidden" name="lang" value="<?=htmlspecialchars($lang)?>">

        <div class="form-group">
          <label><?= t('staff_user') ?></label>
          <input name="username" class="form-input" required>
        </div>
        <div class="form-group">
          <label><?= t('staff_pass') ?></label>
          <input name="password" type="password" class="form-input" required>
        </div>

        <div class="captcha-box">
          <div class="d-flex align-items-center justify-content-between">
            <div class="fw-semibold"><i class="bi bi-shield-check me-1"></i> <?= t('captcha_label') ?></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') ?>" required>
        </div>

        <button class="btn" style="width:100%;margin-top:14px;" type="submit"><?= t('btn_login') ?></button>

        <div class="muted" style="margin-top:10px;"><?= t('log_info') ?></div>
      </form>

      <div class="footer" style="margin-top:18px">© <?= date('Y') ?> Nephro Link</div>
    </div>
  </div>
</body>
</html>