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

require_once 'connectiondb.php';

if (!isset($_GET['student_id']) || (!isset($_GET['exam_id']) && !isset($_GET['selected_exam_id']))) {
    die('Student ID and Exam ID are required.');
}

$student_id = intval($_GET['student_id']);
$exam_id = isset($_GET['selected_exam_id']) ? intval($_GET['selected_exam_id']) : intval($_GET['exam_id']);

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());
}

// Fetch student info
$stmt = $pdo->prepare("SELECT student_id, name FROM students WHERE id = ?");
$stmt->execute([$student_id]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$student) {
    die('Student not found.');
}

// Fetch exam info
$stmt = $pdo->prepare("SELECT exam_name FROM exams WHERE id = ?");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$exam) {
    die('Exam not found.');
}

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

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

// Map question_id to selected option text for quick lookup
$selected_options = [];
foreach ($answers as $answer) {
    $selected_options[$answer['question_id']] = $answer['option_text'];
}

// Fetch all options for each question including is_correct flag
$stmt = $pdo->prepare("SELECT id, question_id, option_text, is_correct FROM options WHERE question_id IN (SELECT id FROM questions WHERE exam_id = ?) ORDER BY question_id, id");
$stmt->execute([$exam_id]);
$options = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Fetch exam start time from student_exams table start_time column
$stmt = $pdo->prepare("
    SELECT start_time
    FROM student_exams
    WHERE student_id = ? AND exam_id = ?
");
$stmt->execute([$student_id, $exam_id]);
$start_time_row = $stmt->fetch(PDO::FETCH_ASSOC);
$start_time = $start_time_row ? $start_time_row['start_time'] : null;

// Fetch exam completion time from student_exams
$stmt = $pdo->prepare("
    SELECT completed_at
    FROM student_exams
    WHERE student_id = ? AND exam_id = ?
");
$stmt->execute([$student_id, $exam_id]);
$completed_row = $stmt->fetch(PDO::FETCH_ASSOC);
$completed_at = $completed_row ? $completed_row['completed_at'] : null;

// Calculate time taken if both timestamps are available
$time_taken_str = 'N/A';

// Debug output for timestamps
// Uncomment below lines to debug timestamps
// echo "<pre>Start Time: " . var_export($start_time, true) . "\nCompleted At: " . var_export($completed_at, true) . "</pre>";

if ($start_time && $completed_at) {
    $start_dt = new DateTime($start_time);
    $completed_dt = new DateTime($completed_at);
    $interval = $start_dt->diff($completed_dt);
    $time_taken_str = $interval->format('%h hours %i minutes %s seconds');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Student Responses - <?php echo htmlspecialchars($student['name']); ?> - <?php echo htmlspecialchars($exam['exam_name']); ?></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>Student Responses</h2>
    <p><strong>Student:</strong> <?php echo htmlspecialchars($student['name']) . " (" . htmlspecialchars($student['student_id']) . ")"; ?></p>
   

    <?php
    // Fetch all exams taken by the student
    $stmtExams = $pdo->prepare("
        SELECT e.id, e.exam_name
        FROM student_exams se
        JOIN exams e ON se.exam_id = e.id
        WHERE se.student_id = ?
        ORDER BY e.exam_name
    ");
    $stmtExams->execute([$student_id]);
    $student_exams = $stmtExams->fetchAll(PDO::FETCH_ASSOC);

    // Determine selected exam ID from GET or default to current exam
    $selected_exam_id = $exam_id;
    if (isset($_GET['selected_exam_id']) && in_array(intval($_GET['selected_exam_id']), array_column($student_exams, 'id'))) {
        $selected_exam_id = intval($_GET['selected_exam_id']);
    }
    ?>

    <form method="GET" action="view_student_responses.php" class="mb-3">
        <input type="hidden" name="student_id" value="<?php echo htmlspecialchars($student_id); ?>" />
        <label for="selected_exam_id" class="form-label">Select Exam to View Responses:</label>
        <select name="selected_exam_id" id="selected_exam_id" class="form-select w-auto d-inline-block" onchange="this.form.submit()">
            <?php foreach ($student_exams as $se): ?>
                <option value="<?php echo htmlspecialchars($se['id']); ?>" <?php echo ($se['id'] == $selected_exam_id) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($se['exam_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <noscript><button type="submit" class="btn btn-primary ms-2">View</button></noscript>
    </form>

    <?php
    // If selected exam changed, reload questions and answers for that exam
    if ($selected_exam_id !== $exam_id) {
        $exam_id = $selected_exam_id;

        // Fetch exam info
        $stmt = $pdo->prepare("SELECT exam_name FROM exams WHERE id = ?");
        $stmt->execute([$exam_id]);
        $exam = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

        // Map question_id to selected option text for quick lookup
        $selected_options = [];
        foreach ($answers as $answer) {
            $selected_options[$answer['question_id']] = $answer['option_text'];
        }

        // Fetch all options for each question including is_correct flag
        $stmt = $pdo->prepare("SELECT id, question_id, option_text, is_correct FROM options WHERE question_id IN (SELECT id FROM questions WHERE exam_id = ?) ORDER BY question_id, id");
        $stmt->execute([$exam_id]);
        $options = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    <p><strong>Exam:</strong> <?php echo htmlspecialchars($exam['exam_name']); ?></p>
    <a href="manage_students.php" class="btn btn-secondary mb-3">Back to Manage Students</a>
    <?php if (empty($questions)): ?>
        <p>No questions found for this exam.</p>
    <?php else: ?>
        <?php
        // Calculate total marks obtained by the student
        $total_questions = count($questions);
        $correct_count = 0;
        foreach ($questions as $question) {
            if (isset($selected_options[$question['id']]) && isset($options_by_question[$question['id']])) {
                foreach ($options_by_question[$question['id']] as $option) {
                    if ($option['is_correct'] == 1 && $option['option_text'] == $selected_options[$question['id']]) {
                        $correct_count++;
                        break;
                    }
                }
            }
        }
        ?>
        <p><strong>Total Questions:</strong> <?php echo $total_questions; ?></p>
        <p><strong>Correct Answers:</strong> <?php echo $correct_count; ?></p>
        <p><strong>Score:</strong> <?php echo $correct_count . ' / ' . $total_questions; ?></p>

<form method="POST" action="view_student_responses.php?student_id=<?php echo htmlspecialchars($student_id); ?>&exam_id=<?php echo htmlspecialchars($exam_id); ?>">
<div class="table-responsive" id="printable-table">
    <table class="table table-bordered table-striped">
        <thead class="table-primary">
            <tr>
                <th>#</th>
                <th>Question</th>
                <th>Options</th>
                <th>Selected Option</th>
                <th>Correct Answer</th>
            </tr>
        </thead>
        <tbody>
            <?php $qnum = 1; foreach ($questions as $question): ?>
                <tr>
                    <td><?php echo $qnum++; ?></td>
                    <td><?php echo htmlspecialchars($question['question_text']); ?></td>
                    <td>
                        <ul class="mb-0">
                            <?php
                            if (isset($options_by_question[$question['id']])) {
                                $opt_num = 1;
                                foreach ($options_by_question[$question['id']] as $option) {
                                    echo '<li>' . $opt_num++ . '. ' . htmlspecialchars($option['option_text']) . '</li>';
                                }
                            } else {
                                echo '<li>No options found</li>';
                            }
                            ?>
                        </ul>
                    </td>
                    <td>
                        <?php
                        if (isset($options_by_question[$question['id']])) {
                            foreach ($options_by_question[$question['id']] as $option) {
                                $checked = (isset($selected_options[$question['id']]) && $selected_options[$question['id']] == $option['option_text']) ? 'checked' : '';
                                echo '<div class="form-check">';
                                echo '<input class="form-check-input" type="radio" name="answers[' . $question['id'] . ']" id="option_' . $option['id'] . '" value="' . $option['id'] . '" ' . $checked . ' />';
                                echo '<label class="form-check-label" for="option_' . $option['id'] . '">' . htmlspecialchars($option['option_text']) . '</label>';
                                echo '</div>';
                            }
                        } else {
                            echo '<em>Not answered</em>';
                        }
                        ?>
                    </td>
                    <td>
                        <?php
                        // Display correct option(s)
                        if (isset($options_by_question[$question['id']])) {
                            $correct_options = array_filter($options_by_question[$question['id']], function($opt) {
                                return $opt['is_correct'] == 1;
                            });
                            $correct_texts = array_map(function($opt) {
                                return $opt['option_text'];
                            }, $correct_options);
                            echo implode(', ', array_map('htmlspecialchars', $correct_texts));
                        } else {
                            echo '<em>No correct answer set</em>';
                        }
                        ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<button type="submit" name="update_answers" class="btn btn-success mb-3">Update Answers</button>
</form>
    <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
