<?php
header('Content-Type: application/json; charset=UTF-8');

require_once __DIR__ . '/firebase-rtdb-admin.php';

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

if (!function_exists('curl_init')) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'PHP curl extension is required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid JSON'], JSON_UNESCAPED_UNICODE);
    exit;
}

$clientId = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
if ($clientId === '' || !preg_match('/^[-A-Za-z0-9_]{1,128}$/', $clientId)) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Valid clientId is required.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Server not configured.'], JSON_UNESCAPED_UNICODE);
    exit;
}
$boot = include $bootPath;
if (!is_array($boot)) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Invalid bootstrap file.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$saPath = isset($boot['service_account_json_path']) ? trim((string) $boot['service_account_json_path']) : '';
$dbUrl = isset($boot['firebase_database_url']) ? trim((string) $boot['firebase_database_url']) : '';
if ($saPath === '' || $dbUrl === '') {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Bootstrap missing required values.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$tok = firebase_service_account_access_token($saPath);
if (isset($tok['error'])) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Firebase admin error: ' . $tok['error']], JSON_UNESCAPED_UNICODE);
    exit;
}
$access = $tok['access_token'];
$settingsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $access);
if (isset($settingsSnap['error'])) {
    http_response_code(503);
    echo json_encode(['status' => 'error', 'message' => 'Could not load site settings.'], JSON_UNESCAPED_UNICODE);
    exit;
}
$settings = is_array($settingsSnap['data']) ? $settingsSnap['data'] : [];
$openaiKey = trim((string) ($settings['openaiApiKey'] ?? ''));
$model = trim((string) ($settings['openaiModel'] ?? 'gpt-4o-mini'));

if ($openaiKey === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'OpenAI API key not found in site settings.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$req = [
    'model' => $model !== '' ? $model : 'gpt-4o-mini',
    'temperature' => 0.2,
    'max_tokens' => 40,
    'messages' => [
        ['role' => 'system', 'content' => 'Reply with one short line only.'],
        ['role' => 'user', 'content' => 'Connection test from dashboard. Return OK.'],
    ],
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($req, JSON_UNESCAPED_UNICODE),
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $openaiKey,
    ],
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 25,
]);
$res = curl_exec($ch);
$errno = curl_errno($ch);
$http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno !== 0 || $res === false) {
    http_response_code(502);
    echo json_encode(['status' => 'error', 'message' => 'Could not reach OpenAI API.'], JSON_UNESCAPED_UNICODE);
    exit;
}

$decoded = json_decode($res, true);
if ($http >= 400) {
    $msg = 'OpenAI request failed.';
    if (is_array($decoded) && isset($decoded['error']['message'])) $msg = (string) $decoded['error']['message'];
    http_response_code($http);
    echo json_encode(['status' => 'error', 'message' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

echo json_encode([
    'status' => 'success',
    'model' => $req['model'],
], JSON_UNESCAPED_UNICODE);
