<?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 = (int)($_GET['id'] ?? 0);

if ($id <= 0) {
    header('Location: index.php');
    exit;
}

$ownerStmt = $pdo->prepare("SELECT created_by_teacher_id FROM topics WHERE id = ? LIMIT 1");
$ownerStmt->execute([$id]);
$owner = $ownerStmt->fetchColumn();
if ($owner === false) { http_response_code(404); die('Topic not found'); }
if (!$isAdmin && ($owner === null || (int)$owner !== $currentUserId)) { http_response_code(403); die('Bạn không có quyền xóa Topic này.'); }

$stmt = $pdo->prepare("
    UPDATE topics
    SET
        status = 'inactive',
        updated_at = NOW()
    WHERE id = ?
");
$stmt->execute([$id]);

header('Location: index.php');
exit;
