<?php
require_once __DIR__ . '/Database.php';
class Auth extends Database {
     public function __construct() {

   }
    public function attempt($username, $password) {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        $instance = parent::getInstance();
        $db = $instance->getConnection();
        $stmt = $db->prepare("SELECT id,username,password,name,role FROM users WHERE username = :username LIMIT 1");
        $stmt->execute([':username' => $username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        parent::DisConnect($db);
        if ($user && password_verify($password, $user['password'])) {
            session_regenerate_id(true);
            $_SESSION['user'] = [
                'id' => $user['id'],
                'username' => $user['username'],
                'name' => $user['name'],
                'role' => $user['role']
            ];
            return true;
        }
        return false;
    }

    public function logout() {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        unset($_SESSION['user']);
        session_destroy();
    }

    public function guard() {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        return $_SESSION['user'] ?? null;
    }
}
