<?php

session_start();

include '../config/database.php';
//Include for Token (7 and 8,13 and 14)
include_once '../security/session_config.php';
include_once '../security/csrf.php';

include_once '../config/properties.php';
include_once "../resources/forum.php";

$csrf_token = $_POST['csrf_token'];
validate_csrf_request($csrf_token);

// initialize objects
$forum = new Forum();

$id = $_SESSION['uid'];

$topic_name = $_POST['topic_name'];
$question_desc = $_POST['question_desc'];
$status = "Active";
$forum->user_id = $id;
$forum->topic_name = $topic_name;
$forum->topic_desc = $question_desc;
$forum->status = $status;
$forum->created_ts = $date_time;
$forum->last_updated_user = $id;
$forum->last_updated_ts = $date_time;
$tid = $forum->insert_question_ai();
// if ($tid ) {

//     //Fetch topic name.
    
//     $stmt = $forum->get_forum_topic_name($id);
//     echo '<option value="">All Topics</option>   ';
//     while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//         echo '<option  value="' . $row['topic_name'] . '">' . $row['topic_name'] . '</option>';
//     }
// }

if ($tid) {
    // Fetch topic name list (for dropdown update)
    $stmt = $forum->get_forum_topic_name($id); // assuming $id is user_id or similar
    $options = '<option value="">All Topics</option>';
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $options .= '<option value="' . $row['topic_name'] . '">' . $row['topic_name'] . '</option>';
    }

    // Return both: the dropdown and the topic ID
    echo json_encode([
        'tid' => $tid,
        'options' => $options
    ]);
    exit;
} else {
    echo json_encode([
        'error' => 'Insert failed'
    ]);
    exit;
}
?>

