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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') intel_error(405, 'Method not allowed');
if (!function_exists('curl_init')) intel_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)) intel_error(400, 'Invalid JSON');

$metrics = isset($body['metrics']) && is_array($body['metrics']) ? $body['metrics'] : null;
if (!$metrics) intel_error(400, 'Metrics payload is required.');

$openaiKey = getenv('OPENAI_API_KEY');
if (!is_string($openaiKey) || trim($openaiKey) === '') {
    // Fallback for environments where env vars are not configured yet.
    $openaiKey = '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';
}
$openaiKey = trim((string) $openaiKey);
if ($openaiKey === '') intel_error(503, 'OpenAI API key is not configured.');

$req = [
    'model' => 'gpt-4o-mini',
    'response_format' => ['type' => 'json_object'],
    'temperature' => 0.4,
    'messages' => [
        [
            'role' => 'system',
            'content' => 'You are an ecommerce analytics assistant. Return concise, actionable insights as strict JSON.'
        ],
        [
            'role' => 'user',
            'content' => json_encode([
                'task' => 'Analyze store metrics and provide 4 short actionable insights.',
                'outputSchema' => [
                    'revenueInsight' => 'string',
                    'timingInsight' => 'string',
                    'geoInsight' => 'string',
                    'retentionInsight' => 'string'
                ],
                'metrics' => $metrics
            ], JSON_UNESCAPED_UNICODE)
        ]
    ]
];

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

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

$insights = json_decode($content, true);
if (!is_array($insights)) intel_error(502, 'Invalid AI JSON response.');

echo json_encode([
    'status' => 'success',
    'insights' => [
        'revenueInsight' => (string) ($insights['revenueInsight'] ?? ''),
        'timingInsight' => (string) ($insights['timingInsight'] ?? ''),
        'geoInsight' => (string) ($insights['geoInsight'] ?? ''),
        'retentionInsight' => (string) ($insights['retentionInsight'] ?? ''),
    ]
], JSON_UNESCAPED_UNICODE);

