<?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 GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    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 view submissions
    if ($user_role !== 'teacher' && $user_role !== 'admin') {
        echo json_encode(['success' => false, 'message' => 'Access denied']);
        exit();
    }
    
    // Get assignment ID from query parameters
    $assignment_id = isset($_GET['assignment_id']) ? (int)$_GET['assignment_id'] : 0;
    
    if (!$assignment_id) {
        echo json_encode(['success' => false, 'message' => 'Assignment ID is required']);
        exit();
    }
    
    // Verify the assignment belongs to this teacher
    if ($user_role === 'teacher') {
        $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 access denied']);
            exit();
        }
    }
    
    // Get all submissions for this assignment
    $stmt = $pdo->prepare("
        SELECT 
            s.id,
            s.assignment_id,
            s.student_id,
            s.file_upload_id,
            s.submission_date,
            s.grade,
            s.feedback,
            s.status,
            st.first_name,
            st.last_name,
            st.student_id as student_code
        FROM assignment_submissions s
        JOIN students st ON s.student_id = st.id
        WHERE s.assignment_id = ?
        ORDER BY s.submission_date ASC
    ");
    $stmt->execute([$assignment_id]);
    $submissions = $stmt->fetchAll();
    
    echo json_encode(['success' => true, 'submissions' => $submissions]);
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error fetching submissions: ' . $e->getMessage()]);
}
?>