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

$conn = new Database();
$assignment_mgr = new Assignment();

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

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

    // Get assignment details
    $assignment = $assignment_mgr->getAssignmentById($assignment_id);

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

    // Check permission (only admin, superadmin or creator can delete)

    $user_type = $assignment_mgr->checkUserType($_SESSION['username']);
    if (
        !in_array($user_type, ['admin', 'superadmin']) &&
        $assignment->created_by != $_SESSION['username']
    ) {
        echo json_encode(['success' => false, 'message' => 'You do not have permission to delete this assignment']);
        exit();
    }

    // Delete attachment file if exists
    if ($assignment->attachment_url && file_exists('../' . $assignment->attachment_url)) {
        unlink('../' . $assignment->attachment_url);
    }

    // Delete assignment (cascades to submissions and related data)
    $result = $assignment_mgr->deleteAssignment($assignment_id);

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

