<?php
session_start();
//require_once 'includes/config.php';
require_once '../admin/includes/database.php';
require_once 'Classes/Assignment.php';

$conn = new Database();
$assignment_mgr = new Assignment();

if (!isset($_SESSION['teacher'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (isset($_POST['grade_submission'])) {
    $submission_id = (int)$_POST['submission_id'];
    $marks = (float)$_POST['marks'];
    $feedback = htmlspecialchars(trim($_POST['feedback']));
    $graded_by = $_SESSION['teacher'];

    // Validate inputs
    if (empty($submission_id) || $marks < 0 || empty($feedback)) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Please fill all required fields
              </div>';
        exit();
    }

    // Validate feedback length
    if (strlen($feedback) < 10) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Feedback must be at least 10 characters
              </div>';
        exit();
    }

    // Get submission details
    $submission = $assignment_mgr->getSubmissionDetails($submission_id);

    if (!$submission) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Submission not found
              </div>';
        exit();
    }

    // Validate marks
    if ($marks > $submission->total_marks) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Marks cannot exceed total marks (' . $submission->total_marks . ')
              </div>';
        exit();
    }

    // Grade submission
    $result = $assignment_mgr->gradeSubmission($submission_id, $marks, $feedback, $graded_by);

    if ($result['success']) {
        echo '<div class="alert alert-success">
                <i class="fas fa-check-circle"></i> ' . $result['message'] . '
              </div>';
    } else {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> ' . $result['message'] . '
              </div>';
    }
} else {
    echo '<div class="alert alert-danger">Invalid request</div>';
}
