<?php
// generate_vapid.php
// Generate VAPID keys untuk Web Push Notification

function generateVapidKeys() {
    // Cek apakah OpenSSL tersedia
    if (!extension_loaded('openssl')) {
        return ['error' => 'OpenSSL extension tidak tersedia'];
    }
    
    // Cek versi OpenSSL
    $openssl_version = OPENSSL_VERSION_TEXT;
    echo "OpenSSL Version: $openssl_version\n\n";
    
    // Metode 1: Generate dengan config yang lebih kompatibel
    $config = [
        'digest_alg' => 'sha256',
        'private_key_bits' => 2048,
        'private_key_type' => OPENSSL_KEYTYPE_EC,
        'curve_name' => 'prime256v1'
    ];
    
    // Coba generate dengan berbagai metode
    $privateKey = null;
    
    // Metode 1: Standard
    try {
        $privateKey = openssl_pkey_new($config);
    } catch (Exception $e) {
        echo "Metode 1 gagal: " . $e->getMessage() . "\n";
    }
    
    // Metode 2: Tanpa config
    if (!$privateKey) {
        try {
            $privateKey = openssl_pkey_new();
        } catch (Exception $e) {
            echo "Metode 2 gagal: " . $e->getMessage() . "\n";
        }
    }
    
    // Metode 3: Generate RSA (fallback)
    if (!$privateKey) {
        try {
            $privateKey = openssl_pkey_new([
                'private_key_bits' => 2048,
                'private_key_type' => OPENSSL_KEYTYPE_RSA
            ]);
        } catch (Exception $e) {
            echo "Metode 3 gagal: " . $e->getMessage() . "\n";
        }
    }
    
    if (!$privateKey) {
        return ['error' => 'Gagal generate private key'];
    }
    
    // Export private key
    if (!openssl_pkey_export($privateKey, $privateKeyPem)) {
        return ['error' => 'Gagal export private key'];
    }
    
    // Get public key details
    $publicKeyDetails = openssl_pkey_get_details($privateKey);
    if (!$publicKeyDetails) {
        return ['error' => 'Gagal mendapatkan public key details'];
    }
    
    // Extract public key
    $publicKeyBase64 = '';
    $privateKeyBase64 = '';
    
    // Untuk EC key
    if (isset($publicKeyDetails['ec']) && isset($publicKeyDetails['ec']['x']) && isset($publicKeyDetails['ec']['y'])) {
        $x = $publicKeyDetails['ec']['x'];
        $y = $publicKeyDetails['ec']['y'];
        $publicKeyHex = '04' . bin2hex($x) . bin2hex($y);
        $publicKeyBase64 = rtrim(strtr(base64_encode(hex2bin($publicKeyHex)), '+/', '-_'), '=');
        $privateKeyBase64 = rtrim(strtr(base64_encode($privateKeyPem), '+/', '-_'), '=');
    } 
    // Untuk RSA key
    else if (isset($publicKeyDetails['key'])) {
        // Extract public key from PEM
        $publicKeyPem = $publicKeyDetails['key'];
        $publicKeyBase64 = rtrim(strtr(base64_encode($publicKeyPem), '+/', '-_'), '=');
        $privateKeyBase64 = rtrim(strtr(base64_encode($privateKeyPem), '+/', '-_'), '=');
    }
    
    if (empty($publicKeyBase64) || empty($privateKeyBase64)) {
        return ['error' => 'Gagal encode keys'];
    }
    
    return [
        'publicKey' => $publicKeyBase64,
        'privateKey' => $privateKeyBase64,
        'publicKeyPem' => $publicKeyDetails['key'] ?? '',
        'privateKeyPem' => $privateKeyPem
    ];
}

// Jalankan generate
echo "========================================\n";
echo "     GENERATE VAPID KEYS\n";
echo "========================================\n\n";

$keys = generateVapidKeys();

if (isset($keys['error'])) {
    echo "❌ Error: " . $keys['error'] . "\n\n";
    echo "Solusi:\n";
    echo "1. Pastikan OpenSSL terinstall di PHP\n";
    echo "2. Cek file php.ini: extension=openssl\n";
    echo "3. Restart XAMPP/WAMP\n";
    echo "4. Atau gunakan VAPID keys dari https://web-push-codelab.glitch.me/\n";
} else {
    echo "✅ VAPID KEYS GENERATED SUCCESSFULLY!\n\n";
    echo "========================================\n";
    echo "PUBLIC KEY (untuk client):\n";
    echo "========================================\n";
    echo $keys['publicKey'] . "\n\n";
    
    echo "========================================\n";
    echo "PRIVATE KEY (untuk server):\n";
    echo "========================================\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";
}
?>