<?php
require_once __DIR__ . '/../config.php';
function db() {
    static $pdo = null;
    if ($pdo === null) {
        $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
        try {
            $pdo = new PDO($dsn, DB_USER, DB_PASS, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            ]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'DB connection failed', 'detail' => $e->getMessage()]);
            exit;
        }
    }
    return $pdo;
}
function create_conversation_if_needed($session_id) {
    $pdo = db();
    $q = $pdo->prepare('SELECT id FROM conversations WHERE session_id = ? ORDER BY created_at DESC LIMIT 1');
    $q->execute([$session_id]);
    $row = $q->fetch();
    if ($row) return (int)$row['id'];
    $q = $pdo->prepare('INSERT INTO conversations (session_id, title, created_at) VALUES (?, ?, NOW())');
    $q->execute([$session_id, 'Percakapan Baru']);
    return (int)$pdo->lastInsertId();
}
function add_message($conversation_id, $role, $content, $openai_response_id = null) {
    $pdo = db();
    $q = $pdo->prepare('INSERT INTO messages (conversation_id, role, content, openai_response_id, created_at) VALUES (?, ?, ?, ?, NOW())');
    $q->execute([$conversation_id, $role, $content, $openai_response_id]);
}
function get_recent_messages($conversation_id, $limit = 12) {
    $pdo = db();
    $q = $pdo->prepare('SELECT role, content FROM messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?');
    $q->bindValue(1, $conversation_id, PDO::PARAM_INT);
    $q->bindValue(2, $limit, PDO::PARAM_INT);
    $q->execute();
    $rows = $q->fetchAll();
    return array_reverse($rows);
}
