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

include 'koneksi.php';

// Cek koneksi
if ($koneksi->connect_error) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Koneksi database gagal: ' . $koneksi->connect_error]);
    exit;
}

// Cek apakah method POST dan parameter id tersedia
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Permintaan tidak valid.']);
    exit;
}

$id = intval($_POST['id']);
if ($id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'ID tidak valid.']);
    exit;
}

// Query hapus dengan prepared statement
$stmt = $koneksi->prepare("DELETE FROM absen WHERE id = ?");
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Gagal menyiapkan query: ' . $koneksi->error]);
    exit;
}

$stmt->bind_param('i', $id);

if ($stmt->execute()) {
    if ($stmt->affected_rows > 0) {
        echo json_encode(['success' => true, 'message' => 'Data berhasil dihapus.']);
    } else {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Data tidak ditemukan.']);
    }
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Gagal menghapus data: ' . $stmt->error]);
}

$stmt->close();
$koneksi->close();
?>
