<?php

require __DIR__.'/vendor/autoload.php';

$app = require_once __DIR__.'/bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

// Token from URL
$tokenString = '123|77UwxldKPVnbEiZPpBV2jP90AAzeKoy7AkDxcMWy410073d3';

echo "Testing Sanctum Token Authentication\n";
echo "=====================================\n\n";

// Parse token
[$id, $token] = explode('|', $tokenString, 2);

echo "Token ID: $id\n";
echo "Token Hash: " . substr($token, 0, 20) . "...\n\n";

// Check if token exists in database
$tokenModel = \Laravel\Sanctum\PersonalAccessToken::find($id);

if (!$tokenModel) {
    echo "❌ Token with ID $id does NOT exist in the database!\n";
    echo "\nLet's check what tokens exist:\n";
    
    $tokens = \Laravel\Sanctum\PersonalAccessToken::latest()->take(5)->get();
    echo "Latest 5 tokens in database:\n";
    foreach ($tokens as $t) {
        echo "  ID: {$t->id}, User ID: {$t->tokenable_id}, Name: {$t->name}, Created: {$t->created_at}\n";
    }
    exit(1);
}

echo "✓ Token found in database\n";
echo "  User ID: {$tokenModel->tokenable_id}\n";
echo "  Token Name: {$tokenModel->name}\n";
echo "  Created: {$tokenModel->created_at}\n";
echo "  Expires: " . ($tokenModel->expires_at ?? 'Never') . "\n\n";

// Check if token is expired
if ($tokenModel->expires_at && $tokenModel->expires_at->isPast()) {
    echo "❌ Token is EXPIRED!\n";
    echo "  Expired at: {$tokenModel->expires_at}\n";
    exit(1);
}

// Verify token hash
$hashedToken = hash('sha256', $token);
echo "Computed Hash: " . substr($hashedToken, 0, 20) . "...\n";
echo "Stored Hash: " . substr($tokenModel->token, 0, 20) . "...\n\n";

if (hash_equals($tokenModel->token, $hashedToken)) {
    echo "✓ Token hash matches!\n";
} else {
    echo "❌ Token hash does NOT match!\n";
    exit(1);
}

// Get the user
$user = $tokenModel->tokenable;
if ($user) {
    echo "\n✓ Token is valid for user:\n";
    echo "  ID: {$user->id}\n";
    echo "  Name: {$user->name}\n";
    echo "  Email: {$user->email}\n";
    echo "  Status: {$user->status}\n";
    
    if ($user->status !== 'active') {
        echo "\n❌ WARNING: User status is '{$user->status}', not 'active'!\n";
    }
} else {
    echo "\n❌ No user found for this token!\n";
    exit(1);
}

echo "\n✅ Token validation successful!\n";
