<?php
require_once __DIR__ . '/../../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../../config/config.php';
require_once __DIR__ . '/../../../functions/csrf.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . BASE_URL . '/admin/ibu_hamil/');
    exit;
}

if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    setFlash('error', 'Invalid CSRF Token.');
    header('Location: ' . BASE_URL . '/admin/ibu_hamil/');
    exit;
}

$id           = (int)($_POST['id'] ?? 0);
$ibu_hamil_id = (int)($_POST['ibu_hamil_id'] ?? 0);
$back         = $_POST['back'] ?? 'detail';

if ($id) {
    try {
        $db = getDB();
        $stmt = $db->prepare("DELETE FROM kunjungan_posyandu WHERE id = ? AND ibu_hamil_id = ?");
        $stmt->execute([$id, $ibu_hamil_id]);
        setFlash('success', 'Data kunjungan dihapus.');
    } catch (PDOException $e) {
        setFlash('error', 'Gagal menghapus kunjungan: ' . $e->getMessage());
    }
}

$redirect = ($back === 'kunjungan')
    ? BASE_URL . '/admin/kunjungan/'
    : BASE_URL . '/admin/ibu_hamil/detail.php?id=' . $ibu_hamil_id;
header('Location: ' . $redirect);
exit;
