<?php
require_once 'db_pdo.php';
require_once 'auth.php';
require_once 'haversine_helper.php';
require_once 'penduduk_feature_helper.php';
require_once 'rumah_ibadah_helper.php';
require_admin_login(true);
header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Input tidak valid']);
    exit;
}

try {
    assertRumahIbadahNotDuplicate($pdo, $input);

    $stmt = $pdo->prepare("INSERT INTO rumah_ibadah (nama, jenis, kontak, alamat, lat, lng, radius) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $input['nama'],
        $input['jenis'],
        $input['kontak'],
        $input['alamat'],
        $input['lat'],
        $input['lng'],
        $input['radius'] ?? 500
    ]);

    $id = $pdo->lastInsertId();
    recalculateAllPendudukCoverage($pdo);
    refreshAllPriorityScores($pdo);

    echo json_encode(['success' => true, 'id' => $id]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
