<?php
require __DIR__ . '/_bootstrap.php';

$licenseKey = input('license_key');
$machineId  = input('machine_id');

if ($licenseKey === '' || $machineId === '') {
    respond(['notifications' => []], 400);
}

$lic = findLicenseByKey($licenseKey);
if (!$lic) {
    respond(['notifications' => []]);
}

$pdo = db();
$out = [];

// ── 1) Auto license-expiry warning (no admin action needed) ──────────────
if ($lic['status'] === 'active' && $lic['expires_at']) {
    $remainingDays = (int) ceil((strtotime($lic['expires_at']) - time()) / 86400);

    if ($remainingDays >= 0 && $remainingDays <= EXPIRY_WARNING_DAYS) {
        // Bucketed by day count, so it naturally re-appears once per day
        // as the countdown changes, without spamming on every poll.
        $syntheticId = "expiry-{$lic['id']}-{$remainingDays}";
        $chk = $pdo->prepare('SELECT 1 FROM notification_reads WHERE notification_id = ? AND machine_id = ?');
        $chk->execute([$syntheticId, $machineId]);
        if (!$chk->fetch()) {
            $out[] = [
                'id'          => $syntheticId,
                'title'       => $remainingDays === 0
                    ? 'Your license expires today'
                    : "Your license expires in {$remainingDays} day" . ($remainingDays === 1 ? '' : 's'),
                'body'        => 'Renew now to keep uninterrupted access to all features.',
                'link'        => null,
                'accentColor' => '#fbbf24',
                'type'        => 'expiry',
            ];
        }
    } elseif ($remainingDays < 0) {
        // Already expired — single-fire (not repeated every day).
        $syntheticId = "expired-{$lic['id']}";
        $chk = $pdo->prepare('SELECT 1 FROM notification_reads WHERE notification_id = ? AND machine_id = ?');
        $chk->execute([$syntheticId, $machineId]);
        if (!$chk->fetch()) {
            $out[] = [
                'id'          => $syntheticId,
                'title'       => 'Your license has expired',
                'body'        => 'Renew now to restore access to your account.',
                'link'        => null,
                'accentColor' => '#f87171',
                'type'        => 'expiry',
            ];
        }
    }
}

// ── 2) Admin broadcasts (promos / announcements) not yet seen by this device ──
$stmt = $pdo->prepare(
    "SELECT n.* FROM notifications n
     WHERE (n.target_license_id IS NULL OR n.target_license_id = ?)
       AND NOT EXISTS (
           SELECT 1 FROM notification_reads r
           WHERE r.notification_id = CAST(n.id AS TEXT) AND r.machine_id = ?
       )
     ORDER BY n.created_at ASC
     LIMIT 5"
);
$stmt->execute([$lic['id'], $machineId]);

foreach ($stmt->fetchAll() as $n) {
    $out[] = [
        'id'          => (string) $n['id'],
        'title'       => $n['title'],
        'body'        => $n['body'],
        'link'        => $n['link'] ?: null,
        'imageUrl'    => $n['image_url'] ?: null,
        'accentColor' => $n['accent_color'] ?: null,
        'type'        => $n['type'],
    ];
}

respond(['notifications' => $out]);
