<?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();
        
        $stmt = $db->prepare("SELECT gambar FROM edukasi WHERE id = ?");
        $stmt->execute([$id]);
        $edu = $stmt->fetch();
        
        if($edu && $edu['gambar'] && file_exists('../../assets/uploads/edukasi/' . $edu['gambar'])) {
            unlink('../../assets/uploads/edukasi/' . $edu['gambar']);
        }

        $stmt = $db->prepare("DELETE FROM edukasi WHERE id = ?");
        $stmt->execute([$id]);
        
        setFlash('success', 'Artikel berhasil dihapus.');
    } catch (PDOException $e) {
        setFlash('error', 'Gagal menghapus data: ' . $e->getMessage());
    }
}

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