<?php
// admin/grading.php - Manual Grading with Company, Exam, Date Filters
require_once '../config/config.php';
require_login();

$action = $_GET['action'] ?? 'list';
$student_exam_id = $_GET['student_exam_id'] ?? null;

// Get filter parameters
$filter_exam = $_GET['exam_id'] ?? '';
$filter_company = $_GET['company'] ?? '';
$filter_date_from = $_GET['date_from'] ?? '';
$filter_date_to = $_GET['date_to'] ?? '';
$filter_status = $_GET['status'] ?? ''; // pending, graded, all

// Handle Grade Submission
if ($action === 'grade' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $answer_id = $_POST['answer_id'];
    $marks = floatval($_POST['marks']);
    $feedback = $_POST['feedback'] ?? null;
    $is_correct = $marks > 0 ? 1 : 0;
    
    $stmt = $pdo->prepare("
        UPDATE student_answers 
        SET partial_marks = ?, is_correct = ?, feedback = ?, graded_by = ?, graded_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$marks, $is_correct, $feedback, $_SESSION['admin_id'] ?? 1, $answer_id]);
    
    if ($student_exam_id) {
        recalculateExamResults($pdo, $student_exam_id);
    }
    
    set_flash('success', 'Answer graded successfully!');
    redirect("admin/grading.php?action=grade_exam&student_exam_id=$student_exam_id");
}

function recalculateExamResults($pdo, $student_exam_id) {
    $stmt = $pdo->prepare("
        SELECT sa.*, q.marks as max_marks, q.auto_grade
        FROM student_answers sa
        JOIN questions q ON sa.question_id = q.id
        WHERE sa.student_exam_id = ?
    ");
    $stmt->execute([$student_exam_id]);
    $answers = $stmt->fetchAll();
    
    $correct = 0;
    $wrong = 0;
    $unanswered = 0;
    $obtained = 0;
    
    foreach ($answers as $ans) {
        if (empty($ans->selected_answer) && empty($ans->answer_text)) {
            $unanswered++;
            continue;
        }
        
        if ($ans->auto_grade) {
            if ($ans->is_correct) {
                $correct++;
                $obtained += $ans->max_marks;
            } else {
                $wrong++;
            }
        } else {
            if ($ans->partial_marks !== null) {
                $obtained += $ans->partial_marks;
                if ($ans->partial_marks > 0) $correct++;
                else $wrong++;
            }
        }
    }
    
    $stmt = $pdo->prepare("SELECT e.* FROM student_exams se JOIN exams e ON se.exam_id = e.id WHERE se.id = ?");
    $stmt->execute([$student_exam_id]);
    $exam = $stmt->fetch();
    
    $percentage = ($exam->total_marks > 0) ? ($obtained / $exam->total_marks) * 100 : 0;
    $pass_pct = ($exam->total_marks > 0) ? ($exam->passing_marks / $exam->total_marks) * 100 : 0;
    $result = ($percentage >= $pass_pct) ? 'pass' : 'fail';
    
    $stmt = $pdo->prepare("
        UPDATE student_exams 
        SET obtained_marks = ?, percentage = ?, correct_answers = ?, wrong_answers = ?, unanswered = ?, result = ?
        WHERE id = ?
    ");
    $stmt->execute([round($obtained, 2), round($percentage, 2), $correct, $wrong, $unanswered, $result, $student_exam_id]);
}

// Get all exams for filter dropdown
$all_exams = $pdo->query("SELECT id, title FROM exams ORDER BY title")->fetchAll();

// Get all unique companies for filter dropdown
$all_companies = $pdo->query("SELECT DISTINCT company FROM students WHERE company IS NOT NULL AND company != '' ORDER BY company")->fetchAll();

// Build filtered query for submissions
$where_conditions = ["se.status = 'completed'"];
$params = [];

if (!empty($filter_exam)) {
    $where_conditions[] = "se.exam_id = ?";
    $params[] = $filter_exam;
}

if (!empty($filter_company)) {
    $where_conditions[] = "s.company = ?";
    $params[] = $filter_company;
}

if (!empty($filter_date_from)) {
    $where_conditions[] = "DATE(se.submitted_at) >= ?";
    $params[] = $filter_date_from;
}

if (!empty($filter_date_to)) {
    $where_conditions[] = "DATE(se.submitted_at) <= ?";
    $params[] = $filter_date_to;
}

if ($filter_status === 'pending') {
    $where_conditions[] = "EXISTS (
        SELECT 1 FROM student_answers sa2 
        JOIN questions q2 ON sa2.question_id = q2.id 
        WHERE sa2.student_exam_id = se.id AND q2.auto_grade = 0 AND sa2.graded_at IS NULL AND sa2.answer_text IS NOT NULL
    )";
} elseif ($filter_status === 'graded') {
    $where_conditions[] = "NOT EXISTS (
        SELECT 1 FROM student_answers sa2 
        JOIN questions q2 ON sa2.question_id = q2.id 
        WHERE sa2.student_exam_id = se.id AND q2.auto_grade = 0 AND sa2.graded_at IS NULL AND sa2.answer_text IS NOT NULL
    )";
}

$where_clause = implode(' AND ', $where_conditions);

// Get filtered submissions
$submissions_query = "
    SELECT se.*, s.full_name, s.email, s.company, e.title as exam_title, e.exam_date,
           (SELECT COUNT(*) FROM student_answers sa 
            JOIN questions q ON sa.question_id = q.id 
            WHERE sa.student_exam_id = se.id AND q.auto_grade = 0 AND sa.graded_at IS NULL AND sa.answer_text IS NOT NULL) as pending_count,
           (SELECT COUNT(*) FROM student_answers sa2 
            JOIN questions q2 ON sa2.question_id = q2.id 
            WHERE sa2.student_exam_id = se.id AND q2.auto_grade = 0) as total_manual
    FROM student_exams se
    JOIN students s ON se.student_id = s.id
    JOIN exams e ON se.exam_id = e.id
    WHERE $where_clause
    ORDER BY pending_count DESC, se.submitted_at DESC
";
$stmt = $pdo->prepare($submissions_query);
$stmt->execute($params);
$submissions = $stmt->fetchAll();

// Get summary stats
$stats_query = "
    SELECT 
        COUNT(*) as total_submissions,
        SUM(CASE WHEN EXISTS (
            SELECT 1 FROM student_answers sa 
            JOIN questions q ON sa.question_id = q.id 
            WHERE sa.student_exam_id = se.id AND q.auto_grade = 0 AND sa.graded_at IS NULL AND sa.answer_text IS NOT NULL
        ) THEN 1 ELSE 0 END) as pending_submissions
    FROM student_exams se
    JOIN students s ON se.student_id = s.id
    JOIN exams e ON se.exam_id = e.id
    WHERE $where_clause
";
$stmt = $pdo->prepare($stats_query);
$stmt->execute($params);
$stats = $stmt->fetch();

// Get answers for grading specific student
$answers_to_grade = [];
$student_info = null;
if ($student_exam_id) {
    $stmt = $pdo->prepare("
        SELECT sa.*, q.question_text, q.marks as max_marks, q.question_type, q.word_limit,
               s.full_name as student_name, s.company, e.title as exam_title
        FROM student_answers sa
        JOIN questions q ON sa.question_id = q.id
        JOIN student_exams se ON sa.student_exam_id = se.id
        JOIN students s ON se.student_id = s.id
        JOIN exams e ON se.exam_id = e.id
        WHERE sa.student_exam_id = ? AND q.auto_grade = 0 AND sa.answer_text IS NOT NULL
        ORDER BY q.id
    ");
    $stmt->execute([$student_exam_id]);
    $answers_to_grade = $stmt->fetchAll();
    
    if (!empty($answers_to_grade)) {
        $student_info = [
            'name' => $answers_to_grade[0]->student_name,
            'company' => $answers_to_grade[0]->company,
            'exam' => $answers_to_grade[0]->exam_title
        ];
    }
}

$flash = get_flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manual Grading - Edoxi Training Center</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <?php include 'includes/nav.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <?php if ($flash): ?>
            <div class="mb-6 bg-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-50 border-l-4 border-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-500 p-4 rounded-lg">
                <p class="text-<?php echo $flash['type'] === 'success' ? 'green' : 'red'; ?>-800 font-medium">
                    <?php echo $flash['message']; ?>
                </p>
            </div>
        <?php endif; ?>
        
        <?php if ($action === 'list'): ?>
            <!-- Header -->
            <div class="mb-8">
                <h1 class="text-3xl font-bold text-gray-800 flex items-center">
                    <div class="bg-orange-100 rounded-lg p-3 mr-3">
                        <i class="fas fa-clipboard-check text-orange-600 text-2xl"></i>
                    </div>
                    Manual Grading
                </h1>
                <p class="text-gray-600 mt-2 ml-16">Grade essays and short answer responses</p>
            </div>
            
            <!-- Filter Section -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-6 gap-4">
                    <input type="hidden" name="action" value="list">
                    
                    <!-- Exam Filter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-file-alt mr-1 text-blue-600"></i> Exam
                        </label>
                        <select name="exam_id" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-sm">
                            <option value="">All Exams</option>
                            <?php foreach ($all_exams as $e): ?>
                                <option value="<?php echo $e->id; ?>" <?php echo $filter_exam == $e->id ? 'selected' : ''; ?>>
                                    <?php echo escape($e->title); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Company Filter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-building mr-1 text-purple-600"></i> Company
                        </label>
                        <select name="company" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-sm">
                            <option value="">All Companies</option>
                            <?php foreach ($all_companies as $c): ?>
                                <option value="<?php echo escape($c->company); ?>" <?php echo $filter_company === $c->company ? 'selected' : ''; ?>>
                                    <?php echo escape($c->company); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Date From -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-calendar mr-1 text-green-600"></i> Date From
                        </label>
                        <input type="date" name="date_from" value="<?php echo $filter_date_from; ?>"
                               class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-sm">
                    </div>
                    
                    <!-- Date To -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-calendar-check mr-1 text-green-600"></i> Date To
                        </label>
                        <input type="date" name="date_to" value="<?php echo $filter_date_to; ?>"
                               class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-sm">
                    </div>
                    
                    <!-- Status Filter -->
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-tasks mr-1 text-orange-600"></i> Status
                        </label>
                        <select name="status" class="w-full px-3 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-sm">
                            <option value="">All Status</option>
                            <option value="pending" <?php echo $filter_status === 'pending' ? 'selected' : ''; ?>>Pending Grading</option>
                            <option value="graded" <?php echo $filter_status === 'graded' ? 'selected' : ''; ?>>Fully Graded</option>
                        </select>
                    </div>
                    
                    <!-- Buttons -->
                    <div class="flex items-end gap-2">
                        <button type="submit" class="flex-1 bg-orange-600 hover:bg-orange-700 text-white px-4 py-2.5 rounded-lg font-semibold transition">
                            <i class="fas fa-filter mr-1"></i> Filter
                        </button>
                        <a href="?action=list" class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-2.5 rounded-lg transition">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </form>
            </div>
            
            <!-- Stats Cards -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-xl shadow p-5 border-l-4 border-blue-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">Total Submissions</p>
                            <p class="text-3xl font-bold text-gray-800"><?php echo $stats->total_submissions ?? 0; ?></p>
                        </div>
                        <div class="bg-blue-100 rounded-full p-3">
                            <i class="fas fa-users text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow p-5 border-l-4 border-yellow-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">Pending Grading</p>
                            <p class="text-3xl font-bold text-yellow-600"><?php echo $stats->pending_submissions ?? 0; ?></p>
                        </div>
                        <div class="bg-yellow-100 rounded-full p-3">
                            <i class="fas fa-clock text-yellow-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow p-5 border-l-4 border-green-500">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">Fully Graded</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo ($stats->total_submissions ?? 0) - ($stats->pending_submissions ?? 0); ?></p>
                        </div>
                        <div class="bg-green-100 rounded-full p-3">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Submissions Table -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gradient-to-r from-gray-50 to-gray-100">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Student</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Company</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Exam</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Submitted</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Score</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Grading Status</th>
                                <th class="px-6 py-4 text-right text-xs font-bold text-gray-700 uppercase">Action</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($submissions as $sub): ?>
                            <tr class="hover:bg-orange-50 transition">
                                <td class="px-6 py-4">
                                    <p class="font-semibold text-gray-900"><?php echo escape($sub->full_name); ?></p>
                                    <p class="text-xs text-gray-500"><?php echo escape($sub->email); ?></p>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="text-sm text-gray-700"><?php echo escape($sub->company); ?></span>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="text-sm font-medium text-gray-900"><?php echo escape($sub->exam_title); ?></span>
                                    <p class="text-xs text-gray-500"><?php echo date('M d, Y', strtotime($sub->exam_date)); ?></p>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-700">
                                    <?php echo date('M d, Y', strtotime($sub->submitted_at)); ?>
                                    <p class="text-xs text-gray-500"><?php echo date('H:i', strtotime($sub->submitted_at)); ?></p>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="font-bold text-gray-900"><?php echo $sub->obtained_marks; ?></span>
                                    <span class="text-gray-500 text-sm">(<?php echo round($sub->percentage, 1); ?>%)</span>
                                    <?php if ($sub->result): ?>
                                    <span class="block text-xs mt-1 <?php echo $sub->result === 'pass' ? 'text-green-600' : 'text-red-600'; ?> font-semibold uppercase">
                                        <?php echo $sub->result; ?>
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4">
                                    <?php if ($sub->pending_count > 0): ?>
                                    <span class="px-3 py-1.5 bg-yellow-100 text-yellow-800 rounded-full text-sm font-semibold inline-flex items-center">
                                        <i class="fas fa-clock mr-1"></i>
                                        <?php echo $sub->pending_count; ?>/<?php echo $sub->total_manual; ?> pending
                                    </span>
                                    <?php elseif ($sub->total_manual > 0): ?>
                                    <span class="px-3 py-1.5 bg-green-100 text-green-800 rounded-full text-sm font-semibold inline-flex items-center">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        All graded
                                    </span>
                                    <?php else: ?>
                                    <span class="px-3 py-1.5 bg-gray-100 text-gray-600 rounded-full text-sm font-semibold">
                                        Auto-graded only
                                    </span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <?php if ($sub->total_manual > 0): ?>
                                    <a href="?action=grade_exam&student_exam_id=<?php echo $sub->id; ?>" 
                                       class="inline-flex items-center px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-lg font-semibold text-sm transition">
                                        <i class="fas fa-pen mr-1"></i> Grade
                                    </a>
                                    <?php else: ?>
                                    <span class="text-gray-400 text-sm">No manual questions</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            
                            <?php if (empty($submissions)): ?>
                            <tr>
                                <td colspan="7" class="px-6 py-16 text-center text-gray-500">
                                    <i class="fas fa-inbox text-6xl mb-4 text-gray-300"></i>
                                    <p class="text-xl font-semibold">No submissions found</p>
                                    <p class="text-sm mt-2">Try adjusting your filters</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
        <?php elseif ($action === 'grade_exam' && $student_exam_id): ?>
            <!-- Grade Individual Student's Answers -->
            <div class="mb-6">
                <a href="?action=list" class="text-orange-600 hover:text-orange-800 font-semibold inline-flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i> Back to Submissions
                </a>
            </div>
            
            <?php if (!empty($answers_to_grade)): ?>
                <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                        <div>
                            <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                                <div class="bg-orange-100 rounded-lg p-2 mr-3">
                                    <i class="fas fa-user-graduate text-orange-600"></i>
                                </div>
                                <?php echo escape($student_info['name']); ?>
                            </h1>
                            <div class="flex flex-wrap gap-3 mt-2 ml-12">
                                <span class="text-sm text-gray-600">
                                    <i class="fas fa-building mr-1 text-purple-500"></i>
                                    <?php echo escape($student_info['company']); ?>
                                </span>
                                <span class="text-sm text-gray-600">
                                    <i class="fas fa-file-alt mr-1 text-blue-500"></i>
                                    <?php echo escape($student_info['exam']); ?>
                                </span>
                            </div>
                        </div>
                        <div class="text-center bg-orange-50 rounded-lg px-6 py-3">
                            <p class="text-sm text-gray-600">Questions to Grade</p>
                            <p class="text-3xl font-bold text-orange-600"><?php echo count($answers_to_grade); ?></p>
                        </div>
                    </div>
                </div>
                
                <div class="space-y-6">
                    <?php foreach ($answers_to_grade as $idx => $ans): ?>
                    <div class="bg-white rounded-xl shadow-lg p-6 <?php echo $ans->graded_at ? 'border-l-4 border-green-500' : 'border-l-4 border-yellow-500'; ?>">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-lg font-bold text-gray-800 flex items-center gap-3">
                                <span class="bg-gray-200 text-gray-700 rounded-full w-8 h-8 flex items-center justify-center text-sm">
                                    <?php echo $idx + 1; ?>
                                </span>
                                Question
                                <span class="px-2 py-1 text-xs rounded-full bg-<?php echo $ans->question_type === 'essay' ? 'red' : 'orange'; ?>-100 text-<?php echo $ans->question_type === 'essay' ? 'red' : 'orange'; ?>-800">
                                    <i class="fas fa-<?php echo $ans->question_type === 'essay' ? 'file-alt' : 'align-left'; ?> mr-1"></i>
                                    <?php echo ucfirst(str_replace('_', ' ', $ans->question_type)); ?>
                                </span>
                            </h3>
                            <span class="text-sm font-semibold text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                Max: <?php echo $ans->max_marks; ?> marks
                            </span>
                        </div>
                        
                        <div class="bg-gray-50 rounded-lg p-4 mb-4">
                            <p class="text-gray-800 font-medium"><?php echo escape($ans->question_text); ?></p>
                        </div>
                        
                        <div class="bg-blue-50 rounded-lg p-4 mb-4">
                            <label class="block text-sm font-semibold text-blue-800 mb-2">
                                <i class="fas fa-user-edit mr-1"></i> Student's Answer:
                            </label>
                            <div class="bg-white rounded-lg p-4 border border-blue-200 whitespace-pre-wrap text-gray-800">
                                <?php echo escape($ans->answer_text); ?>
                            </div>
                            <?php if ($ans->word_limit): ?>
                            <p class="text-xs text-gray-500 mt-2">
                                <i class="fas fa-text-width mr-1"></i>
                                Word count: <?php echo str_word_count($ans->answer_text); ?> / <?php echo $ans->word_limit; ?>
                            </p>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($ans->graded_at): ?>
                        <!-- Already Graded -->
                        <div class="bg-green-50 rounded-lg p-4 border border-green-200">
                            <div class="flex items-center justify-between mb-2">
                                <p class="text-green-800 font-semibold">
                                    <i class="fas fa-check-circle mr-1"></i> Graded
                                </p>
                                <span class="text-2xl font-bold text-green-700">
                                    <?php echo $ans->partial_marks; ?> / <?php echo $ans->max_marks; ?>
                                </span>
                            </div>
                            <?php if ($ans->feedback): ?>
                            <div class="mt-3 pt-3 border-t border-green-200">
                                <p class="text-sm text-gray-700"><strong>Feedback:</strong> <?php echo escape($ans->feedback); ?></p>
                            </div>
                            <?php endif; ?>
                            <p class="text-xs text-gray-500 mt-2">
                                <i class="fas fa-clock mr-1"></i>
                                Graded on <?php echo date('M d, Y H:i', strtotime($ans->graded_at)); ?>
                            </p>
                            
                            <!-- Re-grade button -->
                            <button onclick="document.getElementById('regrade-form-<?php echo $ans->id; ?>').classList.toggle('hidden')" 
                                    class="mt-3 text-sm text-orange-600 hover:text-orange-800 font-semibold">
                                <i class="fas fa-edit mr-1"></i> Re-grade
                            </button>
                            
                            <form id="regrade-form-<?php echo $ans->id; ?>" method="POST" action="?action=grade&student_exam_id=<?php echo $student_exam_id; ?>" class="hidden mt-4 pt-4 border-t border-green-200">
                                <input type="hidden" name="answer_id" value="<?php echo $ans->id; ?>">
                                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                    <div>
                                        <label class="block text-sm font-semibold text-gray-700 mb-2">New Marks</label>
                                        <input type="number" name="marks" required step="0.5" min="0" max="<?php echo $ans->max_marks; ?>"
                                               value="<?php echo $ans->partial_marks; ?>"
                                               class="w-full px-4 py-2 border-2 border-gray-300 rounded-lg">
                                    </div>
                                    <div class="md:col-span-2">
                                        <label class="block text-sm font-semibold text-gray-700 mb-2">New Feedback</label>
                                        <input type="text" name="feedback" value="<?php echo escape($ans->feedback); ?>"
                                               class="w-full px-4 py-2 border-2 border-gray-300 rounded-lg">
                                    </div>
                                </div>
                                <div class="mt-3 flex justify-end">
                                    <button type="submit" class="px-4 py-2 bg-orange-600 text-white rounded-lg font-semibold text-sm">
                                        <i class="fas fa-save mr-1"></i> Update Grade
                                    </button>
                                </div>
                            </form>
                        </div>
                        <?php else: ?>
                        <!-- Grading Form -->
                        <form method="POST" action="?action=grade&student_exam_id=<?php echo $student_exam_id; ?>" class="mt-4 border-t pt-4">
                            <input type="hidden" name="answer_id" value="<?php echo $ans->id; ?>">
                            
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">
                                        <i class="fas fa-star text-yellow-500 mr-1"></i> Award Marks *
                                    </label>
                                    <input type="number" name="marks" required step="0.5" min="0" max="<?php echo $ans->max_marks; ?>"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 text-lg font-semibold"
                                           placeholder="0 - <?php echo $ans->max_marks; ?>">
                                </div>
                                <div class="md:col-span-2">
                                    <label class="block text-sm font-semibold text-gray-700 mb-2">
                                        <i class="fas fa-comment text-blue-500 mr-1"></i> Feedback (optional)
                                    </label>
                                    <input type="text" name="feedback" 
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500"
                                           placeholder="Optional feedback for the student">
                                </div>
                            </div>
                            
                            <!-- Quick marks buttons -->
                            <div class="mt-3 flex flex-wrap gap-2">
                                <span class="text-xs text-gray-500 mr-2 self-center">Quick:</span>
                                <?php 
                                $quick_marks = [0, $ans->max_marks * 0.25, $ans->max_marks * 0.5, $ans->max_marks * 0.75, $ans->max_marks];
                                foreach ($quick_marks as $qm): 
                                ?>
                                <button type="button" onclick="this.closest('form').querySelector('input[name=marks]').value=<?php echo $qm; ?>"
                                        class="px-3 py-1 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded text-sm font-semibold transition">
                                    <?php echo $qm; ?>
                                </button>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="mt-4 flex justify-end">
                                <button type="submit" class="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold transition">
                                    <i class="fas fa-check mr-2"></i> Save Grade
                                </button>
                            </div>
                        </form>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                
            <?php else: ?>
                <div class="bg-white rounded-xl shadow-lg p-12 text-center">
                    <i class="fas fa-check-circle text-6xl text-green-500 mb-4"></i>
                    <p class="text-xl text-gray-700 font-semibold">All answers have been graded!</p>
                    <a href="?action=list" class="mt-4 inline-flex items-center text-orange-600 hover:text-orange-800 font-semibold">
                        <i class="fas fa-arrow-left mr-1"></i> Back to Submissions
                    </a>
                </div>
            <?php endif; ?>
            
        <?php endif; ?>
    </div>
</body>
</html>