<?php
declare(strict_types=1);
namespace Helpers;

use Config\Database;
use RuntimeException;

final class Auth
{
    public static function token(): ?string
{
    $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
    if (preg_match('/Bearer\s+(.*)$/i', $header, $m)) return trim($m[1]);
    
    // Also check X-Auth-Token header
    $xAuthToken = $_SERVER['HTTP_X_AUTH_TOKEN'] ?? '';
    if ($xAuthToken) return trim($xAuthToken);
    
    return null;
}

    public static function user(): ?array
    {
        $token = self::token();
        if (!$token) return null;
        $hash = hash('sha256', $token);
        $db = Database::connection();
        $stmt = $db->prepare('SELECT u.* FROM auth_tokens t JOIN users u ON u.id=t.user_id WHERE t.token_hash=:hash AND t.expires_at > NOW() AND u.status="active" LIMIT 1');
        $stmt->execute(['hash' => $hash]);
        $user = $stmt->fetch();
        return $user ?: null;
    }

    public static function requireUser(): array
    {
        $user = self::user();
        if (!$user) throw new RuntimeException('Authentication required');
        return $user;
    }

    public static function isAdmin(array $user): bool
    {
        return in_array($user['role'] ?? 'customer', ['admin', 'manager'], true);
    }
}
