<?php
require './conn.php';


// Fetch an incomplete broadcast
$b = $mysqli->query("SELECT * FROM broadcasts WHERE completed = 0 ORDER BY id ASC LIMIT 1")
            ->fetch_assoc();

if (!$b) {
    exit("No broadcasts pending.\n");
}

$batchSize = 5;
$lastId = intval($b['next_batch_user_id']);

$stmt = $mysqli->prepare("
    SELECT id, email FROM users
    WHERE id > ?
    ORDER BY id ASC
    LIMIT ?
");
$stmt->bind_param("ii", $lastId, $batchSize);
$stmt->execute();
$result = $stmt->get_result();

$usersProcessed = 0;

while ($u = $result->fetch_assoc()) {
    $usersProcessed++;
    $userId = $u['id'];
    $email  = $u['email'];

  if ($b['type'] === 'email') {

    $htmlMessage = emailTemplate($b['subject'], nl2br(htmlspecialchars($b['message'])));

    sendMail($email, $b['subject'], $htmlMessage);
}


    if ($b['type'] === 'notification') {
        addNotification($userId, $b['message'], $b['subject']);
    }

    $lastId = $userId;
}

$noMoreUsers = ($usersProcessed < $batchSize);

// Update broadcast record
if ($noMoreUsers) {
    $mysqli->query("UPDATE broadcasts SET completed = 1 WHERE id = {$b['id']}");
} else {
    $stmt2 = $mysqli->prepare("UPDATE broadcasts SET next_batch_user_id = ? WHERE id = ?");
    $stmt2->bind_param("ii", $lastId, $b['id']);
    $stmt2->execute();
}

echo "Processed $usersProcessed users. Completed: " . ($noMoreUsers ? "YES" : "NO") . "\n";
