<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';

if (auth_user()) {
    redirect(auth_current_redirect_path());
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    $pdo = crm_pdo();
    $st = $pdo->prepare("SELECT * FROM users WHERE username = :u AND is_active = 1 LIMIT 1");
    $st->execute([':u' => $username]);
    $user = $st->fetch();

    if ($user && password_verify($password, (string)$user['password_hash'])) {
        auth_login($user);
        gp_log_action($pdo, 'LOGIN_SUCCESS', 'user', (int)$user['id'], 'User logged in successfully');
        redirect(auth_post_login_redirect($user));
    } else {
        $error = 'Invalid username or password.';
        gp_log_action($pdo, 'LOGIN_FAILED', 'user', 0, 'Failed login attempt for username: ' . $username);
        usleep(250000);
    }
}

$page_title = 'Login';
include __DIR__ . '/../includes/header.php';
?>
<div style="max-width:460px;margin:40px auto">
  <div class="card">
    <div class="page-header-title" style="margin-bottom:14px">
      <h1>Login</h1>
      <span>GoPools CRM</span>
    </div>

    <?php if ($error): ?>
      <div class="alert-danger"><?php echo h($error); ?></div>
    <?php endif; ?>

    <form method="post" autocomplete="off">
      <div class="form-grid" style="grid-template-columns:1fr">
        <div class="form-group">
          <label>Username</label>
          <input type="text" name="username" required autocomplete="username">
        </div>
        <div class="form-group">
          <label>Password</label>
          <input type="password" name="password" required autocomplete="current-password">
        </div>
      </div>
      <div class="form-actions">
        <button class="btn btn-primary" type="submit">Login</button>
      </div>
    </form>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
