<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once 'connectiondb.php';

// CSRF token generation and validation
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$student_id_input = $_POST['student_id'] ?? '';
$selected_exam_id = $_POST['selected_exam_id'] ?? '';
$action = $_POST['action'] ?? '';
$errors = [];
$success_message = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

$student = null;
$exams = [];
$questions = [];
$options_by_question = [];
$selected_options = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $errors[] = "Invalid CSRF token.";
    } else {
        if ($action === 'find_student') {
            // Find student by student_id
            if (empty($student_id_input)) {
                $errors[] = "Please enter a student ID.";
            } else {
                $stmt = $pdo->prepare("SELECT id, student_id, name FROM students WHERE student_id = ?");
                $stmt->execute([$student_id_input]);
                $student = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$student) {
                    $errors[] = "Student not found with ID: " . htmlspecialchars($student_id_input);
                } else {
                    // Fetch exams taken by student
                    $stmtExams = $pdo->prepare("SELECT e.id, e.exam_name FROM exams e JOIN student_exams se ON e.id = se.exam_id WHERE se.student_id = ? ORDER BY e.exam_name");
                    $stmtExams->execute([$student['id']]);
                    $exams = $stmtExams->fetchAll(PDO::FETCH_ASSOC);
                }
            }
        } elseif ($action === 'edit_exam') {
            // Load student and exam for editing answers
            $student_id_hidden = $_POST['student_id_hidden'] ?? '';
            $selected_exam_id = $_POST['selected_exam_id'] ?? '';

            if (empty($student_id_hidden) || empty($selected_exam_id)) {
                $errors[] = "Invalid student or exam ID.";
            } else {
                // Validate student exists
                $stmt = $pdo->prepare("SELECT id, student_id FROM students WHERE id = ?");
                $stmt->execute([$student_id_hidden]);
                $student = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$student) {
                    $errors[] = "Student not found.";
                } else {
                    // Fetch exams for display
                    $stmtExams = $pdo->prepare("SELECT e.id, e.exam_name FROM exams e JOIN student_exams se ON e.id = se.exam_id WHERE se.student_id = ? ORDER BY e.exam_name");
                    $stmtExams->execute([$student['id']]);
                    $exams = $stmtExams->fetchAll(PDO::FETCH_ASSOC);

                    // Fetch questions for the selected exam
                    $stmtQuestions = $pdo->prepare("SELECT id, question_text FROM questions WHERE exam_id = ? ORDER BY id ASC");
                    $stmtQuestions->execute([$selected_exam_id]);
                    $questions = $stmtQuestions->fetchAll(PDO::FETCH_ASSOC);

                    // Fetch options for questions
                    if (!empty($questions)) {
                        $question_ids = array_column($questions, 'id');
                        $placeholders = implode(',', array_fill(0, count($question_ids), '?'));
                        $stmtOptions = $pdo->prepare("SELECT id, question_id, option_text FROM options WHERE question_id IN ($placeholders) ORDER BY question_id, id");
                        $stmtOptions->execute($question_ids);
                        $options = $stmtOptions->fetchAll(PDO::FETCH_ASSOC);

                        // Group options by question_id
                        foreach ($options as $option) {
                            $options_by_question[$option['question_id']][] = $option;
                        }
                    }

                    // Fetch student's selected answers for the exam
                    $stmtAnswers = $pdo->prepare("SELECT question_id, selected_option_id FROM student_answers WHERE student_id = ? AND question_id IN (SELECT id FROM questions WHERE exam_id = ?)");
                    $stmtAnswers->execute([$student['id'], $selected_exam_id]);
                    $answers = $stmtAnswers->fetchAll(PDO::FETCH_ASSOC);

                    foreach ($answers as $answer) {
                        $selected_options[$answer['question_id']] = $answer['selected_option_id'];
                    }
                }
            }
        } elseif ($action === 'update_answers') {
            // Update answers for student and exam
            $student_id_hidden = $_POST['student_id_hidden'] ?? '';
            $selected_exam_id = $_POST['selected_exam_id'] ?? '';
            $answers = $_POST['answers'] ?? [];

            if (empty($student_id_hidden) || empty($selected_exam_id)) {
                $errors[] = "Invalid student or exam ID.";
            } else {
                // Validate student exists
                $stmt = $pdo->prepare("SELECT id, student_id FROM students WHERE id = ?");
                $stmt->execute([$student_id_hidden]);
                $student = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$student) {
                    $errors[] = "Student not found.";
                }
            }

            if (empty($errors)) {
                try {
                    $pdo->beginTransaction();

                    // Delete previous answers for this student and exam
                    $stmtDelete = $pdo->prepare("DELETE sa FROM student_answers sa JOIN questions q ON sa.question_id = q.id WHERE sa.student_id = ? AND q.exam_id = ?");
                    $stmtDelete->execute([$student_id_hidden, $selected_exam_id]);

                    // Validate and insert new answers
                    $checkOptionStmt = $pdo->prepare("SELECT COUNT(*) FROM options WHERE id = ?");
                    $insertStmt = $pdo->prepare("INSERT INTO student_answers (student_id, question_id, selected_option_id) VALUES (?, ?, ?)");

                    foreach ($answers as $question_id => $option_id) {
                        $checkOptionStmt->execute([$option_id]);
                        $count = $checkOptionStmt->fetchColumn();
                        if ($count == 0) {
                            continue; // skip invalid option
                        }
                        $insertStmt->execute([$student_id_hidden, $question_id, $option_id]);
                    }

                    // Update student_exams status to completed if not already
                    $updateStmt = $pdo->prepare("UPDATE student_exams SET status = 'completed' WHERE student_id = ? AND exam_id = ?");
                    $updateStmt->execute([$student_id_hidden, $selected_exam_id]);

                    $pdo->commit();

                    $success_message = "Answers updated successfully.";

                    // Reload student and exams for display
                    $stmt = $pdo->prepare("SELECT id, student_id, name FROM students WHERE id = ?");
                    $stmt->execute([$student_id_hidden]);
                    $student = $stmt->fetch(PDO::FETCH_ASSOC);

                    $stmtExams = $pdo->prepare("SELECT e.id, e.exam_name FROM exams e JOIN student_exams se ON e.id = se.exam_id WHERE se.student_id = ? ORDER BY e.exam_name");
                    $stmtExams->execute([$student_id_hidden]);
                    $exams = $stmtExams->fetchAll(PDO::FETCH_ASSOC);

                    // Fetch questions and options again for the selected exam
                    $stmtQuestions = $pdo->prepare("SELECT id, question_text FROM questions WHERE exam_id = ? ORDER BY id ASC");
                    $stmtQuestions->execute([$selected_exam_id]);
                    $questions = $stmtQuestions->fetchAll(PDO::FETCH_ASSOC);

                    if (!empty($questions)) {
                        $question_ids = array_column($questions, 'id');
                        $placeholders = implode(',', array_fill(0, count($question_ids), '?'));
                        $stmtOptions = $pdo->prepare("SELECT id, question_id, option_text FROM options WHERE question_id IN ($placeholders) ORDER BY question_id, id");
                        $stmtOptions->execute($question_ids);
                        $options = $stmtOptions->fetchAll(PDO::FETCH_ASSOC);

                        $options_by_question = [];
                        foreach ($options as $option) {
                            $options_by_question[$option['question_id']][] = $option;
                        }
                    }

                    $stmtAnswers = $pdo->prepare("SELECT question_id, selected_option_id FROM student_answers WHERE student_id = ? AND question_id IN (SELECT id FROM questions WHERE exam_id = ?)");
                    $stmtAnswers->execute([$student_id_hidden, $selected_exam_id]);
                    $answers = $stmtAnswers->fetchAll(PDO::FETCH_ASSOC);

                    $selected_options = [];
                    foreach ($answers as $answer) {
                        $selected_options[$answer['question_id']] = $answer['selected_option_id'];
                    }
                } catch (PDOException $e) {
                    if ($pdo->inTransaction()) {
                        $pdo->rollBack();
                    }
                    $errors[] = "Error updating answers: " . $e->getMessage();
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Admin Edit Student Answers</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<?php include 'navbar.php'; ?>
<div class="container my-4">
    <h2>Admin Edit Student Answers</h2>

    <form method="POST" action="admin_edit_answers.php" class="mb-4">
        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
        <div class="mb-3">
            <label for="student_id" class="form-label">Student ID</label>
            <input type="text" name="student_id" id="student_id" class="form-control" value="<?php echo htmlspecialchars($student_id_input); ?>" />
        </div>
        <button type="submit" name="action" value="find_student" class="btn btn-primary mb-3">Find Student</button>
    </form>

    <?php if (!empty($errors)): ?>
        <div class="alert alert-danger">
            <ul>
                <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <?php if ($success_message): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
    <?php endif; ?>

    <?php if ($student): ?>
        <h4>Student: <?php echo htmlspecialchars($student['name']); ?> (ID: <?php echo htmlspecialchars($student['student_id']); ?>)</h4>

        <?php if (empty($exams)): ?>
            <p>No exams found for this student.</p>
        <?php else: ?>
            <h5>Submitted Exams</h5>
            <table class="table table-bordered mb-4">
                <thead>
                    <tr>
                        <th>Exam Name</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($exams as $exam): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($exam['exam_name']); ?></td>
                            <td>
                                <form method="POST" action="admin_edit_answers.php" style="display:inline;">
                                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
                                    <input type="hidden" name="student_id_hidden" value="<?php echo htmlspecialchars($student['id']); ?>" />
                                    <input type="hidden" name="selected_exam_id" value="<?php echo htmlspecialchars($exam['id']); ?>" />
                                    <button type="submit" name="action" value="edit_exam" class="btn btn-sm btn-warning">
                                        Edit
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <?php if ($action === 'edit_exam' || $action === 'update_answers'): ?>
                <?php if (empty($questions)): ?>
                    <p>No questions found for this exam.</p>
                <?php else: ?>
                    <form method="POST" action="admin_edit_answers.php">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
                        <input type="hidden" name="student_id_hidden" value="<?php echo htmlspecialchars($student['id']); ?>" />
                        <input type="hidden" name="selected_exam_id" value="<?php echo htmlspecialchars($selected_exam_id); ?>" />
                        <h5>Edit Answers for Exam: 
                            <?php
                            foreach ($exams as $exam) {
                                if ($exam['id'] == $selected_exam_id) {
                                    echo htmlspecialchars($exam['exam_name']);
                                    break;
                                }
                            }
                            ?>
                        </h5>
                        <div class="mb-3">
                            <?php $qnum = 1; foreach ($questions as $question): ?>
                                <div class="mb-4 p-3 border rounded">
                                    <p><strong>Question <?php echo $qnum++; ?>:</strong> <?php echo htmlspecialchars($question['question_text']); ?></p>
                                    <?php if (isset($options_by_question[$question['id']])): ?>
                                        <?php foreach ($options_by_question[$question['id']] as $option): ?>
                                            <div class="form-check">
                                                <input class="form-check-input" type="radio" name="answers[<?php echo $question['id']; ?>]" id="option_<?php echo $option['id']; ?>" value="<?php echo $option['id']; ?>" <?php echo (isset($selected_options[$question['id']]) && $selected_options[$question['id']] == $option['id']) ? 'checked' : ''; ?> />
                                                <label class="form-check-label" for="option_<?php echo $option['id']; ?>">
                                                    <?php echo htmlspecialchars($option['option_text']); ?>
                                                </label>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <em>No options found</em>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="submit" name="action" value="update_answers" class="btn btn-success">Update Answers</button>
                    </form>
                <?php endif; ?>
            <?php endif; ?>
        <?php endif; ?>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
