<?php
// ─── Savuki Drilling — Auth / Token Validation ────────────────────────────
// Token is accepted from POST body or GET param: ?token=xxx

class Auth {

    /**
     * Validate the incoming token and return the user record.
     * Calls Response::error() and exits if invalid.
     */
    public static function require(): array {
        $token = trim($_POST['token'] ?? $_GET['token'] ?? '');
        if (!$token) Response::error('Authentication required.', 401);

        $db  = DB::get();
        $row = $db->row(
            "SELECT t.user_id, t.expires_at,
                    u.username, u.user_type, u.team_id
             FROM   api_tokens t
             JOIN   users u ON u.record_id = t.user_id
             WHERE  t.token = ?
               AND  t.expires_at > NOW()",
            [$token]
        );

        if (!$row) Response::error('Invalid or expired token. Please log in again.', 401);

        // Bump last_used timestamp
        $db->run("UPDATE api_tokens SET last_used = NOW() WHERE token = ?", [$token]);

        return array_merge($row, ['token' => $token]);
    }

    /** Generate a secure random token string. */
    public static function generateToken(): string {
        return bin2hex(random_bytes(32));
    }

    /** Hash a plain-text password the same way the existing system does. */
    public static function hashPassword(string $plain): string {
        return hash('sha256', $plain);
    }

    /** Verify a plain-text password against a stored hash. */
    public static function verifyPassword(string $plain, string $stored): bool {
        return hash_equals($stored, self::hashPassword($plain));
    }

    /** Normalise user_type to lowercase for consistent role checks. */
    public static function role(array $user): string {
        return strtolower(trim($user['user_type']));
    }
}
