<?php
// =============================================================
//  include/notice_helpers.php
//
//  Shared by: notice_ajax.php (post_notice -> email blast)
// =============================================================

/**
 * Resolve the actual email recipients for a notice, honouring its audience
 * and (when set) department/unit scope — mirrors the department/unit
 * derivation already used for scoping elsewhere (include/scope_helper.php,
 * app/dashboard.php's nrsScope()/srdScope()):
 *   - a nurse's "current" department/unit = their In_Progress rotation schedule row
 *   - a student's "current" department/unit = their Ongoing rotation detail row
 *     (department is one hop further via units.department_id)
 * Only Active accounts are included — the live notice board itself doesn't
 * filter by status (session usertype alone gates access), but blasting email
 * to inactive/cancelled accounts would be wrong, so we filter here.
 *
 * @return array of ['email'=>.., 'name'=>..], de-duplicated by email
 */
function resolveNoticeRecipients(mysqli $conn, string $audience, ?int $scopeDeptId, ?string $scopeUnitIds): array
{
    $recipients = []; // keyed by email to de-dupe

    $unitIdList = null;
    if (!empty($scopeUnitIds)) {
        $clean = preg_replace('/[^0-9,]/', '', $scopeUnitIds);
        if ($clean !== '') $unitIdList = $clean;
    }

    if (in_array($audience, ['nurses', 'both'], true)) {
        $sql = "
            SELECT DISTINCT rn.firstname, rn.surname, rn.email
            FROM rotation_nurses rn
            JOIN nurse_rotations nr ON nr.rotation_nurse_id = rn.id
            JOIN nurse_rotation_schedules nrs ON nrs.nurse_rotation_id = nr.id
            WHERE rn.status = 'Active' AND rn.cancelled_at IS NULL AND nrs.status = 'In_Progress'
        ";
        if ($scopeDeptId) $sql .= ' AND nrs.department_id = ' . (int)$scopeDeptId;
        if ($unitIdList)  $sql .= " AND nrs.unit_id IN ($unitIdList)";
        $res = $conn->query($sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                if (!empty($row['email'])) {
                    $recipients[$row['email']] = ['email' => $row['email'], 'name' => trim($row['firstname'] . ' ' . $row['surname'])];
                }
            }
        }
    }

    if (in_array($audience, ['students', 'both'], true)) {
        $sql = "
            SELECT DISTINCT cs.firstname, cs.surname, cs.email
            FROM clinical_students cs
            JOIN student_rotation_details srd ON srd.clinical_student_id = cs.id
            JOIN clinical_rotations cr ON srd.clinical_rotation_id = cr.id
        ";
        if ($scopeDeptId) $sql .= ' JOIN units u ON srd.unit_id = u.id';
        $sql .= " WHERE cs.status = 'Active' AND srd.status = 'Ongoing'";
        if ($scopeDeptId) $sql .= ' AND u.department_id = ' . (int)$scopeDeptId;
        if ($unitIdList)  $sql .= " AND srd.unit_id IN ($unitIdList)";
        $res = $conn->query($sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                if (!empty($row['email'])) {
                    $recipients[$row['email']] = ['email' => $row['email'], 'name' => trim($row['firstname'] . ' ' . $row['surname'])];
                }
            }
        }
    }

    if ($audience === 'staff') {
        $has_dept_col = $conn->query("SHOW COLUMNS FROM users LIKE 'department_id'");
        $has_dept_col = $has_dept_col && $has_dept_col->num_rows > 0;

        $sql = "
            SELECT firstname, surname, email
            FROM users
            WHERE status = 'Active'
              AND usertype IN ('Admin','Chief_Preceptor','Preceptor','Nurse_Manager','In_Charge')
        ";
        if ($has_dept_col && $scopeDeptId) $sql .= ' AND department_id = ' . (int)$scopeDeptId;
        $res = $conn->query($sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                if (!empty($row['email'])) {
                    $recipients[$row['email']] = ['email' => $row['email'], 'name' => trim($row['firstname'] . ' ' . $row['surname'])];
                }
            }
        }
    }

    return array_values($recipients);
}
