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

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

function chat_error($code, $message) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function chat_path_encode($path) {
    $parts = array_filter(explode('/', trim((string) $path, '/')), 'strlen');
    if (!$parts) return '';
    return implode('/', array_map('rawurlencode', $parts));
}

function chat_rtdb_patch($dbUrl, $path, $accessToken, $data) {
    $base = rtrim($dbUrl, '/');
    $encodedPath = chat_path_encode($path);
    $url = $base . '/' . $encodedPath . '.json';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => 'PATCH',
        CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $accessToken,
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);
    $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 >= 400) return false;
    return true;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') chat_error(405, 'Method not allowed');
if (!function_exists('curl_init')) chat_error(503, 'PHP curl extension is required.');

$raw = file_get_contents('php://input');
$body = json_decode($raw !== false && $raw !== '' ? $raw : '{}', true);
if (!is_array($body)) chat_error(400, 'Invalid JSON');

$clientId = isset($body['clientId']) ? trim((string) $body['clientId']) : '';
$messages = isset($body['messages']) && is_array($body['messages']) ? $body['messages'] : [];
if ($clientId === '' || !preg_match('/^[-A-Za-z0-9_]{1,128}$/', $clientId)) chat_error(400, 'Valid clientId is required.');

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) chat_error(503, 'Server not configured.');
$boot = include $bootPath;
if (!is_array($boot)) chat_error(503, 'Invalid bootstrap file.');

$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 === '') chat_error(503, 'Bootstrap missing required values.');

$tok = firebase_service_account_access_token($saPath);
if (isset($tok['error'])) chat_error(503, 'Firebase admin error: ' . $tok['error']);
$access = $tok['access_token'];

$settingsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/siteSettings', $access);
if (isset($settingsSnap['error'])) chat_error(503, 'Could not load site settings.');
$settings = is_array($settingsSnap['data']) ? $settingsSnap['data'] : [];
$openaiKey = trim((string) ($settings['openaiApiKey'] ?? ''));
$model = trim((string) ($settings['openaiModel'] ?? 'gpt-4o-mini'));
if ($openaiKey === '') chat_error(400, 'OpenAI API Key not found in Site Settings.');

$dateKey = gmdate('Y-m-d');
$usagePath = 'clients/' . $clientId . '/aiBrain/usage/' . $dateKey;
$usageSnap = firebase_rtdb_get($dbUrl, $usagePath, $access);
$usageCount = 0;
if (!isset($usageSnap['error']) && isset($usageSnap['data']['chat']) && is_numeric($usageSnap['data']['chat'])) {
    $usageCount = (int) $usageSnap['data']['chat'];
}
if ($usageCount >= 400) chat_error(429, 'Daily AI chat limit reached (400).');

$productsSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/products', $access);
$ordersSnap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/orders', $access);
$products = !isset($productsSnap['error']) && is_array($productsSnap['data']) ? $productsSnap['data'] : [];
$orders = !isset($ordersSnap['error']) && is_array($ordersSnap['data']) ? $ordersSnap['data'] : [];

$topProducts = [];
foreach ($products as $p) {
    if (!is_array($p)) continue;
    $name = trim((string) ($p['name'] ?? ''));
    if ($name !== '') $topProducts[] = $name;
    if (count($topProducts) >= 5) break;
}

$topCategories = [];
foreach ($products as $p) {
    if (!is_array($p)) continue;
    if (isset($p['categories']) && is_array($p['categories'])) {
        foreach ($p['categories'] as $c) {
            $v = trim((string) $c);
            if ($v !== '') $topCategories[] = $v;
        }
    } else {
        $c = trim((string) ($p['category'] ?? ''));
        if ($c !== '') $topCategories[] = $c;
    }
}
$topCategories = array_slice(array_values(array_unique($topCategories)), 0, 3);

$nowMs = round(microtime(true) * 1000);
$sevenDaysAgo = $nowMs - (7 * 24 * 60 * 60 * 1000);
$orderCount7d = 0;
$revenue7d = 0.0;
foreach ($orders as $o) {
    if (!is_array($o)) continue;
    $ts = isset($o['createdAt']) ? (int) $o['createdAt'] : 0;
    if ($ts < $sevenDaysAgo) continue;
    $orderCount7d++;
    $revenue7d += (float) ($o['totalBill'] ?? 0);
}

$siteName = trim((string) ($settings['siteName'] ?? 'Your store'));
$systemContext = [
    'site_name' => $siteName,
    'top_products' => $topProducts,
    'top_categories' => $topCategories,
    'orders_last_7d' => $orderCount7d,
    'revenue_last_7d_bdt' => round($revenue7d, 2),
    'market' => 'Bangladesh ecommerce',
];

$safeMessages = [];
foreach ($messages as $m) {
    if (!is_array($m)) continue;
    $role = strtolower(trim((string) ($m['role'] ?? 'user')));
    if ($role !== 'assistant' && $role !== 'user') continue;
    $content = trim((string) ($m['content'] ?? ''));
    if ($content === '') continue;
    $safeMessages[] = ['role' => $role, 'content' => mb_substr($content, 0, 1200)];
}
if (!$safeMessages) chat_error(400, 'At least one message is required.');
$safeMessages = array_slice($safeMessages, -12);

$modelMessages = [
    [
        'role' => 'system',
        'content' => 'You are Marketers Brain, a practical Bangla ecommerce growth assistant. Give concise, actionable answers with clear steps. Use simple Bangla language. Context: ' . json_encode($systemContext, JSON_UNESCAPED_UNICODE),
    ],
];
foreach ($safeMessages as $m) $modelMessages[] = $m;

$req = [
    'model' => $model !== '' ? $model : 'gpt-4o-mini',
    'temperature' => 0.6,
    'max_tokens' => 500,
    'messages' => $modelMessages,
];

$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 => 45,
]);
$res = curl_exec($ch);
$errno = curl_errno($ch);
$http = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno !== 0 || $res === false) chat_error(502, 'Could not reach OpenAI API.');

$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'];
    chat_error($http, $msg);
}

$content = '';
if (is_array($decoded) && isset($decoded['choices'][0]['message']['content'])) $content = trim((string) $decoded['choices'][0]['message']['content']);
if ($content === '') chat_error(502, 'Empty response from OpenAI.');

$assistantMessage = [
    'role' => 'assistant',
    'content' => mb_substr($content, 0, 4000),
];

chat_rtdb_patch($dbUrl, $usagePath, $access, [
    'chat' => $usageCount + 1,
    'updatedAt' => $nowMs,
]);

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