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

header('Content-Type: application/json');

// Check if user is logged in and is admin/teacher
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'teacher')) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    // Validate required fields
    if (!$input || !isset($input['id'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $material_id = (int)$input['id'];
    
    // Check if material exists and user has permission to delete it
    if ($_SESSION['user_role'] === 'admin') {
        // Admins can delete any material
        $stmt = $pdo->prepare("SELECT id FROM learning_materials WHERE id = ?");
        $stmt->execute([$material_id]);
    } else {
        // Teachers can only delete their own materials
        $stmt = $pdo->prepare("SELECT id FROM learning_materials WHERE id = ? AND created_by = ?");
        $stmt->execute([$material_id, $user_id]);
    }
    
    if (!$stmt->fetch()) {
        echo json_encode(['success' => false, 'message' => 'Learning material not found or access denied']);
        exit();
    }
    
    // Delete learning material (will cascade delete related views)
    $stmt = $pdo->prepare("DELETE FROM learning_materials WHERE id = ?");
    $result = $stmt->execute([$material_id]);
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Learning material deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete learning material']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error deleting learning material: ' . $e->getMessage()]);
}
?>