<?php
require_once __DIR__ . '/../config.php';
session_name(SESSION_NAME);
session_start();

// Coba juga cek session dari cookie langsung
if (empty($_SESSION['user_id'])) {
    // Re-try dengan cookie yang dikirim
    if (!empty($_COOKIE[SESSION_NAME])) {
        session_write_close();
        session_id($_COOKIE[SESSION_NAME]);
        session_start();
    }
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized - silakan refresh halaman dan login ulang']);
        exit;
    }
}

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

$input = json_decode(file_get_contents('php://input'), true);
$question = trim($input['question'] ?? '');
if (!$question) {
    echo json_encode(['error' => 'Empty question']);
    exit;
}

$apiKey = require '/home/caracuanbiz/anthropic-secret.php';

$lang   = trim($input["lang"] ?? "id");
$langInstr = ($lang === "en")
    ? "Answer in English. Provide technical answers with specific FortiGate CLI commands and practical steps."
    : "Jawab dalam Bahasa Indonesia. Berikan jawaban teknis dengan CLI commands FortiGate spesifik dan langkah-langkah praktis.";

$system = "You are an expert FortiGate Network Engineer. Active device configuration:
- Device: FortiGate-100F, hostname: mermaid-mrl, Firmware 7.4.11 build2878
- Mode: Standalone, VDOM: root, Timezone: Asia/Kuala_Lumpur
- WAN: wan1=VSAT2, wan2=Starlink2-KIT-357, port2=Starlink1-KIT355 (no SD-WAN configured)
- LAN: lan=10.20.11.254/23 (port3-19), DMZ=10.10.10.1/24, MGMT=192.168.1.99/24
- PABX: port12=10.30.10.254/24, SWMGMT: port20=10.20.12.254/24
- WiFi VLANs: MarineCrewWifi=10.30.11.0/24, ClientCrewWifi=10.40.11.0/24, PMT Wifi=10.50.11.0/24, Client Office=10.60.11.0/24, AppUpdate=10.70.11.0/24
- DNS: FortiGuard 96.45.45.45/46.46, DoT enabled, via port2
- Users: 82 local accounts (marine001-081 + guest), FortiToken Cloud available but not configured per-user
- QoS shapers: Microsoft-High(guar 2M/max 10M), Sosial-Media-Low(guar 1M/max 3M), quic-isakmp-low, all-other, mid
- Security RISKS: Telnet port 23 active, HTTP admin port 80 active, no 2FA per user
$langInstr";

$payload = json_encode([
    'model'      => 'claude-sonnet-4-6',
    'max_tokens' => 1200,
    'system'     => $system,
    'messages'   => [['role' => 'user', 'content' => $question]]
]);

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

$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if (!$response) {
    echo json_encode(['error' => 'cURL failed: ' . $curlError]);
    exit;
}

$data = json_decode($response, true);
if ($httpCode !== 200) {
    echo json_encode(['error' => 'API error ' . $httpCode . ': ' . ($data['error']['message'] ?? $response)]);
    exit;
}

$text = $data['content'][0]['text'] ?? 'Tidak ada respons.';
echo json_encode(['answer' => $text]);
