<?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: ./');
    exit;
}

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

$id = $_POST['id'] ?? null;
if ($id) {
    try {
        $db = getDB();
        
        // Hapus user yang terkait terlebih dahulu
        $stmt = $db->prepare("DELETE FROM users WHERE ibu_hamil_id = ?");
        $stmt->execute([$id]);
        
        // Hapus data ibu hamil
        $stmt = $db->prepare("DELETE FROM ibu_hamil WHERE id = ?");
        $stmt->execute([$id]);
        
        setFlash('success', 'Data Ibu Hamil berhasil dihapus.');
    } catch (PDOException $e) {
        setFlash('error', 'Gagal menghapus data: ' . $e->getMessage());
    }
}

header('Location: ./');
exit;
