<?php

namespace Core;

class Auth
{
    const DEFAULT_PASSWORD = 'admin123';

    public static function startSession()
    {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    }

    public static function login($username, $password, $pdo)
    {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            self::startSession();
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            $_SESSION['force_password_change'] = self::isDefaultPasswordHash($user['password']);
            return true;
        }
        return false;
    }

    public static function logout()
    {
        self::startSession();
        session_destroy();
    }

    public static function check()
    {
        self::startSession();
        return isset($_SESSION['user_id']);
    }

    public static function needsPasswordReset()
    {
        self::startSession();
        return !empty($_SESSION['force_password_change']);
    }

    public static function clearPasswordResetFlag()
    {
        self::startSession();
        unset($_SESSION['force_password_change']);
    }

    public static function generateCsrfToken()
    {
        self::startSession();
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    public static function verifyCsrfToken($token)
    {
        self::startSession();
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }

    private static function isDefaultPasswordHash($hash)
    {
        return password_verify(self::DEFAULT_PASSWORD, $hash);
    }
}
