<?php
require_once __DIR__.'/../../config/functions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    $csrf = $_POST['csrf_token'] ?? '';

    if (!verifyCsrfToken($csrf)) {
        jsonResponse(false, 'Ralat keselamatan (CSRF).');
    }

    $stmt = $pdo->prepare("SELECT * FROM informasi WHERE id = ?");
    $stmt->execute([$id]);
    $info = $stmt->fetch();

    if (!$info) {
        jsonResponse(false, 'Rekod tidak dijumpai.');
    }

    // Hak akses: Superadmin atau pemilik
    if (!isSuperAdmin() && (!empty($_SESSION['pegawai_id']) && $_SESSION['pegawai_id'] != $info['pegawai_id'])) {
        jsonResponse(false, 'Anda tiada kebenaran untuk memadam rekod ini.');
    }

    // Padam lampiran jika ada
    if ($info['lampiran']) {
        deleteFile('documents/' . $info['lampiran']);
    }

    $delete = $pdo->prepare("DELETE FROM informasi WHERE id = ?");
    if ($delete->execute([$id])) {
        logActivity('padam', 'informasi', $id, 'Padam informasi: ' . $info['tajuk']);
        jsonResponse(true, 'Informasi berjaya dipadam.');
    } else {
        jsonResponse(false, 'Gagal memadam informasi.');
    }
}
