<?php
require_once '../includes/config.php';
require_once '../includes/auth.php';

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

// Check authentication
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'DELETE':
            // Delete document
            if (!isset($_GET['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'message' => 'Document ID required']);
                exit();
            }
            
            $docId = $_GET['id'];
            $userId = $_SESSION['user_id'];
            
            // Verify ownership (students can only delete their own docs)
            $stmt = $pdo->prepare("SELECT student_id FROM student_documents WHERE id = ?");
            $stmt->execute([$docId]);
            $doc = $stmt->fetch();
            
            if (!$doc) {
                http_response_code(404);
                echo json_encode(['success' => false, 'message' => 'Document not found']);
                exit();
            }
            
            if (hasRole('student') && $doc['student_id'] != $userId) {
                http_response_code(403);
                echo json_encode(['success' => false, 'message' => 'Not authorized']);
                exit();
            }
            
            // Get file path before deletion
            $stmt = $pdo->prepare("SELECT file_path FROM student_documents WHERE id = ?");
            $stmt->execute([$docId]);
            $filePath = $stmt->fetchColumn();
            
            // Delete from database
            $stmt = $pdo->prepare("DELETE FROM student_documents WHERE id = ?");
            $stmt->execute([$docId]);
            
            // Delete file
            if ($filePath && file_exists('../' . $filePath)) {
                unlink('../' . $filePath);
            }
            
            echo json_encode(['success' => true]);
            break;
            
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>