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

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    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'];
    $user_role = $_SESSION['user_role'];
    
    // Only teachers and admins can delete assignments
    if ($user_role !== 'teacher' && $user_role !== 'admin') {
        echo json_encode(['success' => false, 'message' => 'Only teachers and admins can delete assignments']);
        exit();
    }
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['assignment_id'])) {
        echo json_encode(['success' => false, 'message' => 'Missing assignment ID']);
        exit();
    }
    
    $assignment_id = (int)$input['assignment_id'];
    
    // Verify the assignment exists and belongs to the teacher (or user is admin)
    if ($user_role === 'teacher') {
        // For teachers, check if they own this assignment
        $stmt = $pdo->prepare("
            SELECT id 
            FROM assignments 
            WHERE id = ? AND teacher_id = (SELECT id FROM teachers WHERE user_id = ?)
        ");
        $stmt->execute([$assignment_id, $user_id]);
        $assignment = $stmt->fetch();
        
        if (!$assignment) {
            echo json_encode(['success' => false, 'message' => 'Assignment not found or you do not have permission to delete it']);
            exit();
        }
    } else {
        // For admins, just check if assignment exists
        $stmt = $pdo->prepare("SELECT id FROM assignments WHERE id = ?");
        $stmt->execute([$assignment_id]);
        $assignment = $stmt->fetch();
        
        if (!$assignment) {
            echo json_encode(['success' => false, 'message' => 'Assignment not found']);
            exit();
        }
    }
    
    // Delete related submissions first (due to foreign key constraints)
    $stmt = $pdo->prepare("DELETE FROM assignment_submissions WHERE assignment_id = ?");
    $stmt->execute([$assignment_id]);
    
    // Delete the assignment
    $stmt = $pdo->prepare("DELETE FROM assignments WHERE id = ?");
    $result = $stmt->execute([$assignment_id]);
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Assignment deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete assignment']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error deleting assignment: ' . $e->getMessage()]);
}
?>