<?php
// ============================================================
// chat.php — Proxy ke Groq API untuk ZPMC Crane AI Dashboard
// ============================================================
// Dashboard HTML memanggil endpoint ini, bukan Groq langsung.
// API key disimpan di server (config.php), tidak terlihat di browser.
// ============================================================

require_once __DIR__ . '/config.php';

// --- CORS ---
header('Access-Control-Allow-Origin: ' . ALLOWED_ORIGIN);
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// Browser kadang kirim OPTIONS dulu (preflight) sebelum POST
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;
}

// --- Rate limiting sederhana berbasis file (per IP, per jam) ---
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;
    }
}

// --- Validasi API key sudah diisi ---
if (GROQ_API_KEY === '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' || empty(GROQ_API_KEY)) {
    http_response_code(500);
    echo json_encode(['error' => 'Server belum dikonfigurasi: API key Groq belum diisi di config.php']);
    exit;
}

// --- Ambil body request dari dashboard ---
$rawInput = file_get_contents('php://input');
$payload = json_decode($rawInput, true);

if (!$payload || !isset($payload['messages']) || !is_array($payload['messages'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Request tidak valid. Field "messages" wajib ada dan berupa array.']);
    exit;
}

// --- Susun ulang request untuk Groq, pakai system prompt dari dashboard kalau ada ---
$messages = [];
if (!empty($payload['system'])) {
    $messages[] = ['role' => 'system', 'content' => $payload['system']];
}
foreach ($payload['messages'] as $m) {
    if (isset($m['role']) && isset($m['content'])) {
        $messages[] = ['role' => $m['role'], 'content' => $m['content']];
    }
}

$groqBody = [
    'model'       => GROQ_MODEL,
    'max_tokens'  => $payload['max_tokens'] ?? 1000,
    'temperature' => $payload['temperature'] ?? 0.3,
    'messages'    => $messages,
];

// --- Kirim ke Groq via cURL ---
$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . GROQ_API_KEY,
    ],
    CURLOPT_POSTFIELDS     => json_encode($groqBody),
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_SSL_VERIFYPEER => true,
]);

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

if ($response === false) {
    http_response_code(502);
    echo json_encode(['error' => 'Gagal terhubung ke Groq API: ' . $curlError]);
    exit;
}

// --- Teruskan response Groq apa adanya ke dashboard ---
http_response_code($httpCode);
echo $response;
