<?php
declare(strict_types=1);

final class Auth {
  public function __construct(private PDO $db) {}

  public function user(): ?array {
    if (!isset($_SESSION['uid'])) return null;

    $stmt = $this->db->prepare("
      SELECT id, full_name, email, phone, is_active
      FROM users
      WHERE id=?
    ");
    $stmt->execute([$_SESSION['uid']]);
    $u = $stmt->fetch();

    return $u ?: null;
  }

  public function requireLogin(): void {
    if ($this->user()) return;

    global $config;
    $bp = rtrim(($config['app']['base_path'] ?? ''), '/');

    header('Location: ' . ($bp ? $bp : '') . '/login');
    exit;
  }

  public function login(string $email, string $password): array {
    $stmt = $this->db->prepare("
      SELECT id, password_hash, is_active
      FROM users
      WHERE email=?
      LIMIT 1
    ");
    $stmt->execute([$email]);
    $row = $stmt->fetch();

    if (!$row || (int)$row['is_active'] !== 1) {
      return ['ok'=>false, 'msg'=>'Invalid credentials.'];
    }

    if (!password_verify($password, (string)$row['password_hash'])) {
      return ['ok'=>false, 'msg'=>'Invalid credentials.'];
    }

    $_SESSION['uid'] = (int)$row['id'];

    // update last login timestamp
    $this->db->prepare("
      UPDATE users
      SET last_login_at = NOW()
      WHERE id = ?
    ")->execute([(int)$row['id']]);

    return ['ok'=>true];
  }

  public function logout(): void {
    $_SESSION = [];

    if (ini_get('session.use_cookies')) {
      $params = session_get_cookie_params();
      setcookie(
        session_name(),
        '',
        time() - 42000,
        $params['path'],
        $params['domain'],
        $params['secure'],
        $params['httponly']
      );
    }

    session_destroy();
  }
}