<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/nabila/includes/functions.php';

// Cek login
cek_login();

// Cek akses
if (!cek_akses('absensi', 'delete')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/absensi/index.php?error=" . urlencode("ID tidak valid!"));
    exit();
}

$id = (int)$_GET['id'];

// Ambil tanggal untuk redirect
$query = "SELECT tanggal FROM absensi WHERE id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/absensi/index.php?error=" . urlencode("Data absensi tidak ditemukan!"));
    exit();
}

$row = mysqli_fetch_assoc($result);
$tanggal = $row['tanggal'];

// Hapus data
$delete_query = "DELETE FROM absensi WHERE id = $id";
if (mysqli_query($conn, $delete_query)) {
    header("Location: " . BASE_URL . "/modules/absensi/index.php?tanggal=$tanggal&success=" . urlencode("Data absensi berhasil dihapus!"));
} else {
    header("Location: " . BASE_URL . "/modules/absensi/index.php?tanggal=$tanggal&error=" . urlencode("Gagal menghapus data absensi!"));
}
exit();
?>