<?php
session_start();
require_once '../config/database.php';

if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin','teacher'])) {
    header('Location: ../login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD']==='POST') {
    $id = (int)($_POST['id'] ?? 0);
    if ($id>0) {
        try {
            $pdo->beginTransaction();
            // Load attachments to delete files from disk
            $stmt = $pdo->prepare("SELECT file_path FROM notices_attachments WHERE notice_id=?");
            $stmt->execute([$id]);
            $files = $stmt->fetchAll(PDO::FETCH_COLUMN);
            // Delete notice (attachments rows will cascade)
            $stmt = $pdo->prepare("DELETE FROM notices WHERE id=?");
            $stmt->execute([$id]);
            // Delete files from disk
            foreach ($files as $fp) {
                if ($fp) { @unlink(dirname(__DIR__) . DIRECTORY_SEPARATOR . $fp); }
            }
            $pdo->commit();
            header('Location: index.php');
            exit();
        } catch (Exception $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            $_SESSION['error'] = 'ডিলিট ব্যর্থ: ' . $e->getMessage();
            header('Location: index.php');
            exit();
        }
    }
}
header('Location: index.php');