<?php
session_start();
require_once 'includes/database.php';
require_once 'Classes/ELearning.php';

$conn = new Database();
$elearning = new ELearning();

if (!isset($_SESSION['username'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

if (isset($_POST['material_id'])) {
    $material_id = (int)$_POST['material_id'];

    // Get material details to delete file
    $material = $elearning->getMaterialById($material_id);

    if (!$material) {
        echo json_encode(['success' => false, 'message' => 'Material not found']);
        exit();
    }

    // Allow only admin or superadmin or the person who uploaded the material
    $user_type = $elearning->checkUserType($_SESSION['username']);
    if (
        !in_array($user_type, ['admin', 'superadmin']) &&
        $material->uploaded_by != $_SESSION['username']
    ) {
        echo json_encode(['success' => false, 'message' => 'You do not have permission to delete this material']);
        exit();
    }


    $file_path = $material->file_path ? '../' . $material->file_path : null;
    $result = $elearning->deleteMaterial($material_id, $file_path);

    echo json_encode($result);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
