<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Your Grok API key
$apiKey = 'cc435f0b-5d10-4e98-a45e-3a47ca8e6a4a';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_FILES['image'])) {
    echo json_encode(['error' => 'No image uploaded']);
    exit;
}

$imagePath = $_FILES['image']['tmp_name'];
$imageData = base64_encode(file_get_contents($imagePath));
$mime = $_FILES['image']['type'] ?: 'image/jpeg';

$payload = [
    'model' => 'grok-4-fast',
    'messages' => [
        [
            'role' => 'user',
            'content' => [
                [
                    'type' => 'text',
                    'text' => 'Estimate the calories and macros for this meal. Return ONLY valid JSON with these keys: {"name":"meal name","calories":0,"protein":0,"carbs":0,"fat":0,"confidence":"low|medium|high"}'
                ],
                [
                    'type' => 'image_url',
                    'image_url' => ['url' => "data:$mime;base64,$imageData"]
                ]
            ]
        ]
    ],
    'temperature' => 0.2
];

$ch = curl_init('https://api.x.ai/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
    CURLOPT_TIMEOUT => 30
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
$content = $data['choices'][0]['message']['content'] ?? '';

// Try to extract JSON from the response
if (preg_match('/\{.*\}/s', $content, $matches)) {
    $result = json_decode($matches[0], true);
    if ($result) {
        echo json_encode($result);
        exit;
    }
}

echo json_encode(['error' => 'Could not parse estimate', 'raw' => $content]);