<?php
/**
 * chat.php - AI Backend untuk OffshoreAI Landing Page
 * Menggunakan Groq API (Llama 3.3)
 * Arsitektur SAMA dengan Clyde 37-DE (sudah berhasil)
 */

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

// ============================================================
// 2. CORS HEADERS
// ============================================================
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: ' . ALLOWED_ORIGIN);
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();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed. Gunakan POST.']);
    exit();
}

// ============================================================
// 3. RATE LIMITING
// ============================================================
if (RATE_LIMIT_PER_HOUR > 0) {
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $rateDir = __DIR__ . '/_ratelimit';
    if (!is_dir($rateDir)) { @mkdir($rateDir, 0755, true); }
    $rateFile = $rateDir . '/' . md5($ip) . '.json';
    $hourKey = date('YmdH');

    $data = ['hour' => $hourKey, 'count' => 0];
    if (file_exists($rateFile)) {
        $existing = json_decode(file_get_contents($rateFile), true);
        if ($existing && $existing['hour'] === $hourKey) {
            $data = $existing;
        }
    }
    $data['count']++;
    @file_put_contents($rateFile, json_encode($data));

    if ($data['count'] > RATE_LIMIT_PER_HOUR) {
        http_response_code(429);
        echo json_encode(['error' => 'Rate limit tercapai. Coba lagi nanti.']);
        exit();
    }
}

// ============================================================
// 4. VALIDASI API KEY
// ============================================================
if (GROQ_API_KEY === 'PASTE_GROQ_API_KEY_KAMU_DISINI' || empty(GROQ_API_KEY)) {
    http_response_code(500);
    echo json_encode(['error' => 'Server belum dikonfigurasi: API key Groq belum diisi di config.php']);
    exit();
}

// ============================================================
// 5. SYSTEM PROMPT - OFFSHOREAI (bilingual)
// ============================================================
$SYSTEM_PROMPT_ID = "Anda adalah OffshoreAI Assistant untuk offshoreai.biz.id.

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

TENTANG OFFSHOREAI:
OffshoreAI adalah platform AI Diagnostic untuk industri marine dan offshore.

PRODUK TERSEDIA:
1. Mooring Winch AI: http://mw.offshoreai.biz.id/
2. Crane Diagnostic AI: https://zpmc-crane.offshoreai.biz.id/
3. Clyde 37-DE · RCI-1550: https://clyde.offshoreai.biz.id/
   Fitur: Load Cell Calibration (F-02, F-03), Boom Angle & Length (F-08, F-09), ATB / Over-hoist (Error 220), CPU Box Troubleshooting (10 steps), Rigging Mode, Data Logger (F-34, F-35), Complete F-Code List (F-00 to F-76)
4. Engine Room Copilot: https://ecr.offshoreai.biz.id/
5. ICT Solutions: https://offshoreai.biz.id/payment.html

MANFAAT: 80% faster troubleshooting, 70% reduced diagnostic time, 24/7 AI assistance.

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

$SYSTEM_PROMPT_EN = "You are the OffshoreAI Assistant for offshoreai.biz.id.

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

ABOUT OFFSHOREAI:
OffshoreAI is an AI Diagnostic platform for marine and offshore industries.

AVAILABLE PRODUCTS:
1. Mooring Winch AI: http://mw.offshoreai.biz.id/
2. Crane Diagnostic AI: https://zpmc-crane.offshoreai.biz.id/
3. Clyde 37-DE · RCI-1550: https://clyde.offshoreai.biz.id/
   Features: Load Cell Calibration (F-02, F-03), Boom Angle & Length (F-08, F-09), ATB / Over-hoist (Error 220), CPU Box Troubleshooting (10 steps), Rigging Mode, Data Logger (F-34, F-35), Complete F-Code List (F-00 to F-76)
4. Engine Room Copilot: https://ecr.offshoreai.biz.id/
5. ICT Solutions: https://offshoreai.biz.id/payment.html

BENEFITS: 80% faster troubleshooting, 70% reduced diagnostic time, 24/7 AI assistance.

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

// ============================================================
// 6. DETEKSI BAHASA (fallback)
// ============================================================
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';
}

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

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

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

// 🔧 PRIORITAS: Gunakan system dari frontend jika ada (sama seperti Clyde)
if (!empty($system)) {
    $finalSystem = $system;
} else {
    // Fallback: deteksi bahasa dari pesan terakhir
    $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);

// ============================================================
// 8. CALL GROQ API
// ============================================================
$payload = [
    'model' => GROQ_MODEL,
    'messages' => array_merge(
        [['role' => 'system', 'content' => $finalSystem]],
        $history
    ),
    'max_tokens' => $max_tokens,
    'temperature' => $temperature
];

$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . GROQ_API_KEY
]);
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);

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

if ($httpCode !== 200) {
    $errorData = json_decode($response, true);
    $errorMsg = $errorData['error']['message'] ?? 'Unknown API error';
    
    // Jika model decommissioned, coba fallback ke model lain
    if (strpos($errorMsg, 'decommissioned') !== false) {
        $fallbackModels = ['llama-3.3-70b-versatile', 'llama-3.1-8b-instant', 'mixtral-8x7b-32768'];
        foreach ($fallbackModels as $model) {
            if ($model === GROQ_MODEL) continue;
            
            $payload['model'] = $model;
            $ch2 = curl_init('https://api.groq.com/openai/v1/chat/completions');
            curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch2, CURLOPT_POST, true);
            curl_setopt($ch2, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Authorization: Bearer ' . GROQ_API_KEY
            ]);
            curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch2, CURLOPT_TIMEOUT, 30);
            $response2 = curl_exec($ch2);
            $httpCode2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
            curl_close($ch2);
            
            if ($httpCode2 === 200) {
                http_response_code(200);
                echo $response2;
                exit();
            }
        }
    }
    
    http_response_code($httpCode);
    echo json_encode([
        'error' => $errorMsg,
        'http_code' => $httpCode,
        'fallback' => true
    ]);
    exit();
}

http_response_code(200);
echo $response;
?>