<?php
/**
 * AI Chatbot Query Endpoint
 * Handle AI chatbot queries
 */

require_once __DIR__ . '/../layouts/main.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/AIChatbotService.php';

requireLogin();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$question = $input['question'] ?? '';
$member_id = $input['member_id'] ?? null;

if (empty($question)) {
    echo json_encode(['success' => false, 'message' => 'Question is required']);
    exit();
}

$chatbotService = new AIChatbotService($conn);
$result = $chatbotService->getWithdrawalCalculationHelp($member_id, $question);

// Log the interaction
if ($result['success']) {
    $chatbotService->logInteraction(
        $_SESSION['user_id'],
        $member_id,
        $question,
        $result['response']
    );
}

echo json_encode($result);
