<?php
declare(strict_types=1);
require __DIR__ . '/../partials/auth.php';
require_once __DIR__ . '/../../config/database.php';

$pdo = getDbConnection();
$currentUserId = (int)($_SESSION['user_id'] ?? 0);
$currentUserRole = strtolower(trim((string)($_SESSION['user_role'] ?? $_SESSION['role'] ?? 'teacher')));
$isAdmin = $currentUserRole === 'admin';
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);

if ($id) {
    $stmt = $pdo->prepare('SELECT created_by_teacher_id FROM flashcard_sets WHERE id = ? LIMIT 1');
    $stmt->execute([$id]);
    $owner = $stmt->fetchColumn();
    $allowed = $isAdmin || ($owner !== false && $owner !== null && (int)$owner === $currentUserId);
    if (!$allowed) {
        http_response_code(403);
        $_SESSION['flashcards_message'] = 'Bạn chỉ có thể xóa Flashcard Set do chính mình tạo.';
        $_SESSION['flashcards_message_type'] = 'error';
        header('Location:index.php');
        exit;
    }
    $s = $pdo->prepare('DELETE FROM flashcard_sets WHERE id = ?');
    $s->execute([$id]);
}
header('Location:index.php?deleted=1');
