<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/auth.php';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $stmt = db()->prepare("SELECT id, full_name, username, password_hash, role, account_type, password_changed_at, status FROM users WHERE username = ? AND portal_access IN ('admin','both') LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();
    if ($user && password_verify($password, $user['password_hash'])) {
        if ($user['status'] !== 'active') {
            $error = 'Account inactive.';
        } elseif ($user['role'] !== 'admin' && $user['role'] !== 'staff') {
            $error = 'Portal restricted.';
        } elseif ($user['role'] !== 'admin' && passwordExpired($user['password_changed_at'])) {
            $error = 'Password expired. Contact admin for reset.';
        } else {
            loginUser($user);
            header('Location: dashboard.php');
            exit;
        }
    } else {
        $error = 'Invalid login.';
    }
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Admin Login - SHAHANA VEGETABLES</title>
  <link rel="stylesheet" href="../assets/style.css">
</head>
<body>
<div class="login-shell">
  <div class="login-card">
    <div class="hero-pane">
      <h1>SHAHANA VEGETABLES</h1>
      <p>Fresh vegetables, retail and wholesale billing, customer accounts, expense tracking, and reports in one clean workspace for admin and staff.</p>
      <p><strong>Portal:</strong> adm.shahanaveg.in</p>
    </div>
    <div class="form-pane">
      <h2>Admin / Staff Login</h2>
      <?php if ($error): ?><p style="color:#b23b3b"><?php echo htmlspecialchars($error); ?></p><?php endif; ?>
      <form method="post">
        <label>Username</label>
        <input type="text" name="username" required>
        <label>Password</label>
        <input type="password" name="password" required>
        <button class="btn btn-primary" type="submit">Login</button>
      </form>
    </div>
  </div>
</div>
</body>
</html>
