<?php
// generate_vapid_simple.php
// Generate VAPID keys menggunakan metode alternatif

function generateVapidKeysSimple() {
    // Coba metode yang lebih sederhana
    $config = [
        "digest_alg" => "sha256",
        "private_key_bits" => 2048,
        "private_key_type" => OPENSSL_KEYTYPE_RSA, // Gunakan RSA sebagai fallback
    ];
    
    $res = openssl_pkey_new($config);
    if (!$res) {
        return ['error' => 'Gagal generate key dengan RSA'];
    }
    
    // Export private key
    if (!openssl_pkey_export($res, $privKey)) {
        return ['error' => 'Gagal export private key'];
    }
    
    // Get public key
    $pubKey = openssl_pkey_get_details($res);
    if (!$pubKey) {
        return ['error' => 'Gagal get public key'];
    }
    
    // Encode ke base64 URL
    $publicKeyBase64 = rtrim(strtr(base64_encode($pubKey['key']), '+/', '-_'), '=');
    $privateKeyBase64 = rtrim(strtr(base64_encode($privKey), '+/', '-_'), '=');
    
    return [
        'publicKey' => $publicKeyBase64,
        'privateKey' => $privateKeyBase64,
        'publicKeyPem' => $pubKey['key'],
        'privateKeyPem' => $privKey
    ];
}

$keys = generateVapidKeysSimple();

echo "========================================\n";
echo "     VAPID KEYS GENERATED (RSA)\n";
echo "========================================\n\n";

if (isset($keys['error'])) {
    echo "❌ Error: " . $keys['error'] . "\n";
    echo "\nCoba solusi lain:\n";
    echo "1. Install OpenSSL di sistem Windows\n";
    echo "2. Gunakan Node.js untuk generate (lihat di bawah)\n";
} else {
    echo "✅ PUBLIC KEY:\n";
    echo $keys['publicKey'] . "\n\n";
    
    echo "✅ PRIVATE KEY:\n";
    echo $keys['privateKey'] . "\n\n";
    
    echo "========================================\n";
    echo "SQL UPDATE (copy dan jalankan di phpMyAdmin):\n";
    echo "========================================\n\n";
    echo "UPDATE profil_sekolah SET \n";
    echo "  vapid_public_key = '" . $keys['publicKey'] . "',\n";
    echo "  vapid_private_key = '" . $keys['privateKey'] . "'\n";
    echo "WHERE id = 1;\n";
}
?>