<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

require "../../config/database.php";
require "../../helpers/response.php";

$sppg_id = isset($_GET["sppg_id"]) ? (int) $_GET["sppg_id"] : 0;

$where = "WHERE status = 'Aktif'";

if ($sppg_id > 0) {
    $where .= " AND (sppg_id = $sppg_id OR sppg_id IS NULL)";
}

$query = "
    SELECT
        id,
        sppg_id,
        nama_puskesmas,
        provinsi,
        kabupaten,
        kecamatan,
        alamat,
        penanggung_jawab,
        kontak,
        status,
        created_at
    FROM puskesmas
    $where
    ORDER BY nama_puskesmas ASC
";

$result = $conn->query($query);

if (!$result) {
    response(false, "Gagal mengambil data puskesmas: " . $conn->error, []);
}

$data = [];

while ($row = $result->fetch_assoc()) {
    $row["id"] = (int) $row["id"];
    $row["sppg_id"] = $row["sppg_id"] !== null ? (int) $row["sppg_id"] : null;
    $data[] = $row;
}

response(true, "Data puskesmas berhasil diambil", $data);

?>