<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

$host = 'localhost';
$dbname = 'kijani_quiz';
$username = 'kijani_su';
$password = 'VVk?)dh;=?pm';

// Create connection
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the request
$data = json_decode(file_get_contents('php://input'), true);
$topic = isset($data['topic']) ? $data['topic'] : null;
$email = isset($data['email']) ? $data['email'] : null;
$answers = isset($data['answers']) ? $data['answers'] : null;

// Ensure email is not null
if ($email === null || $answers === null) {
    echo json_encode(['success' => false, 'message' => 'Invalid input. Email or answers are missing.']);
    exit();
}

// Check if the user already exists
$query = "SELECT user_id, category_id FROM users WHERE email = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    // Assign to a general category (assume general category_id = 1)
    $general_category_id = 1;
    $insertUser = "INSERT INTO users (email, category_id) VALUES (?, ?)";
    $stmt = $conn->prepare($insertUser);
    $stmt->bind_param("si", $email, $general_category_id);
    $stmt->execute();
    $user_id = $stmt->insert_id;
} else {
    $user_id = $user['user_id'];
}

// Insert answers
foreach ($answers as $question_id => $option_id) {
    if ($option_id !== null) { // Ensure that an option was selected
        $insertResponse = "INSERT INTO responses (user_id, question_id, option_id) VALUES (?, ?, ?)";
        $stmt = $conn->prepare($insertResponse);
        $stmt->bind_param("iii", $user_id, $question_id, $option_id);
        $stmt->execute();
    }
}

// Response to client
echo json_encode(['success' => true, 'message' => 'Survey submitted successfully']);
?>
