<?php
require_once '../config/config.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

function logDebug($message, $data = null) {
    $logDir = __DIR__ . '/../logs';
    if (!is_dir($logDir)) mkdir($logDir, 0755, true);
    $entry = date('Y-m-d H:i:s') . ' - ' . $message;
    if ($data) $entry .= ' - ' . json_encode($data);
    file_put_contents($logDir . '/ai-chat.log', $entry . PHP_EOL, FILE_APPEND);
}

$input = json_decode(file_get_contents('php://input'), true);
$message = $input['message'] ?? '';
$conversation = $input['conversation'] ?? [];

logDebug('Received', ['message' => substr($message, 0, 100)]);

if (empty($message)) {
    echo json_encode(['error' => 'Message is required']);
    exit();
}

function buildSystemPrompt() {
    $k = FORTIGATE_KNOWLEDGE;
    
    // Interfaces
    $interfaces = array_map(function($n, $d) {
        $ip = $d['ip'] ?? 'DHCP';
        return "- {$n}: {$d['alias']} ({$ip}) [{$d['role']}]";
    }, array_keys($k['interfaces']), $k['interfaces']);
    
    // DHCP
    $dhcp = array_map(function($n, $d) {
        return "- {$n}: gateway {$d['gateway']} (range: {$d['range']})";
    }, array_keys($k['dhcp_servers']), $k['dhcp_servers']);
    
    // Aruba VLANs
    $arubaVlans = array_map(function($v) {
        return "- VLAN {$v['id']}: {$v['name']} ({$v['subnet']})";
    }, $k['aruba']['vlans']);
    
    // Aruba Ports
    $arubaPorts = array_map(function($p) {
        return "- Port {$p['port']}: {$p['description']} (VLAN {$p['vlan']})";
    }, $k['aruba']['ports']);
    
    return "You are an AI Assistant for FortiGate and Aruba Instant On network troubleshooting.
You have deep knowledge of the following network configuration:

=== DEVICE ===
- FortiGate: {$k['model']} (FortiOS {$k['firmware']})
- Mode: {$k['vdom_mode']}, HA: {$k['ha_mode']}
- Aruba Instant On: {$k['aruba']['model']} (Management IP: {$k['aruba']['management_ip']})

=== FORTIGATE INTERFACES ===
" . implode("\n", $interfaces) . "

=== FORTIGATE DHCP SERVERS ===
" . implode("\n", $dhcp) . "

=== FORTIGATE VLAN INTERFACES ===
" . implode("\n", array_map(function($n, $d) {
    return "- {$n}: {$d['ip']} (VLAN {$d['vlanid']})";
}, array_keys($k['vlan_interfaces']), $k['vlan_interfaces'])) . "

=== ARUBA INSTANT ON CONFIGURATION ===
- Uplink: {$k['aruba']['uplink']}
- Status: {$k['aruba']['status']}

ARUBA VLANS:
" . implode("\n", $arubaVlans) . "

ARUBA PORTS:
" . implode("\n", $arubaPorts) . "

=== FORTIGATE FEATURES ===
- SSL VPN: 10.212.134.200-210
- IPSec VPN: 2DMC tunnel
- ZTNA: enabled
- FortiLink: 10.255.1.1/24

=== RESPONSE RULES ===
1. Respond in English by default
2. If user asks in Indonesian, respond in Indonesian
3. Provide structured answers with:
   **📋 ANALYSIS:** [summary]
   **🔍 SOLUTION:** [step-by-step troubleshooting]
   **💡 RECOMMENDATION:** [additional suggestions]
4. Include CLI commands when relevant
5. For network topology questions, describe the full network layout including FortiGate, Aruba switch, and all VLANs

=== NETWORK TOPOLOGY ===
FortiGate 100F (10.20.11.254) 
  ├── WAN1 (VSAT2) - DHCP
  ├── WAN2 (Starlink2) - DHCP  
  ├── port2 (Starlink1) - DHCP
  ├── LAN (10.20.10.0/23) - Hard Switch
  │   ├── Aruba Instant On 1930 (10.20.11.241)
  │   │   ├── VLAN 1 (Default) - 10.20.10.0/23
  │   │   ├── VLAN 30 (MarineCrewWifi) - 10.30.11.0/24
  │   │   ├── VLAN 40 (ClientCrewWifi) - 10.40.11.0/24
  │   │   ├── VLAN 50 (PMT Wifi) - 10.50.11.0/24
  │   │   ├── VLAN 60 (Client Office) - 10.60.11.0/24
  │   │   ├── VLAN 70 (AppUpdate) - 10.70.11.0/24
  │   │   └── VLAN 9 (Resiliant-Wifi) - 10.9.10.0/24
  │   └── APs connected to Aruba ports
  ├── DMZ (10.10.10.0/24)
  ├── port12 (PABX-System) - 10.30.10.0/24
  ├── port20 (SWMGMT) - 10.20.12.0/24
  └── FortiLink (10.255.1.0/24)";
}

function callAIAPI($message, $conversation) {
    $system = buildSystemPrompt();
    $messages = [['role' => 'system', 'content' => $system]];
    foreach (array_slice($conversation, -10) as $m) {
        if (isset($m['role'], $m['content'])) {
            $messages[] = ['role' => $m['role'], 'content' => $m['content']];
        }
    }
    $messages[] = ['role' => 'user', 'content' => $message];
    
    $provider = defined('AI_PROVIDER') ? AI_PROVIDER : 'gemini';
    return ($provider === 'gemini') ? callGeminiAPI($messages) : callLocalKnowledge($message);
}

function callGeminiAPI($messages, $retry = 0) {
    if (!defined('GEMINI_API_KEY') || GEMINI_API_KEY === 'YOUR_GEMINI_API_KEY_HERE') {
        return ['error' => 'Gemini API Key not configured'];
    }
    
    $contents = [];
    foreach ($messages as $m) {
        $role = ($m['role'] === 'assistant') ? 'model' : 'user';
        $contents[] = ['role' => $role, 'parts' => [['text' => $m['content']]]];
    }
    
    $payload = [
        'contents' => $contents,
        'generationConfig' => [
            'temperature' => 0.3,
            'maxOutputTokens' => 2048,
            'topP' => 0.9
        ]
    ];
    
    $url = GEMINI_API_URL . '?key=' . GEMINI_API_KEY;
    logDebug('Calling Gemini API, model: ' . GEMINI_MODEL);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($code === 503 && $retry < 3) {
        logDebug('Model busy, retry ' . ($retry + 1) . '/3');
        sleep(2);
        return callGeminiAPI($messages, $retry + 1);
    }
    
    if ($code !== 200) {
        logDebug('Gemini API Error (HTTP ' . $code . '): ' . substr($response, 0, 200));
        $data = json_decode($response, true);
        $errorMsg = $data['error']['message'] ?? 'Unknown error';
        return ['error' => 'Gemini API Error (HTTP ' . $code . '): ' . $errorMsg];
    }
    
    $data = json_decode($response, true);
    if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
        return ['response' => $data['candidates'][0]['content']['parts'][0]['text']];
    }
    return ['error' => 'Unexpected Gemini response'];
}

function callLocalKnowledge($message) {
    $msg = strtolower($message);
    $lines = [];
    
    // Detect language preference
    $lang = 'en';
    if (strpos($msg, 'bahasa indonesia') !== false || strpos($msg, 'indonesia') !== false) {
        $lang = 'id';
    } elseif (strpos($msg, 'bahasa') !== false) {
        $lang = 'id';
    }
    
    if (strpos($msg, 'topology') !== false || strpos($msg, 'topologi') !== false) {
        $lines[] = ($lang === 'en') 
            ? "**📋 NETWORK TOPOLOGY**" 
            : "**📋 TOPOLOGI JARINGAN**";
        $lines[] = "";
        $lines[] = "```";
        $lines[] = "FortiGate 100F (10.20.11.254)";
        $lines[] = "  ├── WAN1 (VSAT2) - DHCP";
        $lines[] = "  ├── WAN2 (Starlink2) - DHCP";
        $lines[] = "  ├── port2 (Starlink1) - DHCP";
        $lines[] = "  ├── LAN (10.20.10.0/23) - Hard Switch";
        $lines[] = "  │   ├── Aruba Instant On 1930 (10.20.11.241)";
        $lines[] = "  │   │   ├── VLAN 1 (Default) - 10.20.10.0/23";
        $lines[] = "  │   │   ├── VLAN 30 (MarineCrewWifi) - 10.30.11.0/24";
        $lines[] = "  │   │   ├── VLAN 40 (ClientCrewWifi) - 10.40.11.0/24";
        $lines[] = "  │   │   ├── VLAN 50 (PMT Wifi) - 10.50.11.0/24";
        $lines[] = "  │   │   ├── VLAN 60 (Client Office) - 10.60.11.0/24";
        $lines[] = "  │   │   ├── VLAN 70 (AppUpdate) - 10.70.11.0/24";
        $lines[] = "  │   │   └── VLAN 9 (Resiliant-Wifi) - 10.9.10.0/24";
        $lines[] = "  │   └── APs (Aruba Instant On Access Points)";
        $lines[] = "  ├── DMZ (10.10.10.0/24)";
        $lines[] = "  ├── port12 (PABX-System) - 10.30.10.0/24";
        $lines[] = "  ├── port20 (SWMGMT) - 10.20.12.0/24";
        $lines[] = "  └── FortiLink (10.255.1.0/24)";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = ($lang === 'en')
            ? "**💡 RECOMMENDATION:** Use VLAN segregation for different user groups (Crew, Client, PMT, Office). All APs are managed by Aruba Instant On switch."
            : "**💡 REKOMENDASI:** Gunakan segregasi VLAN untuk group user yang berbeda (Crew, Client, PMT, Office). Semua AP dikelola oleh switch Aruba Instant On.";
        return ['response' => implode("\n", $lines)];
    }
    
    // Default: General FortiGate troubleshooting
    if (strpos($msg, 'dhcp') !== false || strpos($msg, 'ip') !== false) {
        $lines[] = ($lang === 'en')
            ? "**📋 ANALYSIS:** DHCP / Client IP assignment issue detected."
            : "**📋 ANALISIS:** Masalah DHCP / Client tidak mendapatkan IP.";
        $lines[] = "";
        $lines[] = "**🔍 " . (($lang === 'en') ? "TROUBLESHOOTING STEPS:" : "LANGKAH TROUBLESHOOTING:") . "**";
        $lines[] = "";
        $lines[] = "1. " . (($lang === 'en') ? "Check DHCP Server status:" : "Cek status DHCP Server:");
        $lines[] = "```";
        $lines[] = "show system dhcp server";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "2. " . (($lang === 'en') ? "View active leases:" : "Lihat leases aktif:");
        $lines[] = "```";
        $lines[] = "diagnose dhcp server lease";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "3. " . (($lang === 'en') ? "Check DHCP logs:" : "Cek log DHCP:");
        $lines[] = "```";
        $lines[] = "execute log display | grep -i dhcp";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "**📋 " . (($lang === 'en') ? "DHCP CONFIGURATION:" : "DHCP YANG DIKONFIGURASI:") . "**";
        $lines[] = "- **lan**: 10.20.11.1-253 & 10.20.10.2-253";
        $lines[] = "- **port12 (PABX)**: 10.30.10.2-253";
        $lines[] = "- **fortilink**: 10.255.1.2-254";
    } elseif (strpos($msg, 'vpn') !== false || strpos($msg, 'ssl') !== false) {
        $lines[] = ($lang === 'en')
            ? "**📋 ANALYSIS:** SSL VPN / Authentication issue detected."
            : "**📋 ANALISIS:** Masalah SSL VPN / Autentikasi.";
        $lines[] = "";
        $lines[] = "**🔍 " . (($lang === 'en') ? "TROUBLESHOOTING STEPS:" : "LANGKAH TROUBLESHOOTING:") . "**";
        $lines[] = "";
        $lines[] = "1. " . (($lang === 'en') ? "Check SSL VPN Status:" : "Cek Status SSL VPN:");
        $lines[] = "```";
        $lines[] = "get vpn ssl status";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "2. " . (($lang === 'en') ? "View connected users:" : "Lihat user terhubung:");
        $lines[] = "```";
        $lines[] = "get vpn ssl users";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "3. " . (($lang === 'en') ? "Check authentication log:" : "Cek log autentikasi:");
        $lines[] = "```";
        $lines[] = "diagnose debug application sslvpn -1";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "**💡 RECOMMENDATION:** SSL VPN Address Pool: **10.212.134.200-210**";
        $lines[] = "- Verify username/password with `show user local`";
    } elseif (strpos($msg, 'wan') !== false || strpos($msg, 'internet') !== false) {
        $lines[] = ($lang === 'en')
            ? "**📋 ANALYSIS:** WAN / Internet connectivity issue detected."
            : "**📋 ANALISIS:** Masalah Koneksi WAN / Internet.";
        $lines[] = "";
        $lines[] = "**🔍 " . (($lang === 'en') ? "TROUBLESHOOTING STEPS:" : "LANGKAH TROUBLESHOOTING:") . "**";
        $lines[] = "";
        $lines[] = "1. " . (($lang === 'en') ? "Check WAN Interface Status:" : "Cek Status Interface WAN:");
        $lines[] = "```";
        $lines[] = "get system interface physical | grep -E 'wan1|wan2|port2'";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "2. " . (($lang === 'en') ? "Test connectivity:" : "Test koneksi:");
        $lines[] = "```";
        $lines[] = "execute ping 8.8.8.8";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "**📋 WAN CONFIGURATION:**";
        $lines[] = "- wan1 (VSAT2): DHCP";
        $lines[] = "- wan2 (Starlink2): DHCP";
        $lines[] = "- port2 (Starlink1): DHCP";
        $lines[] = "- DNS: 96.45.45.45 / 96.45.46.46";
    } elseif (strpos($msg, 'block') !== false || strpos($msg, 'ips') !== false) {
        $lines[] = ($lang === 'en')
            ? "**📋 ANALYSIS:** IPS Blocking / Security issue detected."
            : "**📋 ANALISIS:** Masalah Blokir IPS / Keamanan.";
        $lines[] = "";
        $lines[] = "**🔍 " . (($lang === 'en') ? "TROUBLESHOOTING STEPS:" : "LANGKAH TROUBLESHOOTING:") . "**";
        $lines[] = "";
        $lines[] = "1. " . (($lang === 'en') ? "Check IPS Sensor:" : "Cek IPS Sensor:");
        $lines[] = "```";
        $lines[] = "show ips sensor high_security";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "2. " . (($lang === 'en') ? "Check IPS logs:" : "Lihat log IPS:");
        $lines[] = "```";
        $lines[] = "execute log display | grep -i ips";
        $lines[] = "```";
        $lines[] = "";
        $lines[] = "**💡 RECOMMENDATION:**";
        $lines[] = "- IPS Sensors: high_security, protect_http_server, protect_client";
        $lines[] = "- URL Filter blocks: instagram, gthost, apple, speedtest";
    } else {
        $lines[] = ($lang === 'en')
            ? "**📋 ANALYSIS:** I'm ready to help with FortiGate & Aruba Instant On troubleshooting."
            : "**📋 ANALISIS:** Saya siap membantu troubleshooting FortiGate & Aruba Instant On.";
        $lines[] = "";
        $lines[] = "**💡 " . (($lang === 'en') ? "ASK ABOUT:" : "COBA TANYAKAN:") . "**";
        $lines[] = "";
        $lines[] = "🔹 **Network Issues:**";
        $lines[] = "   - \"WAN1 cannot get IP\" / \"WAN1 tidak dapat IP\"";
        $lines[] = "   - \"Client cannot get IP from DHCP\" / \"Client tidak dapat IP dari DHCP\"";
        $lines[] = "";
        $lines[] = "🔹 **VPN Issues:**";
        $lines[] = "   - \"SSL VPN authentication error\" / \"SSL VPN error authentication\"";
        $lines[] = "";
        $lines[] = "🔹 **Security Issues:**";
        $lines[] = "   - \"IPS blocking traffic\" / \"IPS memblokir traffic\"";
        $lines[] = "";
        $lines[] = "🔹 **Network Topology:**";
        $lines[] = "   - \"Show network topology\" / \"Tampilkan topologi jaringan\"";
        $lines[] = "";
        $lines[] = "📋 **Devices:** FortiGate 100F + Aruba Instant On 1930";
    }
    
    $lines[] = "";
    $lines[] = "---";
    $lines[] = "🤖 *AI Assistant*";
    $lines[] = "⏱️ " . date('d-m-Y H:i:s');
    
    return ['response' => implode("\n", $lines)];
}

logDebug('Processing message: ' . substr($message, 0, 100));
$result = callAIAPI($message, $conversation);

if (isset($result['error'])) {
    logDebug('API Error: ' . $result['error'] . ', using local knowledge');
    $local = callLocalKnowledge($message);
    $result = ['response' => $local['response'], 'source' => 'local'];
} else {
    $result['source'] = 'api';
}

echo json_encode($result);
?>