<?php

require_once __DIR__ . '/../../core/bootstrap.php';

/*
|--------------------------------------------------------------------------
| Push Notification Worker
|--------------------------------------------------------------------------
| Sends pushes in controlled batches
| Prevents Firebase push storms
*/

$batch_size = 50;

/* Fetch pending pushes */

$stmt = $pdo->prepare("
    SELECT *
    FROM push_queue
    WHERE status = 'pending'
    ORDER BY id ASC
    LIMIT ?
");

$stmt->bindValue(1,$batch_size,PDO::PARAM_INT);
$stmt->execute();

$pushes = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach($pushes as $push){

    try{

        sendPush($pdo,$push);

        $stmt = $pdo->prepare("
            UPDATE push_queue
            SET status='sent', processed_at=NOW()
            WHERE id=?
        ");

        $stmt->execute([$push['id']]);

    }catch(Throwable $e){

        $stmt = $pdo->prepare("
            UPDATE push_queue
            SET attempts = attempts + 1,
                status = IF(attempts > 3,'failed','pending')
            WHERE id = ?
        ");

        $stmt->execute([$push['id']]);
    }
}

function sendPush($pdo,$push)
{

    $stmt = $pdo->prepare("
        SELECT device_token
        FROM device_tokens
        WHERE company_id = ?
    ");

    $stmt->execute([$push['company_id']]);

    $tokens = $stmt->fetchAll(PDO::FETCH_COLUMN);

    foreach($tokens as $token){

        sendFirebasePush($token,$push['push_type'],$push['breakdown_id']);

    }
}