<?php
// =============================================================
//  include/notification_queue.php
//
//  Enqueue helpers for the notification_queue table (see
//  scripts/create_notification_queue.sql). Used by bulk operations that
//  would otherwise send many SMS/emails synchronously inside one HTTP
//  request. A cron job (scripts/process_notification_queue.php) drains
//  the queue on a schedule.
//
//  Deliberately NOT used by the single-record Add flows — those send one
//  SMS + one email per submit, which is fast enough to stay synchronous
//  and give the admin an immediate pass/fail result.
// =============================================================

require_once __DIR__ . '/settings_helper.php'; // enqueuePush()'s getSetting('firebase_enabled', ...) check

/**
 * Queue an email notification. Silently no-ops on an invalid/empty
 * address rather than throwing, matching sendAccountEmail()'s behavior.
 */
function enqueueEmail(mysqli $conn, string $email, string $subject, string $heading, array $lines): bool
{
    if (trim($email) === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) return false;

    $stmt = $conn->prepare("
        INSERT INTO notification_queue (channel, recipient, subject, heading, body_lines_json)
        VALUES ('email', ?, ?, ?, ?)
    ");
    if (!$stmt) return false;
    $json = json_encode($lines);
    $stmt->bind_param('ssss', $email, $subject, $heading, $json);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}

/**
 * Queue an SMS notification.
 */
function enqueueSms(mysqli $conn, string $phone, string $message): bool
{
    if (trim($phone) === '') return false;

    $stmt = $conn->prepare("
        INSERT INTO notification_queue (channel, recipient, sms_message)
        VALUES ('sms', ?, ?)
    ");
    if (!$stmt) return false;
    $stmt->bind_param('ss', $phone, $message);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}

/**
 * Queue a push notification for an account (not a specific device token —
 * an account can have several, registered via
 * api/v1/auth/register_device.php into device_push_tokens; the worker
 * resolves current tokens at send time). $recipient reuses the existing
 * varchar column as "{account_table}:{account_id}" rather than adding a
 * new column pair for something that's just a polymorphic reference, the
 * same shape credentials.owner_table/owner_id already uses elsewhere in
 * this schema.
 *
 * $title reuses the 'subject' column, $body reuses 'sms_message' — same
 * reasoning: this is one more notification shape riding the existing
 * queue/table rather than a parallel one, not a repurposing that changes
 * what those columns mean for 'sms'/'email' rows.
 *
 * No-ops (returns false) without inserting anything if Firebase isn't
 * configured yet — see services/FirebaseServiceProvider.php's header
 * comment — so callers can call this unconditionally alongside
 * enqueueSms() without needing to check readiness themselves.
 */
function enqueuePush(mysqli $conn, string $accountTable, int $accountId, string $title, string $body): bool
{
    if (!in_array($accountTable, ['users', 'rotation_nurses', 'clinical_students'], true)) return false;
    if (!(bool)getSetting('firebase_enabled', false, $conn)) return false;

    $recipient = $accountTable . ':' . $accountId;
    $stmt = $conn->prepare("
        INSERT INTO notification_queue (channel, recipient, subject, sms_message)
        VALUES ('push', ?, ?, ?)
    ");
    if (!$stmt) return false;
    $stmt->bind_param('sss', $recipient, $title, $body);
    $ok = $stmt->execute();
    $stmt->close();
    return $ok;
}
