<?php
// push_sync.php
// سینک نوتیف‌ها و اعلان‌هایی که pushed_at ندارن → ارسال Web Push

declare(strict_types=1);

require __DIR__ . '/db.php';
require __DIR__ . '/push_notifications.php';

header('Content-Type: text/plain; charset=utf-8');

try {
    $sentNotif = syncUserNotifications($pdo);
    $sentAnn   = syncAnnouncements($pdo);

    echo "OK\n";
    echo "notifications_sent={$sentNotif}\n";
    echo "announcements_sent={$sentAnn}\n";
} catch (Throwable $e) {
    http_response_code(500);
    echo "ERROR: " . $e->getMessage() . "\n";
}

/**
 * نوتیف‌های شخصی که هنوز pushed_at ندارن رو پوش می‌کند
 */
function syncUserNotifications(PDO $pdo): int
{
    $sql = "
        SELECT id, user_id, type, title, body
        FROM notifications
        WHERE is_read = 0
          AND (pushed_at IS NULL OR pushed_at = '0000-00-00 00:00:00')
        ORDER BY id ASC
        LIMIT 100
    ";

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

    if (!$rows) {
        return 0;
    }

    $totalSent = 0;
    $doneIds   = [];

    foreach ($rows as $r) {
        $notifId = (int)($r['id'] ?? 0);
        $userId  = (int)($r['user_id'] ?? 0);
        if ($notifId <= 0 || $userId <= 0) {
            continue;
        }

        $title = trim((string)($r['title'] ?? '')) ?: 'اعلان جدید دیمینت';
        $body  = trim((string)($r['body']  ?? ''));
        $url   = '/index.php?tab=panel';

        $payload = [
            'title' => $title,
            'body'  => $body,
            'url'   => $url,
            'type'  => $r['type'] ?? 'system',
            'id'    => $notifId,
             'icon'  => '/assets/logo192.png'
        ];

        $sent = diminet_push_to_user($pdo, $userId, $payload);

        $doneIds[] = $notifId;
        $totalSent += $sent;
    }

    if ($doneIds) {
        $placeholders = implode(',', array_fill(0, count($doneIds), '?'));
        $stmt = $pdo->prepare("
            UPDATE notifications
            SET pushed_at = NOW()
            WHERE id IN ($placeholders)
        ");
        $stmt->execute($doneIds);
    }

    return $totalSent;
}

/**
 * اعلان‌های عمومی که هنوز pushed_at ندارن رو پوش می‌کند
 */
function syncAnnouncements(PDO $pdo): int
{
    $sql = "
        SELECT id, title, body, visible_scope
        FROM announcements
        WHERE is_active = 1
          AND (pushed_at IS NULL OR pushed_at = '0000-00-00 00:00:00')
        ORDER BY id ASC
        LIMIT 50
    ";

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

    if (!$rows) {
        return 0;
    }

    $totalSent = 0;
    $doneIds   = [];

    foreach ($rows as $r) {
        $annId = (int)($r['id'] ?? 0);
        if ($annId <= 0) {
            continue;
        }

        $scope = (int)($r['visible_scope'] ?? 0);
        // 0 = همه، 1 = فقط لاگین‌ها
        $onlyLoggedIn = ($scope === 1);

        $title = trim((string)($r['title'] ?? '')) ?: 'اطلاعیه دیمینت';
        $body  = trim((string)($r['body']  ?? ''));
        $url   = '/index.php';

        $payload = [
            'title' => $title,
            'body'  => $body,
            'url'   => $url,
            'type'  => 'announcement',
            'id'    => $annId,
             'icon'  => '/assets/logo192.png'
        ];

        $sent = diminet_push_broadcast($pdo, $payload, $onlyLoggedIn);

        $doneIds[] = $annId;
        $totalSent += $sent;
    }

    if ($doneIds) {
        $placeholders = implode(',', array_fill(0, count($doneIds), '?'));
        $stmt = $pdo->prepare("
            UPDATE announcements
            SET pushed_at = NOW()
            WHERE id IN ($placeholders)
        ");
        $stmt->execute($doneIds);
    }

    return $totalSent;
}
