<?php
// api/ai.php — Proxy ke Anthropic Claude API
session_start();
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'POST required']);
    exit;
}

$body    = json_decode(file_get_contents('php://input'), true);
$question = trim($body['question'] ?? '');
$history  = $body['history'] ?? [];

if (empty($question)) {
    echo json_encode(['error' => 'Empty question']);
    exit;
}

$apiKey = getConfig('anthropic_key', '');
if (empty($apiKey)) {
    // Coba juga dari environment variable
    $apiKey = getenv('ANTHROPIC_API_KEY') ?: '';
}

if (empty($apiKey)) {
    echo json_encode(['error' => 'API key Anthropic belum dikonfigurasi. Masukkan di tab Pengaturan.']);
    exit;
}

// Susun messages dengan history
$messages = [];
foreach (array_slice($history, -6) as $h) {
    if (isset($h['role'], $h['content'])) {
        $messages[] = ['role' => $h['role'], 'content' => $h['content']];
    }
}
$messages[] = ['role' => 'user', 'content' => $question];

$systemPrompt = "Kamu adalah senior network engineer spesialis jaringan maritim (kapal laut). Admin memiliki:
- Fortinet FortiGate 60F (FortiOS 7.4.3) sebagai firewall/router utama
- Aruba Instant On (6 AP: AP22, AP22D, AP25) untuk WiFi kapal
- Starlink Maritime (Flat High Performance) sebagai koneksi internet satelit
- Semua terhubung dalam satu LAN kapal (192.168.1.0/24)
- 4G backup (WAN2) sebagai failover

Berikan jawaban dalam Bahasa Indonesia yang teknis, praktis, dan actionable. Gunakan format terstruktur. Untuk perintah CLI, gunakan blok kode. Jika ada troubleshooting, berikan langkah step-by-step.";

$payload = [
    'model'      => 'claude-sonnet-4-6',
    'max_tokens' => 1000,
    'system'     => $systemPrompt,
    'messages'   => $messages,
];

$ch = curl_init('https://api.anthropic.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'x-api-key: ' . $apiKey,
        'anthropic-version: 2023-06-01',
    ],
    CURLOPT_TIMEOUT => 60,
]);

$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err  = curl_error($ch);
curl_close($ch);

if ($err) {
    echo json_encode(['error' => 'cURL error: ' . $err]);
    exit;
}

$data = json_decode($resp, true);
if ($code !== 200 || empty($data['content'])) {
    $errMsg = $data['error']['message'] ?? 'Unknown error';
    echo json_encode(['error' => "API error ($code): $errMsg"]);
    exit;
}

$text = implode('', array_map(fn($c) => $c['text'] ?? '', $data['content']));
writeLog("AI query: " . substr($question, 0, 60));

echo json_encode(['answer' => $text]);
