<?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 grade submissions
    if ($user_role !== 'teacher' && $user_role !== 'admin') {
        echo json_encode(['success' => false, 'message' => 'Access denied']);
        exit();
    }
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['submission_id']) || !isset($input['grade']) || !isset($input['feedback'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $submission_id = (int)$input['submission_id'];
    $grade = (float)$input['grade'];
    $feedback = trim($input['feedback']);
    
    // Validate grade
    if ($grade < 0) {
        echo json_encode(['success' => false, 'message' => 'Grade cannot be negative']);
        exit();
    }
    
    // Verify the submission exists and belongs to an assignment this teacher can access
    if ($user_role === 'teacher') {
        $stmt = $pdo->prepare("
            SELECT asub.id
            FROM assignment_submissions asub
            JOIN assignments a ON asub.assignment_id = a.id
            JOIN teachers t ON a.teacher_id = t.id
            WHERE asub.id = ? AND t.user_id = ?
        ");
        $stmt->execute([$submission_id, $user_id]);
    } else {
        // Admins can grade any submission
        $stmt = $pdo->prepare("
            SELECT id
            FROM assignment_submissions
            WHERE id = ?
        ");
        $stmt->execute([$submission_id]);
    }
    
    $submission = $stmt->fetch();
    
    if (!$submission) {
        echo json_encode(['success' => false, 'message' => 'Submission not found or access denied']);
        exit();
    }
    
    // Update the submission with grade and feedback
    $stmt = $pdo->prepare("
        UPDATE assignment_submissions 
        SET grade = ?, feedback = ?, status = 'graded'
        WHERE id = ?
    ");
    $result = $stmt->execute([$grade, $feedback, $submission_id]);
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Submission graded successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to grade submission']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error grading submission: ' . $e->getMessage()]);
}
?>