<?php
// push_notification.php
// Web Push Notification menggunakan Service Worker

include "config.php";

// Fungsi untuk mendapatkan semua token push user
function getPushTokens($conn, $user_id = null) {
    $sql = "SELECT token FROM push_subscriptions";
    if ($user_id !== null) {
        $sql .= " WHERE user_id = " . intval($user_id);
    }
    $result = mysqli_query($conn, $sql);
    $tokens = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $tokens[] = $row['token'];
    }
    return $tokens;
}

// Fungsi untuk menyimpan subscription
function savePushSubscription($conn, $user_id, $token) {
    $token = mysqli_real_escape_string($conn, $token);
    // Cek apakah sudah ada
    $check = mysqli_query($conn, "SELECT id FROM push_subscriptions WHERE user_id = $user_id AND token = '$token'");
    if (mysqli_num_rows($check) == 0) {
        $insert = mysqli_query($conn, "INSERT INTO push_subscriptions (user_id, token, created_at) VALUES ($user_id, '$token', NOW())");
        return $insert ? true : false;
    }
    return true;
}

// Fungsi untuk mengirim push notification
function kirimPushNotification($message, $title = 'Sistem Absensi', $user_id = null, $url = null) {
    global $conn;
    
    $tokens = getPushTokens($conn, $user_id);
    if (empty($tokens)) {
        return "⚠️ Tidak ada subscriber push notification";
    }
    
    $vapidPublicKey = getVapidPublicKey();
    $vapidPrivateKey = getVapidPrivateKey();
    
    if (!$vapidPublicKey || !$vapidPrivateKey) {
        return "⚠️ VAPID key belum diset. Generate di https://web-push-codelab.glitch.me/";
    }
    
    $payload = json_encode([
        'title' => $title,
        'body' => $message,
        'icon' => '/assets/icon-192.png',
        'badge' => '/assets/badge-72x72.png',
        'url' => $url ?? '/scan_wa_api.php',
        'timestamp' => time()
    ]);
    
    $success_count = 0;
    foreach ($tokens as $token) {
        // Decode token
        $subscription = json_decode($token, true);
        if (!$subscription) continue;
        
        // Kirim ke endpoint
        $result = sendWebPush($subscription, $payload, $vapidPublicKey, $vapidPrivateKey);
        if ($result === true) {
            $success_count++;
        } else {
            // Jika token expired, hapus
            if (strpos($result, 'expired') !== false || strpos($result, '410') !== false) {
                $escaped_token = mysqli_real_escape_string($conn, $token);
                mysqli_query($conn, "DELETE FROM push_subscriptions WHERE token = '$escaped_token'");
            }
        }
    }
    
    return "📱 Push notification dikirim ke {$success_count} perangkat";
}

// Fungsi untuk mendapatkan VAPID key dari database
function getVapidPublicKey() {
    global $conn;
    $result = mysqli_query($conn, "SELECT vapid_public_key FROM profil_sekolah LIMIT 1");
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['vapid_public_key'] ?? '';
    }
    return '';
}

function getVapidPrivateKey() {
    global $conn;
    $result = mysqli_query($conn, "SELECT vapid_private_key FROM profil_sekolah LIMIT 1");
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        return $row['vapid_private_key'] ?? '';
    }
    return '';
}

// Fungsi untuk generate VAPID keys (gunakan library web-push)
function generateVapidKeys() {
    // Menggunakan openssl untuk generate
    $publicKey = '';
    $privateKey = '';
    
    // Generate VAPID keys menggunakan library atau manual
    // Untuk production gunakan: composer require minishlink/web-push
    
    return ['publicKey' => $publicKey, 'privateKey' => $privateKey];
}

// Fungsi untuk send Web Push dengan JWT
function sendWebPush($subscription, $payload, $publicKey, $privateKey) {
    $endpoint = $subscription['endpoint'] ?? '';
    if (empty($endpoint)) return false;
    
    $auth = $subscription['keys']['auth'] ?? '';
    $p256dh = $subscription['keys']['p256dh'] ?? '';
    
    if (empty($auth) || empty($p256dh)) return false;
    
    // Generate salt untuk enkripsi
    $salt = random_bytes(16);
    
    // Untuk implementasi lengkap, gunakan library:
    // composer require minishlink/web-push
    // Atau implementasi manual dengan enkripsi
    
    // Buat JWT untuk VAPID
    $jwt = generateVapidJWT($publicKey, $privateKey, $endpoint);
    
    // Enkripsi payload (sederhana)
    // Untuk production, gunakan enkripsi yang benar dengan AES-GCM
    
    // Headers yang diperlukan
    $headers = [
        'Content-Type: application/octet-stream',
        'Content-Encoding: aes128gcm',
        'TTL: 86400',
        'Authorization: WebPush ' . $jwt
    ];
    
    $ch = curl_init($endpoint);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode >= 200 && $httpCode < 300) {
        return true;
    } else if ($httpCode == 410 || $httpCode == 404) {
        return "expired";
    }
    
    return "Error: HTTP {$httpCode}";
}

// Generate VAPID JWT
function generateVapidJWT($publicKey, $privateKey, $endpoint) {
    $header = base64url_encode(json_encode([
        'alg' => 'ES256',
        'typ' => 'JWT'
    ]));
    
    $url_parts = parse_url($endpoint);
    $origin = $url_parts['scheme'] . '://' . $url_parts['host'];
    
    $payload = base64url_encode(json_encode([
        'aud' => $origin,
        'exp' => time() + 86400,
        'sub' => 'mailto:admin@sekolah.com'
    ]));
    
    $signature = '';
    // Untuk signature, gunakan openssl dengan curve P-256
    
    return $header . '.' . $payload . '.' . $signature;
}

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

// API endpoint untuk subscribe push notification
if (isset($_POST['action']) && $_POST['action'] === 'subscribe') {
    session_start();
    header('Content-Type: application/json');
    
    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
    
    $subscription = json_decode($_POST['subscription'], true);
    if (!$subscription) {
        echo json_encode(['success' => false, 'message' => 'Invalid subscription']);
        exit;
    }
    
    $user_id = $_SESSION['user_id'];
    $token = mysqli_real_escape_string($conn, json_encode($subscription));
    
    if (savePushSubscription($conn, $user_id, $token)) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to save']);
    }
    exit;
}

// API untuk get VAPID public key
if (isset($_GET['action']) && $_GET['action'] === 'getVapidKey') {
    header('Content-Type: application/json');
    $key = getVapidPublicKey();
    echo json_encode(['vapidPublicKey' => $key]);
    exit;
}
?>