<?php
// save_manual_answers.php
// Save answers submitted from manual_enter_answers.php
// Place this file in: C:\xampp\htdocs\rs_lab\save_manual_answers.php

require_once __DIR__ . '/config.php';
if (session_status() === PHP_SESSION_NONE) session_start();

// Basic login check (optional)
if (empty($_SESSION['user_id'])) {
    // If you want to allow anonymous saving, remove this block.
    // For now we redirect to login so only teachers can save.
    header('Location: login.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Invalid request method.');
}

// Validate quiz_id
if (!isset($_POST['quiz_id']) || !ctype_digit(strval($_POST['quiz_id']))) {
    die('Quiz ID missing or invalid.');
}
$quiz_id = (int) $_POST['quiz_id'];

// student details
$student_name = isset($_POST['student_name']) ? trim($_POST['student_name']) : '';
$roll_no      = isset($_POST['roll_no']) ? trim($_POST['roll_no']) : '';

// sanitize small
$student_name = substr($student_name, 0, 150);
$roll_no = substr($roll_no, 0, 50);

if ($student_name === '' || $roll_no === '') {
    die('Student name and roll number are required.');
}

// answers[] array
if (!isset($_POST['answers']) || !is_array($_POST['answers'])) {
    die('Answers missing.');
}
$answersArr = $_POST['answers'];

// Fetch quiz to know total_questions (safety)
$stmtQ = $conn->prepare("SELECT id, total_questions FROM manual_quizzes WHERE id = ? LIMIT 1");
$stmtQ->bind_param('i', $quiz_id);
$stmtQ->execute();
$qres = $stmtQ->get_result();
if ($qres->num_rows === 0) {
    $stmtQ->close();
    die('Quiz not found.');
}
$quizRow = $qres->fetch_assoc();
$stmtQ->close();
$totalQuestions = (int)$quizRow['total_questions'];

// Normalize answers to totalQuestions length and uppercase
$normalized = [];
for ($i = 0; $i < $totalQuestions; $i++) {
    $val = isset($answersArr[$i]) ? strtoupper(trim($answersArr[$i])) : '';
    // accept only A/B/C/D or blank
    if (!in_array($val, ['', 'A', 'B', 'C', 'D'], true)) $val = '';
    $normalized[] = $val;
}

// join as CSV string e.g. "A,B,,D,..."
$answersStr = implode(',', $normalized);

// Save to DB (manual_answers table)
$createdBy = (int)$_SESSION['user_id'];

$stmt = $conn->prepare("
    INSERT INTO manual_answers
    (quiz_id, student_name, roll_no, answers, created_by_user_id)
    VALUES (?, ?, ?, ?, ?)
");
if (!$stmt) {
    die('DB prepare failed: ' . $conn->error);
}
$stmt->bind_param('isssi', $quiz_id, $student_name, $roll_no, $answersStr, $createdBy);

if ($stmt->execute()) {
    $insertId = $stmt->insert_id;
    $stmt->close();
    // Redirect to result/profile page for this answer
    header('Location: manual_result_profile.php?answer_id=' . $insertId);
    exit;
} else {
    $err = $stmt->error;
    $stmt->close();
    die('Failed to save answers: ' . htmlspecialchars($err));
}
