<?php
require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

if (isAdminLoggedIn()) { header('Location: /admin/index.php'); exit; }

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { $error = 'Invalid request.'; goto done; }
    $username = trim($_POST['username'] ?? '');
    $pass     = $_POST['password'] ?? '';
    if (!$username || !$pass) { $error = 'Please fill in all fields.'; goto done; }

    $stmt = $pdo->prepare("SELECT * FROM admin_users WHERE (username=? OR email=?) AND status='active' LIMIT 1");
    $stmt->execute([$username, $username]);
    $admin = $stmt->fetch();

    if (!$admin) { $error = 'Invalid credentials.'; goto done; }

    $valid = false;
    if (str_starts_with($admin['password'], '$2y$')) {
        $valid = password_verify($pass, $admin['password']);
    } else {
        $valid = md5($pass) === $admin['password'];
        if ($valid) $pdo->prepare("UPDATE admin_users SET password=? WHERE id=?")->execute([password_hash($pass,PASSWORD_DEFAULT),$admin['id']]);
    }

    if (!$valid) { $error = 'Invalid credentials.'; goto done; }

    $pdo->prepare("UPDATE admin_users SET last_login=NOW(), last_login_ip=? WHERE id=?")->execute([$_SERVER['REMOTE_ADDR'],$admin['id']]);
    logActivity($pdo, null, $admin['id'], 'admin_login', 'Admin login from ' . $_SERVER['REMOTE_ADDR']);
    $_SESSION['admin_id']   = $admin['id'];
    $_SESSION['admin_role'] = $admin['role'];
    header('Location: /admin/index.php'); exit;
}
done:
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin Login | <?= SITE_NAME ?></title>
<link rel="icon" href="/assets/img/logo.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="auth-page">
<div class="container">
  <div class="d-flex justify-content-center">
    <div class="auth-card fade-in-up">
      <div class="auth-logo"><img src="/assets/img/logo.png" alt="<?= SITE_NAME ?>"></div>
      <h2 class="auth-title">Admin Portal</h2>
      <p class="auth-subtitle">Sign in to the management dashboard</p>
      <?php if ($error): ?><div class="alert alert-danger py-2 small"><i class="fa fa-exclamation-circle me-1"></i><?= sanitize($error) ?></div><?php endif; ?>
      <form method="POST">
        <?= csrf_field() ?>
        <div class="mb-3">
          <label class="form-label">Username or Email</label>
          <div class="input-group"><span class="input-group-text"><i class="fa fa-user-shield"></i></span>
          <input type="text" name="username" class="form-control" required autofocus></div>
        </div>
        <div class="mb-4">
          <label class="form-label">Password</label>
          <div class="input-group"><span class="input-group-text"><i class="fa fa-lock"></i></span>
          <input type="password" name="password" class="form-control" required></div>
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold"><i class="fa fa-sign-in-alt me-2"></i>Sign In to Admin</button>
      </form>
      <hr><p class="text-center small mb-0"><a href="/login.php" style="color:var(--primary)"><i class="fa fa-arrow-left me-1"></i>Customer Portal</a></p>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body></html>
