<?php
function admin_colony_ids($conn, $adminId)
{
    $ids = array();
    $query = $conn->query("SELECT colony_id FROM admin_colonies WHERE admin_id='".(int)$adminId."' ORDER BY colony_id");
    if($query) {
        while($row = $query->fetch_assoc()) {
            $ids[] = (int)$row['colony_id'];
        }
    }
    return $ids;
}

function save_admin_colonies($conn, $adminId, $colonyIds, $divisionId, $departmentId = 0)
{
    $adminId = (int)$adminId;
    $divisionId = (int)$divisionId;
    $departmentId = (int)$departmentId;
    $conn->query("DELETE FROM admin_colonies WHERE admin_id='".$adminId."'");

    foreach(array_unique(array_map('intval', (array)$colonyIds)) as $colonyId) {
        if($colonyId <= 0) {
            continue;
        }
        $where = "id='".$colonyId."' AND status='1' AND division_id='".$divisionId."'";
        $valid = $conn->query("SELECT id FROM colonies WHERE ".$where." LIMIT 1");
        if($valid && $valid->num_rows > 0) {
            $conn->query("INSERT IGNORE INTO admin_colonies (admin_id, colony_id) VALUES ('".$adminId."', '".$colonyId."')");
        }
    }
}
?>
