<?php
declare(strict_types=1);

require_once __DIR__ . '/../connect.php';
require_once __DIR__ . '/../config.php';

function h(string $v): string { return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }

$pdo = null;
if (defined('ENABLE_DB') && ENABLE_DB) {
  try { $pdo = pdo(); } catch (Throwable $e) { $pdo = null; }
}

// Redirect if already logged in
if (!empty($_SESSION['admin_id'])) {
  header('Location: index.php');
  exit;
}

$errors = [];
$info = null;
$isFirstRun = false;

if ($pdo instanceof PDO) {
  try {
    $count = (int)$pdo->query('SELECT COUNT(*) FROM users')->fetchColumn();
    $isFirstRun = ($count === 0);
  } catch (Throwable $e) {
    $isFirstRun = false;
  }
}

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
  // login using existing users table (columns: id, username, password, email, created_at, updated_at, deleted_at)
  $username = trim((string)($_POST['username'] ?? ''));
  $password = (string)($_POST['password'] ?? '');

  if ($username === '' || $password === '') {
    $errors[] = 'Username and password are required.';
  } elseif (!$pdo instanceof PDO) {
    $errors[] = 'Database connection is unavailable.';
  } else {
    try {
      $stmt = $pdo->prepare('SELECT * FROM `users` WHERE `username` = :u LIMIT 1');
      $stmt->execute([':u' => $username]);
      $row = $stmt->fetch();
      if (!$row) {
        $errors[] = 'Invalid username or password.';
      } else {
        $deletedAt = isset($row['deleted_at']) ? (string)$row['deleted_at'] : '';
        if ($deletedAt !== '' && $deletedAt !== '0000-00-00 00:00:00') {
          $errors[] = 'Account is disabled.';
        } else {
          $stored = (string)($row['password'] ?? '');
          if (!verify_password_compat($password, $stored)) {
            $errors[] = 'Invalid username or password.';
          } else {
            $_SESSION['admin_id'] = (string)($row['id'] ?? $row['username']);
            $_SESSION['admin_username'] = (string)$row['username'];
            $_SESSION['admin_name'] = (string)$row['username'];
            header('Location: index.php');
            exit;
          }
        }
      }
    } catch (Throwable $e) {
      $errors[] = 'Login failed due to a server error.';
    }
  }
}

function verify_password_compat(string $input, string $stored): bool {
  $stored = trim($stored);
  if ($stored === '') { return false; }
  // PHP password_hash (bcrypt/argon2)
  if (preg_match('/^\$(2y|2a|2b)\$/', $stored) || strpos($stored, '$argon2') === 0) {
    return password_verify($input, $stored);
  }
  $lower = strtolower($stored);
  // Common legacy hashes
  if (preg_match('/^[a-f0-9]{32}$/', $lower)) { // MD5
    return md5($input) === $lower;
  }
  if (preg_match('/^[a-f0-9]{40}$/', $lower)) { // SHA1
    return sha1($input) === $lower;
  }
  // Fallback to plain-text comparison
  return hash_equals($stored, $input);
}

?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= h(APP_NAME) ?> | Admin Login</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="../assets/styles.css">
  <link rel="icon" href="../assets/favicon.jpg" type="image/jpeg">
  <style>
    .auth-card { max-width: 640px; margin: 0 auto; }
    .error-box { color:#c62828; font-weight:600; margin-top:8px; }
    .note { color: var(--muted); font-size: 14px; }
  </style>
</head>
<body>
  <main class="container">
    <header class="header">
      <img src="../assets/logo.jpg" alt="Logo" class="logo" />
      <h1 class="title">Admin Login</h1>
      <p class="subtitle">Secure access to the dashboard.</p>
    </header>

    <?php if ($errors): ?>
      <section class="card auth-card"><div class="error-box"><?= h(implode("\n", $errors)) ?></div></section>
    <?php endif; ?>

    <section class="card auth-card" aria-labelledby="login-title">
      <h2 id="login-title" class="sr-only">Login</h2>
      <form method="post" novalidate>
        <div class="grid" style="grid-template-columns:1fr;">
          <div class="field">
            <label for="l_username">Username</label>
            <input id="l_username" name="username" type="text" required autocomplete="username" />
          </div>
          <div class="field">
            <label for="l_password">Password</label>
            <input id="l_password" name="password" type="password" required autocomplete="current-password" />
          </div>
        </div>
        <div class="actions">
          <button class="btn" type="submit"><span class="btn-label">Login</span><span class="spinner" aria-hidden="true"></span></button>
        </div>
      </form>
    </section>
  </main>
</body>
</html>
