<?php
require_once('../config.php');
include('../header/header.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'lecturer') {
    header("Location: dashboard.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$success = '';

// Handle result submission
if (isset($_POST['add_result'])) {
    $student_id = $_POST['student_id'];
    $course_id = $_POST['course_id'];
    $score = $_POST['score'];
    $grade = $_POST['grade'];
    $remarks = $_POST['remarks'];

    $stmt = $pdo->prepare("INSERT INTO results (student_id, course_id, score, grade, remarks) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$student_id, $course_id, $score, $grade, $remarks]);
    $success = "Result recorded successfully!";
}

// Fetch all courses managed by this lecturer
$stmt = $pdo->prepare("SELECT id, course_name FROM courses WHERE lecturer_id = ?");
$stmt->execute([$user_id]);
$courses = $stmt->fetchAll();

// Fetch enrolled students for the lecturer's courses
$stmt = $pdo->prepare("SELECT u.id, u.username, c.id as course_id, c.course_name FROM users u JOIN enrollments e ON u.id = e.student_id JOIN courses c ON e.course_id = c.id WHERE c.lecturer_id = ? AND e.status = 'enrolled'");
$stmt->execute([$user_id]);
$enrolled_students = $stmt->fetchAll();
?>

<div class="container-fluid py-4">
    <div class="row">
        <div class="col-lg-4 mb-4">
            <div class="card shadow-sm border-0">
                <div class="card-body p-4">
                    <h4 class="fw-bold mb-4">Input Student Results</h4>
                    
                    <?php if($success): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Select Student & Course</label>
                            <select name="student_course" class="form-select" id="student_course" onchange="updateFields()" required>
                                <option value="">-- Select --</option>
                                <?php foreach($enrolled_students as $s): ?>
                                    <option value="<?php echo $s['id'] . '|' . $s['course_id']; ?>">
                                        <?php echo htmlspecialchars($s['username']) . ' (' . htmlspecialchars($s['course_name']) . ')'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden" name="student_id" id="student_id">
                            <input type="hidden" name="course_id" id="course_id">
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Score (%)</label>
                            <input type="number" name="score" class="form-control" placeholder="0-100" min="0" max="100" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Grade</label>
                            <select name="grade" class="form-select" required>
                                <option value="A">A</option>
                                <option value="B">B</option>
                                <option value="C">C</option>
                                <option value="D">D</option>
                                <option value="F">F</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Remarks</label>
                            <textarea name="remarks" class="form-control" rows="3" placeholder="Excellent, Good, etc."></textarea>
                        </div>
                        <button type="submit" name="add_result" class="btn btn-primary w-100 py-2 fw-bold">Submit Result</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-8">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white py-3 border-0">
                    <h4 class="fw-bold mb-0">Graded Performance Summary</h4>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-4">Student</th>
                                    <th>Course</th>
                                    <th>Score</th>
                                    <th>Grade</th>
                                    <th class="pe-4 text-end">Date Released</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $stmt = $pdo->prepare("SELECT r.*, u.username, c.course_name FROM results r JOIN users u ON r.student_id = u.id JOIN courses c ON r.course_id = c.id WHERE c.lecturer_id = ? ORDER BY r.created_at DESC");
                                $stmt->execute([$user_id]);
                                $graded_results = $stmt->fetchAll();
                                foreach($graded_results as $res): ?>
                                    <tr>
                                        <td class="ps-4 fw-bold"><?php echo htmlspecialchars($res['username']); ?></td>
                                        <td><?php echo htmlspecialchars($res['course_name']); ?></td>
                                        <td><?php echo $res['score']; ?>%</td>
                                        <td><span class="badge bg-primary"><?php echo $res['grade']; ?></span></td>
                                        <td class="pe-4 text-end small text-muted"><?php echo date('M d, Y', strtotime($res['created_at'])); ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function updateFields() {
    const val = document.getElementById('student_course').value;
    if (val) {
        const parts = val.split('|');
        document.getElementById('student_id').value = parts[0];
        document.getElementById('course_id').value = parts[1];
    }
}
</script>

<?php include('../footer/footer.php'); ?>
