<?php
if (!defined('WD')) { define('WD', __DIR__ . '/../../'); }
require_once WD . '/vendor/autoload.php';
require_once WD . '/classes/webauthn.php';

use Webauthn\PublicKeyCredentialSource;

// Mock passkeys_o
if (!class_exists('objects\passkeys_o')) {
    // Need to define it in the expected namespace
    eval('
    namespace objects;
    class MockProperty {
        public $val;
        public function __construct($v) { $this->val = $v; }
        public function value() { return $this->val; }
        public function set($v) { }
    }
    class passkeys_o {
        public $credential_id, $public_key, $transports, $user_id, $sign_count;
        public function __construct($cid_b64, $pk_b64, $uid) {
            $this->credential_id = new MockProperty($cid_b64);
            $this->public_key = new MockProperty($pk_b64);
            $this->transports = new MockProperty([]);
            $this->user_id = new MockProperty($uid);
            $this->sign_count = new MockProperty(0);
        }
    }
    ');
}

// Helper to encode Base64URL
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// Simulate a successful registration (how it's stored in DB currently)
$raw_cid = random_bytes(16);
$b64_cid = base64url_encode($raw_cid);

// This is a fake public key for testing
$raw_pk = random_bytes(64); 
$b64_pk = base64url_encode($raw_pk);

$user_id = 123;
$passkey = new objects\passkeys_o($b64_cid, $b64_pk, $user_id);

$wa = new classes\webauthn();

// We'll use Reflection to access createSourceFromObject
$refl = new ReflectionClass($wa);
$method = $refl->getMethod('createSourceFromObject');
$method->setAccessible(true);

/** @var PublicKeyCredentialSource $source */
$source = $method->invoke($wa, $passkey);

echo "Stored Credential ID (Base64URL): $b64_cid\n";
echo "Source PublicKeyCredentialId (Hex): " . bin2hex($source->publicKeyCredentialId) . "\n";

if ($source->publicKeyCredentialId === $raw_cid) {
    echo "✔ Source ID matches raw binary ID\n";
} else {
    echo "✘ Source ID DOES NOT match raw binary ID.\n";
}

echo "Source UserHandle (Hex): " . bin2hex($source->userHandle) . "\n";
if ($source->userHandle === (string)$user_id) {
    echo "✔ Source UserHandle matches user_id string\n";
} else {
    echo "✘ Source UserHandle DOES NOT match user_id string\n";
}
