<?php
require_once __DIR__ . '/config.php';

if (!empty($_SESSION['admin_id'])) redirect(BASE_URL . '/index.php');

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $u = trim($_POST['username'] ?? '');
    $p = $_POST['password'] ?? '';
    $stmt = $conn->prepare("SELECT id, username, password FROM admin_users WHERE username = ? LIMIT 1");
    $stmt->bind_param('s', $u);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    if ($res && password_verify($p, $res['password'])) {
        $_SESSION['admin_id'] = $res['id'];
        $_SESSION['admin_username'] = $res['username'];
        redirect(BASE_URL . '/index.php');
    } else {
        $err = 'Invalid username or password';
    }
}
?>
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login | CMS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>body{background:linear-gradient(135deg,#667eea,#764ba2);min-height:100vh;display:flex;align-items:center;}</style>
</head><body>
<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-4">
      <div class="card shadow">
        <div class="card-body p-4">
          <h3 class="text-center mb-4">CMS Admin Login</h3>
          <?php if ($err): ?><div class="alert alert-danger"><?= e($err) ?></div><?php endif; ?>
          <form method="post">
            <div class="mb-3">
              <label class="form-label">Username</label>
              <input type="text" name="username" class="form-control" required autofocus>
            </div>
            <div class="mb-3">
              <label class="form-label">Password</label>
              <input type="password" name="password" class="form-control" required>
            </div>
            <button class="btn btn-primary w-100">Login</button>
          </form>
          <p class="text-muted small mt-3 mb-0 text-center">Default: admin / admin123</p>
        </div>
      </div>
    </div>
  </div>
</div>
</body></html>
