TKK_E32230273/save_subscription.php

73 lines
2.7 KiB
PHP

<?php
// save_subscription.php
session_start();
require 'koneksi.php';
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['subscription'])) {
echo json_encode(['status' => 'error', 'message' => 'Valid subscription object not found.']);
exit;
}
// Ensure user is logged in
$id_account = isset($_SESSION['id_account']) ? (int)$_SESSION['id_account'] : 0;
if ($id_account === 0) {
if (isset($_SESSION['user_id'])) {
$id_account = (int)$_SESSION['user_id'];
} else {
echo json_encode(['status' => 'error', 'message' => 'User not logged in.']);
exit;
}
}
$sub = $data['subscription'];
$endpoint = $sub['endpoint'] ?? '';
$p256dh = $sub['keys']['p256dh'] ?? '';
$auth = $sub['keys']['auth'] ?? '';
if (empty($endpoint) || empty($p256dh) || empty($auth)) {
echo json_encode(['status' => 'error', 'message' => 'Incomplete subscription keys.']);
exit;
}
try {
// Auto-create table if it doesn't exist on the hosting server
$pdo->exec("CREATE TABLE IF NOT EXISTS push_subscriptions (
id INT AUTO_INCREMENT PRIMARY KEY,
id_account INT NOT NULL,
endpoint TEXT NOT NULL,
p256dh VARCHAR(255) NOT NULL,
auth VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// Check if THIS exact browser subscription already exists
$stmt = $pdo->prepare("SELECT id FROM push_subscriptions WHERE endpoint = ?");
$stmt->execute([$endpoint]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC);
if ($existing) {
// Update to make sure id_account is current (in case multiple accounts login on same browser)
$upd = $pdo->prepare("UPDATE push_subscriptions SET id_account = ? WHERE id = ?");
$upd->execute([$id_account, $existing['id']]);
echo json_encode(['status' => 'success', 'message' => 'Subscription updated.']);
} else {
// Insert new subscription
$ins = $pdo->prepare("INSERT INTO push_subscriptions (id_account, endpoint, p256dh, auth) VALUES (?, ?, ?, ?)");
$ins->execute([$id_account, $endpoint, $p256dh, $auth]);
echo json_encode(['status' => 'success', 'message' => 'Subscription saved.']);
}
} catch (PDOException $e) {
$err = "[" . date('Y-m-d H:i:s') . "] Save Subscription DB Error: " . $e->getMessage() . "\n";
file_put_contents(__DIR__ . '/push_error.log', $err, FILE_APPEND);
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}