<?php
declare(strict_types=1);

function assertRumahIbadahNotDuplicate(PDO $pdo, array $input, ?int $ignoreId = null): void
{
    $nama = trim((string)($input['nama'] ?? ''));
    $jenis = trim((string)($input['jenis'] ?? ''));
    $lat = round((float)($input['lat'] ?? 0), 6);
    $lng = round((float)($input['lng'] ?? 0), 6);
    $allowedJenis = ['Masjid', 'Gereja', 'Pura', 'Vihara', 'Klenteng', 'Lainnya'];

    if ($nama === '' || $jenis === '' || !isset($input['lat'], $input['lng'])) {
        throw new InvalidArgumentException('Nama, jenis, dan lokasi rumah ibadah wajib diisi.');
    }

    if (!in_array($jenis, $allowedJenis, true)) {
        throw new InvalidArgumentException('Jenis rumah ibadah tidak valid.');
    }

    $sql = "
        SELECT id
        FROM rumah_ibadah
        WHERE LOWER(TRIM(nama)) = LOWER(TRIM(?))
          AND jenis = ?
          AND ROUND(lat, 6) = ?
          AND ROUND(lng, 6) = ?
    ";
    $params = [$nama, $jenis, $lat, $lng];

    if ($ignoreId !== null) {
        $sql .= " AND id <> ?";
        $params[] = $ignoreId;
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    if ($stmt->fetch()) {
        throw new InvalidArgumentException('Rumah ibadah dengan nama, jenis, dan lokasi yang sama sudah ada.');
    }
}
