<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/db.php';

/* =========================
   SAFETY HELPERS (guarded)
   ========================= */
if (!function_exists('esc')) {
  function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}
if (!function_exists('app_url')) {
  function app_url(string $path=''): string {
    // base is the current directory in URL space
    $base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
    if ($path !== '' && $path[0] !== '/') $path = '/'.$path;
    return $base.$path;
  }
}
if (!function_exists('table_exists')) {
  function table_exists(mysqli $db, string $name): bool {
    $like = $db->real_escape_string($name);
    $res  = $db->query("SHOW TABLES LIKE '$like'");
    if (!$res) return false;
    $ok = $res->num_rows > 0;
    $res->close();
    return $ok;
  }
}
if (!function_exists('csrf_token')) {
  function csrf_token(): string {
    if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
    return $_SESSION['csrf'];
  }
}
if (!function_exists('csrf_check')) {
  function csrf_check(): bool {
    return isset($_POST['csrf']) && hash_equals($_SESSION['csrf'] ?? '', (string)$_POST['csrf']);
  }
}
if (!function_exists('redirect_by_role')) {
  function redirect_by_role(string $role): void {
    // Honor ?next=/relative/path if provided
    $next = $_GET['next'] ?? '';
    $is_rel = is_string($next) && $next !== '' && $next[0] === '/' && !preg_match('~^//|https?://~i', $next);
    if ($is_rel) {
      header("Location: ".$next);
      exit;
    }

    // Adjust these destinations to your structure if needed
    switch (strtolower($role)) {
      case 'super_admin':
      case 'admin':
        header("Location: ".app_url("/../admin/dashboard.php"));
        break;
      case 'lecturer':
        header("Location: ".app_url("/../lecturer/lecturer_sessions.php"));
        break;
      case 'student':
        header("Location: ".app_url("/../student/attendance_overview.php"));
        break;
      default:
        header("Location: ".app_url("/../index.php"));
        break;
    }
    exit;
  }
}

/* =========================
   RATE LIMIT
   ========================= */
const MAX_ATTEMPTS = 5;
const LOCK_SECONDS = 180;
$_SESSION['login_failures'] = (int)($_SESSION['login_failures'] ?? 0);
$now = time();
$locked_until = (int)($_SESSION['locked_until'] ?? 0);
$is_locked = $locked_until > $now;

/* =========================
   DEMO ACCOUNTS (fallback)
   ========================= */
$DEMO_ACCOUNTS = $DEMO_ACCOUNTS ?? [
  ['u'=>'admin',    'p'=>'admin123',   'name'=>'Demo Admin', 'role'=>'super_admin'],
  ['u'=>'lecturer', 'p'=>'lect123',    'name'=>'Demo Lecturer', 'role'=>'lecturer'],
  ['u'=>'student',  'p'=>'student123', 'name'=>'Demo Student',  'role'=>'student'],
];

$msg = '';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  if ($is_locked) {
    $msg = 'Too many failed attempts. Try again later.';
  } elseif (!csrf_check()) {
    $msg = 'Security check failed. Please refresh and try again.';
  } else {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if ($username === '' || $password === '') {
      $msg = 'Enter both username and password.';
    } else {
      $logged = null;

      // 1) Prefer ELMS super_admin table if present
      if ($mysqli instanceof mysqli) {
        if (table_exists($mysqli, 'elms_users')) {
          $st = $mysqli->prepare("
            SELECT id, username, password_hash, role_code, is_active
            FROM elms_users
            WHERE username=? LIMIT 1
          ");
          if ($st) {
            $st->bind_param('s', $username);
            $st->execute();
            $row = $st->get_result()->fetch_assoc();
            $st->close();

            if ($row && (int)$row['is_active'] === 1 && strtolower($row['role_code']) === 'super_admin') {
              if (password_verify($password, (string)$row['password_hash'])) {
                $logged = [
                  'id'   => (int)$row['id'],
                  'user' => (string)$row['username'],
                  'name' => (string)$row['username'],
                  'role' => 'super_admin',
                ];
                @$mysqli->query("UPDATE elms_users SET last_login_at=NOW() WHERE id=".(int)$row['id']);
              }
            }
          }
        }
        // 2) Generic users table (any role) if ELMS not used
        if (!$logged && table_exists($mysqli, 'users')) {
          $st = $mysqli->prepare("
            SELECT id, username, password AS password_hash, role,
                   COALESCE(full_name, username) AS name
            FROM users WHERE username=? LIMIT 1
          ");
          if ($st) {
            $st->bind_param('s', $username);
            $st->execute();
            $row = $st->get_result()->fetch_assoc();
            $st->close();

            if ($row) {
              $hashInfo = password_get_info((string)$row['password_hash']);
              $ok = $hashInfo['algo'] !== 0
                    ? password_verify($password, (string)$row['password_hash'])
                    : hash_equals((string)$row['password_hash'], $password);
              if ($ok) {
                $logged = [
                  'id'   => (int)$row['id'],
                  'user' => (string)$row['username'],
                  'name' => (string)$row['name'],
                  'role' => (string)$row['role'],
                ];
              }
            }
          }
        }
      }

      // 3) Fallback demo accounts
      if (!$logged) {
        foreach ($DEMO_ACCOUNTS as $acc) {
          if (strcasecmp($acc['u'], $username) === 0 && hash_equals($acc['p'], $password)) {
            $logged = ['id'=>0, 'user'=>$acc['u'], 'name'=>$acc['name'], 'role'=>$acc['role']];
            break;
          }
        }
      }

      if ($logged) {
        $_SESSION['user'] = $logged;
        $_SESSION['login_failures'] = 0;
        $_SESSION['locked_until'] = 0;
        redirect_by_role($logged['role']);
      } else {
        $msg = 'Invalid username or password';
        $_SESSION['login_failures']++;
      }
    }
  }

  if ($_SESSION['login_failures'] >= MAX_ATTEMPTS) {
    $_SESSION['locked_until'] = $now + LOCK_SECONDS;
    $is_locked = true;
    $msg = 'Too many failed attempts. Please wait a few minutes.';
  }
}

$lock_remaining = $is_locked ? max(0, $locked_until - $now) : 0;
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ELMS — Super Admin Login</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">
  <style>
    body{background:#f7f9fc}
    .card{border:1px solid #e8eef6;border-radius:12px;box-shadow:0 10px 30px rgba(18,38,63,.05)}
    .brand{font-weight:700;letter-spacing:.2px}
  </style>
</head>
<body>
  <div class="container py-5">
    <div class="row justify-content-center">
      <div class="col-sm-10 col-md-7 col-lg-5">
        <div class="text-center mb-3">
          <div class="mb-2">
            <img src="<?= esc(app_url('/includes/logo/edden_logo.jpg')) ?>" alt="EdenCampus" style="max-height:70px;width:auto">
          </div>
          <div class="brand h4 m-0">ELMS — Super Admin</div>
          <div class="text-muted small">Sign in to manage the system</div>
        </div>

        <?php if ($msg): ?>
          <div class="alert alert-danger py-2">
            <?= esc($msg) ?><?php if ($lock_remaining): ?> · <small><?= (int)$lock_remaining ?>s left</small><?php endif; ?>
          </div>
        <?php endif; ?>

        <div class="card">
          <div class="card-body">
            <form method="post" autocomplete="off" novalidate>
              <input type="hidden" name="csrf" value="<?= esc(csrf_token()) ?>">
              <div class="mb-3">
                <label class="form-label">Username</label>
                <input class="form-control" name="username" required autofocus>
              </div>
              <div class="mb-3">
                <label class="form-label">Password</label>
                <input class="form-control" type="password" name="password" required>
              </div>
              <button class="btn btn-primary w-100" <?= $is_locked?'disabled':'' ?>>
                <?= $is_locked ? 'Locked' : 'Sign in' ?>
              </button>
            </form>
          </div>
        </div>

        <div class="text-center mt-3">
          <small class="text-muted">© <?= date('Y') ?> EdenCampus ELMS</small>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
