<?php
header('Content-Type: application/json');
session_start();

require __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/config.php';

// TODO: valide admin aqui (ex: $_SESSION['usuario_tipo'] === 'admin')

$title  = trim($_POST['title'] ?? 'Notificação');
$body   = trim($_POST['body'] ?? '');
$url    = trim($_POST['url'] ?? '/');
$target = $_POST['target'] ?? 'all';

if ($body === '') {
  echo json_encode(['success' => false, 'message' => 'Mensagem vazia']);
  exit;
}

use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;

$webPush = new WebPush([
  'VAPID' => [
    'subject' => VAPID_SUBJECT,
    'publicKey' => VAPID_PUBLIC_KEY,
    'privateKey' => VAPID_PRIVATE_KEY,
  ],
]);

$payload = json_encode([
  'title' => $title,
  'body'  => $body,
  'url'   => $url,
  'icon'  => '/imagens/icon-192.png'
]);

// Filtra alvo
$sql = "SELECT id, endpoint, p256dh, auth FROM push_subscriptions";
if ($target === 'logged') $sql .= " WHERE usuario_id IS NOT NULL";
if ($target === 'guest')  $sql .= " WHERE usuario_id IS NULL";

$subs = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

foreach ($subs as $s) {
  $subscription = Subscription::create([
    'endpoint' => $s['endpoint'],
    'keys' => [
      'p256dh' => $s['p256dh'],
      'auth'   => $s['auth'],
    ]
  ]);

  $webPush->queueNotification($subscription, $payload);
}

$sent = 0; $failed = 0;

foreach ($webPush->flush() as $report) {
  if ($report->isSuccess()) {
    $sent++;
  } else {
    $failed++;
    // remove endpoints inválidos
    $endpoint = (string) $report->getRequest()->getUri();
    $del = $pdo->prepare("DELETE FROM push_subscriptions WHERE endpoint = ?");
    $del->execute([$endpoint]);
  }
}

echo json_encode([
  'success' => true,
  'message' => "Notificação enviada.",
  'sent' => $sent,
  'failed' => $failed
]);
