<?php
session_start();
include('config.php');

// Ensure the employee is logged in
if (!isset($_SESSION['employee_id'])) {
    die("Please log in to continue.");
}
$employee_id = $_SESSION['employee_id'];

// Validate form submission
if (!isset($_POST['question_id'], $_POST['answer'])) {
    die("Invalid form submission.");
}
$question_id = (int) $_POST['question_id'];
$answer = trim($_POST['answer']);
$current_date = date('Y-m-d');

// Check again that the employee hasn't already submitted an answer for today
$query = "SELECT id FROM habits_responses WHERE employee_id = ? AND response_date = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("is", $employee_id, $current_date);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
    echo "You have already submitted an answer for today.";
    exit;
}

// Insert the response into the habits_responses table
$query = "INSERT INTO habits_responses (employee_id, question_id, answer, response_date) VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($query);
$stmt->bind_param("iiss", $employee_id, $question_id, $answer, $current_date);
if ($stmt->execute()) {
    echo "Your answer was submitted successfully!";
    // Optionally, redirect back to your dashboard or habits page
    // header("Location: dashboard_employee.php");
    // exit;
} else {
    echo "Error submitting your answer: " . $stmt->error;
}
?>
