<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Server A: api/laporan_kehamilan_api.php
// Pastikan db_connect.php sudah ada dan menginisialisasi $pdo

header('Content-Type: application/json');

// Mengizinkan CORS (Cross-Origin Resource Sharing)
// SESUAIKAN DENGAN DOMAIN SERVER BIDAN DESA ANDA UNTUK KEAMANAN!
// HINDARI '*' DI LINGKUNGAN PRODUKSI UNTUK KEAMANAN MAKSIMAL
header("Access-Control-Allow-Origin: *"); // Ganti * dengan https://bidan.domainanda.com
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, X-API-Key, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    // Tangani preflight OPTIONS request untuk CORS
    exit();
}

require_once 'db_connect.php'; // Koneksi ke database

// --- API Key Validation ---
function validateApiKey($pdo) {
    $api_key = '';
    if (isset($_SERVER['HTTP_X_API_KEY'])) {
        $api_key = $_SERVER['HTTP_X_API_KEY'];
    } elseif (isset($_GET['api_key'])) {
        $api_key = $_GET['api_key'];
    }

    if (empty($api_key)) {
        http_response_code(401); // Unauthorized
        echo json_encode(array('success' => false, 'message' => 'API Key is missing.'));
        exit();
    }

    $valid_api_key_from_config = 'p3513150201'; // GANTI DENGAN API KEY YANG SANGAT KUAT!

    if ($api_key !== $valid_api_key_from_config) {
        http_response_code(403); // Forbidden
        echo json_encode(array('success' => false, 'message' => 'Invalid API Key.'));
        exit();
    }
    return true;
}

validateApiKey($pdo); // Validasi API Key untuk setiap request

$method = $_SERVER['REQUEST_METHOD'];
// Untuk PHP 5.6, lebih aman mengelola endpoint via $_GET['endpoint']
$requested_endpoint = isset($_GET['endpoint']) ? $_GET['endpoint'] : '';


// --- Endpoint GET: Mengambil Laporan Kehamilan (TIDAK ADA PERUBAHAN DI SINI) ---
if ($method === 'GET') {
    if ($requested_endpoint === 'laporan_kehamilan' || $requested_endpoint === '') {
        $query = "SELECT * FROM laporan_kehamilan";
        $params = array();
        $conditions = array();

        // Filter berdasarkan ID
        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            $conditions[] = "id = :id";
            $params[':id'] = (int)$_GET['id'];
        }
        // Filter berdasarkan NIK
        if (isset($_GET['nik']) && !empty($_GET['nik'])) {
            $conditions[] = "nik = :nik";
            $params[':nik'] = $_GET['nik'];
        }
        // Filter berdasarkan status verifikasi (misal: hanya yang belum diverifikasi)
        if (isset($_GET['verif_status']) && in_array($_GET['verif_status'], array('0', '1'))) {
            $conditions[] = "verif = :verif_status";
            $params[':verif_status'] = (int)$_GET['verif_status'];
        }
        // Filter berdasarkan status laporan (misal: 'pending', 'aktif')
        if (isset($_GET['status']) && !empty($_GET['status'])) {
            $conditions[] = "status = :status";
            $params[':status'] = $_GET['status'];
        }

        // --- TAMBAHKAN FILTER BERDASARKAN DESA DI SINI ---
        if (isset($_GET['desa']) && !empty($_GET['desa'])) {
            $conditions[] = "desa = :desa";
            $params[':desa'] = $_GET['desa'];
        }
        // --------------------------------------------------

        if (count($conditions) > 0) {
            $query .= " WHERE " . implode(' AND ', $conditions);
        }

        $query .= " ORDER BY tanggal_lapor DESC";

        // Pagination
        $limit = isset($_GET['limit']) && is_numeric($_GET['limit']) ? (int)$_GET['limit'] : 10;
        $offset = isset($_GET['offset']) && is_numeric($_GET['offset']) ? (int)$_GET['offset'] : 0;
        $query .= " LIMIT :limit OFFSET :offset";
        $params[':limit'] = $limit;
        $params[':offset'] = $offset;

        try {
            $stmt = $pdo->prepare($query);
            foreach ($params as $key => &$val) {
                $param_type = PDO::PARAM_STR;
                if (is_int($val)) {
                    $param_type = PDO::PARAM_INT;
                } elseif (is_bool($val)) {
                    $val = (int)$val;
                    $param_type = PDO::PARAM_INT;
                }
                $stmt->bindParam($key, $val, $param_type);
            }
            $stmt->execute();
            $laporan = $stmt->fetchAll(PDO::FETCH_ASSOC);

            echo json_encode(array('success' => true, 'data' => $laporan));

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Database error: ' . $e->getMessage()));
        }
    } else {
        http_response_code(404);
        echo json_encode(array('success' => false, 'message' => 'Endpoint not found.'));
    }
}
// --- Endpoint POST: Verifikasi Laporan & Update Status Daftar ---
elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if ($requested_endpoint === 'verify') {
        if (!isset($input['id']) || !is_numeric($input['id'])) {
            http_response_code(400);
            echo json_encode(array('success' => false, 'message' => 'Laporan ID is required.'));
            exit();
        }
        if (!isset($input['verif']) || !in_array($input['verif'], array(0, 1))) {
            http_response_code(400);
            echo json_encode(array('success' => false, 'message' => 'Verification status (verif) is required and must be 0 or 1.'));
            exit();
        }

        $laporan_id = (int)$input['id'];
        $verif_status = (int)$input['verif'];

        $status_laporan = isset($input['status']) ? $input['status'] : null;
        $catatan_bidan = isset($input['catatan_bidan']) ? $input['catatan_bidan'] : null;

        $tanggal_verif = date('Y-m-d H:i:s'); // Waktu verifikasi

        try {
            $query = "UPDATE laporan_kehamilan SET verif = :verif, tanggal_verif = :tanggal_verif";
            $params = array(
                ':verif' => $verif_status,
                ':tanggal_verif' => $tanggal_verif,
                ':id' => $laporan_id
            );

            if ($status_laporan !== null) {
                $query .= ", status = :status";
                $params[':status'] = $status_laporan;
            }
            if ($catatan_bidan !== null) {
                $query .= ", catatan_bidan = :catatan_bidan";
                $params[':catatan_bidan'] = $catatan_bidan;
            }

            $query .= " WHERE id = :id";

            $stmt = $pdo->prepare($query);
            foreach ($params as $key => &$val) {
                $param_type = PDO::PARAM_STR;
                if (is_int($val)) {
                    $param_type = PDO::PARAM_INT;
                }
                $stmt->bindParam($key, $val, $param_type);
            }
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                echo json_encode(array('success' => true, 'message' => 'Laporan updated successfully.'));
            } else {
                http_response_code(404);
                echo json_encode(array('success' => false, 'message' => 'Laporan not found or no changes made.'));
            }

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(array('success' => false, 'message' => 'Database error: ' . $e->getMessage()));
        }
    }
    // --- ENDPOINT BARU UNTUK UPDATE KOLOM 'DAFTAR' (TIDAK ADA PERUBAHAN PADA LOGIKA LAIN) ---
    elseif ($requested_endpoint === 'update_laporan_daftar') {
        if (!isset($input['id_laporan']) || !is_numeric($input['id_laporan'])) {
            http_response_code(400); // Bad Request
            echo json_encode(['success' => false, 'message' => 'Invalid JSON input or missing id_laporan.']);
            exit();
        }

        $id_laporan_to_update = (int)$input['id_laporan'];

        try {
            // Update kolom 'daftar' menjadi 1 (TRUE)
            $stmt = $pdo->prepare("UPDATE laporan_kehamilan SET daftar = 1 WHERE id = :id_laporan");
            $stmt->bindParam(':id_laporan', $id_laporan_to_update, PDO::PARAM_INT);
            $stmt->execute();

            if ($stmt->rowCount() > 0) {
                echo json_encode(['success' => true, 'message' => 'Status laporan berhasil diperbarui menjadi terdaftar.']);
            } else {
                // Laporan tidak ditemukan atau status sudah 1
                echo json_encode(['success' => false, 'message' => 'Laporan tidak ditemukan atau sudah terdaftar.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
    }
    // --- End of new endpoint ---
    else {
        http_response_code(404);
        echo json_encode(array('success' => false, 'message' => 'Endpoint not found.'));
    }
} else {
    http_response_code(405); // Method Not Allowed
    echo json_encode(array('success' => false, 'message' => 'Method Not Allowed.'));
}

?>