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

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

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Check if user is instructor or admin
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['instructor', 'admin'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Access denied']);
    exit;
}

$db = getDB();

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);
$submissionId = $input['submission_id'] ?? null;
$grade = $input['grade'] ?? null;
$feedback = $input['feedback'] ?? '';

if (!$submissionId || $grade === null) {
    echo json_encode(['success' => false, 'error' => 'Submission ID and grade are required']);
    exit;
}

// Validate grade
if (!is_numeric($grade) || $grade < 0 || $grade > 100) {
    echo json_encode(['success' => false, 'error' => 'Grade must be a number between 0 and 100']);
    exit;
}

try {
    // Verify the submission belongs to the instructor's course
    $stmt = $db->prepare("
        SELECT asub.id
        FROM assignment_submissions asub
        JOIN course_lessons cl ON asub.lesson_id = cl.id
        JOIN courses c ON cl.course_id = c.id
        WHERE asub.id = ? AND c.instructor_id = ?
    ");
    $stmt->execute([$submissionId, $_SESSION['user_id']]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$submission) {
        echo json_encode(['success' => false, 'error' => 'Submission not found or access denied']);
        exit;
    }

    // Update the submission with grade and feedback
    $stmt = $db->prepare("
        UPDATE assignment_submissions
        SET grade = ?, feedback = ?, status = 'graded', graded_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$grade, $feedback, $submissionId]);

    echo json_encode(['success' => true, 'message' => 'Assignment graded successfully']);

} catch (Exception $e) {
    error_log('Grade assignment error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'An error occurred while grading the assignment']);
}
?>