<?php
/**
 * chat.php - AI Backend untuk Mooring Winch AI
 * Menggunakan Gemini API via config.php
 */

// ============================================================
// 1. LOAD CONFIG
// ============================================================
require_once __DIR__ . '/config.php';

// ============================================================
// 2. CORS HEADERS
// ============================================================
header('Content-Type: application/json');

// Izinkan origin yang sama dengan ALLOWED_ORIGIN, atau * jika di-set '*'
$requestOrigin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowedOrigin = ALLOWED_ORIGIN;
if ($allowedOrigin === '*' || $requestOrigin === $allowedOrigin || empty($requestOrigin)) {
    header('Access-Control-Allow-Origin: ' . ($allowedOrigin === '*' ? '*' : $requestOrigin));
} else {
    // Fallback: izinkan juga jika request dari host yang sama (same-origin, no Origin header)
    header('Access-Control-Allow-Origin: ' . $allowedOrigin);
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

// ============================================================
// 3. SYSTEM PROMPTS
// ============================================================
$SYSTEM_PROMPT_EN = "You are Mooring AI Assistant, expert in Unidrive SP drives, mooring winches, and CTSoft exports.

⚠️ LANGUAGE RULES:
- If user asks in ENGLISH → respond in ENGLISH
- If user asks in INDONESIAN → respond in INDONESIAN
- NEVER mix languages

KEY KNOWLEDGE:
- SL1 Trip: Encoder signal loss. Check encoder cable, feedback module, power supply.
- Fault 7: Motor thermistor over-temperature. Check cooling, reduce load.
- Fault 2: Overcurrent (OI.br). Check motor parameters, load, wiring.
- CTSoft: Export .csv or .txt files for drive parameter analysis.
- Menu 1: Speed, Menu 2: Ramps, Menu 5: Motor, Menu 10: Trips.

Respond professionally, clearly, and helpfully. Use bullet points if needed.";

$SYSTEM_PROMPT_ID = "Anda adalah Mooring AI Assistant, ahli dalam Unidrive SP, mooring winch, dan CTSoft.

⚠️ ATURAN BAHASA:
- Jika pengguna bertanya dalam BAHASA INDONESIA → jawab dalam BAHASA INDONESIA
- Jika pengguna bertanya dalam BAHASA INGGRIS → jawab dalam BAHASA INGGRIS
- JANGAN PERNAH mencampur bahasa

PENGETAHUAN UTAMA:
- SL1 Trip: Encoder signal loss. Cek kabel encoder, modul feedback, power supply.
- Fault 7: Motor thermistor over-temperature. Cek cooling, kurangi beban.
- Fault 2: Overcurrent (OI.br). Cek parameter motor, beban, wiring.
- CTSoft: Export file .csv atau .txt untuk analisis parameter drive.
- Menu 1: Speed, Menu 2: Ramps, Menu 5: Motor, Menu 10: Trips.

Jawab dengan profesional, jelas, dan membantu. Gunakan bullet points jika perlu.";

// ============================================================
// 4. DETEKSI BAHASA
// ============================================================
function detectLanguage($text) {
    $idPatterns = ['kalibrasi', 'cara', 'bagaimana', 'apa', 'yang', 'di', 'ke', 'dari', 'untuk', 'dengan', 'pada', 'saya', 'anda', 'bisa', 'apakah'];
    $enPatterns = ['how', 'what', 'is', 'are', 'the', 'to', 'for', 'with', 'from', 'calibrate', 'troubleshoot', 'step', 'does', 'do', 'can'];

    $lower = strtolower($text);
    $idScore = 0;
    $enScore = 0;

    foreach ($idPatterns as $p) {
        if (strpos($lower, $p) !== false) $idScore++;
    }
    foreach ($enPatterns as $p) {
        if (strpos($lower, $p) !== false) $enScore++;
    }

    return ($idScore > $enScore) ? 'id' : 'en';
}

// ============================================================
// 5. VALIDASI API KEY
// ============================================================
if (!defined('GEMINI_API_KEY') || GEMINI_API_KEY === 'YOUR_GEMINI_API_KEY_HERE' || empty(GEMINI_API_KEY)) {
    http_response_code(500);
    echo json_encode(['error' => 'Gemini API Key belum dikonfigurasi. Edit api/config.php dan isi GEMINI_API_KEY.']);
    exit();
}

// ============================================================
// 6. PROCESS REQUEST
// ============================================================
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid request']);
    exit();
}

$messages    = $input['messages']    ?? [];
$system      = $input['system']      ?? null;
$max_tokens  = $input['max_tokens']  ?? 1024;
$temperature = $input['temperature'] ?? 0.3;

// Tentukan system prompt
if (!empty($system)) {
    $finalSystem = $system;
} else {
    $lastMessage = '';
    if (!empty($messages)) {
        $last = end($messages);
        if ($last && isset($last['content'])) {
            $lastMessage = $last['content'];
        }
    }
    $lang = detectLanguage($lastMessage);
    $finalSystem = ($lang === 'id') ? $SYSTEM_PROMPT_ID : $SYSTEM_PROMPT_EN;
}

$history = array_slice($messages, -10);

// ============================================================
// 7. BANGUN CONTENTS UNTUK GEMINI
// ============================================================
// Gemini tidak punya field "system" terpisah — inject ke pesan pertama user
$contents = [];

foreach ($history as $index => $msg) {
    $role    = ($msg['role'] === 'assistant') ? 'model' : 'user';
    $content = $msg['content'] ?? '';

    // Sisipkan system prompt di depan pesan user pertama
    if ($index === 0 && $role === 'user') {
        $content = $finalSystem . "\n\n" . $content;
    }

    $contents[] = [
        'role'  => $role,
        'parts' => [['text' => $content]]
    ];
}

// Pastikan array tidak kosong
if (empty($contents)) {
    http_response_code(400);
    echo json_encode(['error' => 'No messages provided']);
    exit();
}

// ============================================================
// 8. CALL GEMINI API
// ============================================================
$geminiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/'
           . GEMINI_MODEL
           . ':generateContent?key='
           . GEMINI_API_KEY;

$payload = [
    'contents'         => $contents,
    'generationConfig' => [
        'temperature'     => (float)$temperature,
        'maxOutputTokens' => (int)$max_tokens
    ]
];

// Debug log
$debugLog  = date('Y-m-d H:i:s') . " - Request to Gemini\n";
$debugLog .= "Model: " . GEMINI_MODEL . "\n";
$debugLog .= "Messages: " . count($messages) . "\n";

$ch = curl_init($geminiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

$debugLog .= "HTTP Code: " . $httpCode . "\n";
$debugLog .= "Response: " . substr($response, 0, 500) . "\n\n";
file_put_contents(__DIR__ . '/debug.log', $debugLog, FILE_APPEND);

// ============================================================
// 9. RESPONSE
// ============================================================
if ($curlError) {
    http_response_code(500);
    echo json_encode(['error' => 'Curl error: ' . $curlError]);
    exit();
}

$data = json_decode($response, true);

if ($httpCode !== 200) {
    $errorMsg = $data['error']['message'] ?? 'Gemini API error';
    http_response_code($httpCode);
    echo json_encode(['error' => $errorMsg]);
    exit();
}

// Ekstrak teks dari Gemini response
$replyText = $data['candidates'][0]['content']['parts'][0]['text'] ?? 'No response.';

// Kembalikan dalam format yang kompatibel dengan frontend
http_response_code(200);
echo json_encode([
    'reply'   => $replyText,
    'model'   => GEMINI_MODEL,
    'usage'   => $data['usageMetadata'] ?? null
]);
?>
