<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../ai/LocalAIApi.php';
require_once __DIR__ . '/../db/config.php';

// Get the user's message from the POST request
$input = json_decode(file_get_contents('php://input'), true);
$userMessage = $input['message'] ?? '';

if (empty($userMessage)) {
    echo json_encode(['error' => 'No message provided.']);
    exit;
}

// --- Context Gathering ---
$context = "";

try {
    $pdo = db();
    
    // Fetch candidates
    $stmt = $pdo->query("SELECT name, status, email FROM candidates ORDER BY created_at DESC LIMIT 10");
    $candidates = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $context .= "\n\nRecent Candidates:\n" . json_encode($candidates, JSON_PRETTY_PRINT);

    // Fetch tasks
    $stmt = $pdo->query("SELECT t.task_name, c.name as assigned_to, t.status, t.due_date FROM tasks t JOIN candidates c ON t.candidate_id = c.id ORDER BY t.created_at DESC LIMIT 10");
    $tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $context .= "\n\nRecent Tasks:\n" . json_encode($tasks, JSON_PRETTY_PRINT);

} catch (PDOException $e) {
    // Don't expose DB errors to the user, but log them.
    error_log("AI Chat Context Error: " . $e->getMessage());
    // Provide a fallback context
    $context = "\n\nCould not fetch real-time data. Please rely on general knowledge.";
}


// --- AI Interaction ---
$systemPrompt = <<<PROMPT
You are an expert HR assistant for a company called FinMox.
Your role is to answer questions about candidates and tasks based on the data provided below.
Be concise and professional. If you don't have the answer, say so.

Here is the current data from the system:
{$context}
PROMPT;

$messages = [
    ['role' => 'system', 'content' => $systemPrompt],
    ['role' => 'user', 'content' => $userMessage]
];

$response = LocalAIApi::createResponse([
    'input' => $messages,
]);

if (!empty($response['success'])) {
    $decoded = LocalAIApi::decodeJsonFromResponse($response);
    $aiReply = $decoded['choices'][0]['message']['content'] ?? 'Sorry, I could not process that.';
    echo json_encode(['reply' => $aiReply]);
} else {
    error_log('AI error: ' . ($response['error'] ?? 'unknown'));
    echo json_encode(['error' => 'Failed to get a response from the AI.']);
}

?>