<?php
/**
 * groq-proxy.php
 * -----------------------------------------------------------------
 * Server-side proxy for the Clyde 37-DE / RCI-1550 dashboard's AI
 * Troubleshooting Assistant, to be hosted on cPanel alongside the
 * dashboard HTML file.
 *
 * Why this exists: Groq's API key must NEVER be exposed in browser
 * JavaScript. This script keeps the key on the server and simply
 * forwards the chat request to Groq, then relays the response back.
 *
 * SETUP ON CPANEL
 * 1. Upload this file to your hosting (e.g. public_html/groq-proxy.php).
 * 2. Create your Groq API key at https://console.groq.com
 * 3. Set the key using ONE of the two methods below (Method A is safer).
 * 4. In the dashboard HTML, set GROQ_PROXY_URL to the full path of
 *    this file once uploaded, e.g. "https://yourdomain.com/groq-proxy.php"
 * -----------------------------------------------------------------
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');      // tighten to your own domain once live
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

/* ---------------------------------------------------------------
 * METHOD A (recommended): key stored in a file OUTSIDE public_html
 * e.g. /home/yourcpaneluser/groq-secret.php containing only:
 *   <?php return 'gsk_xxxxxxxxxxxxxxxxxxxxx';
 * Adjust the path below to match your actual home directory.
 * ------------------------------------------------------------- */
$secretFile = dirname(__DIR__) . '/groq-secret.php';
$apiKey = is_file($secretFile) ? include $secretFile : null;

/* ---------------------------------------------------------------
 * METHOD B (quick start, less safe): paste your key directly below.
 * Only use this if Method A isn't practical, and make sure this
 * .php file itself is never served as plain text by your host.
 * ------------------------------------------------------------- */
if (!$apiKey) {
    $apiKey = ''; // <-- paste your Groq key here as a fallback, e.g. 'gsk_...'
}

if (!$apiKey) {
    http_response_code(500);
    echo json_encode(['error' => 'Server is missing a Groq API key. See setup notes in groq-proxy.php.']);
    exit;
}

$incoming = file_get_contents('php://input');
$payload = json_decode($incoming, true);

if (!is_array($payload) || empty($payload['messages'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Request body must include a "messages" array.']);
    exit;
}

// Force a sane default model/limit if the client didn't set one.
if (empty($payload['model'])) {
    $payload['model'] = 'llama-3.3-70b-versatile';
}
if (empty($payload['max_tokens']) && empty($payload['max_completion_tokens'])) {
    $payload['max_completion_tokens'] = 1000;
}

$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlErr  = curl_error($ch);
curl_close($ch);

if ($response === false) {
    http_response_code(502);
    echo json_encode(['error' => 'Could not reach Groq: ' . $curlErr]);
    exit;
}

http_response_code($httpCode ?: 502);
echo $response;
