<?php
/* ============================================================================
 *  push_subscribe.php — store / remove a browser's push subscription for the
 *  logged-in user, and send a test push. Called by assets/push.js.
 * ==========================================================================*/
session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/notify.php';

if (!isset($_SESSION['user_id'])) { echo json_encode(['ok'=>false,'error'=>'not logged in']); exit; }
$userId = (int)$_SESSION['user_id'];

$in = json_decode(file_get_contents('php://input'), true) ?: [];
$action = $in['action'] ?? '';

if ($action === 'subscribe') {
    $endpoint = trim($in['endpoint'] ?? '');
    $p256dh   = trim($in['p256dh'] ?? '');
    $auth     = trim($in['auth'] ?? '');
    if ($endpoint === '' || $p256dh === '' || $auth === '') { echo json_encode(['ok'=>false,'error'=>'missing keys']); exit; }
    try {
        $pdo->prepare("INSERT INTO push_subscriptions (user_id,endpoint,p256dh,auth,ua,created_at)
                       VALUES (?,?,?,?,?,NOW())
                       ON DUPLICATE KEY UPDATE user_id=VALUES(user_id), p256dh=VALUES(p256dh), auth=VALUES(auth), ua=VALUES(ua)")
            ->execute([$userId,$endpoint,$p256dh,$auth, mb_substr($_SERVER['HTTP_USER_AGENT'] ?? '',0,255)]);
        echo json_encode(['ok'=>true]);
    } catch (Throwable $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()]); }
    exit;
}

if ($action === 'unsubscribe') {
    $endpoint = trim($in['endpoint'] ?? '');
    try { $pdo->prepare("DELETE FROM push_subscriptions WHERE user_id=? AND endpoint=?")->execute([$userId,$endpoint]); } catch (Throwable $e) {}
    echo json_encode(['ok'=>true]); exit;
}

if ($action === 'test') {
    try {
        $st = $pdo->prepare("SELECT COUNT(*) FROM push_subscriptions WHERE user_id=?");
        $st->execute([$userId]); $n = (int)$st->fetchColumn();
        if ($n === 0) { echo json_encode(['ok'=>false,'error'=>'no devices subscribed']); exit; }
        notify_user($pdo, $userId, '🔔 Test notification', 'If you can see this, alerts are working!', 'company/dashboard.php');
        echo json_encode(['ok'=>true,'sent'=>$n]);
    } catch (Throwable $e) { echo json_encode(['ok'=>false,'error'=>$e->getMessage()]); }
    exit;
}

echo json_encode(['ok'=>false,'error'=>'unknown action']);