<?php
/**
 * AI Extraction endpoint — calls Groq API (free, no billing) to extract
 * purchase/sales data from uploaded invoice images.
 *
 * POST params:
 *   file     - uploaded image (JPG, PNG, WEBP, GIF)
 *   type     - "purchase" or "sales"
 *
 * Get a free Groq API key (no credit card) at: https://console.groq.com
 */
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/config.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Invalid request']);
    exit;
}

$apiKey = defined('GROQ_API_KEY') ? GROQ_API_KEY : '';
if (empty($apiKey)) {
    echo json_encode(['error' => 'Groq API key not configured. Get a free key (no credit card) at console.groq.com and set GROQ_API_KEY in includes/config.php']);
    exit;
}

if (empty($_FILES['file']['tmp_name'])) {
    echo json_encode(['error' => 'No file uploaded']);
    exit;
}

$type     = $_POST['type'] ?? 'purchase';
$tmpPath  = $_FILES['file']['tmp_name'];
$mimeType = mime_content_type($tmpPath);

// Groq vision does not support PDF — images only
if ($mimeType === 'application/pdf') {
    echo json_encode(['error' => 'PDF not supported by Groq vision. Please take a photo or screenshot of the invoice and upload that instead (JPG/PNG).']);
    exit;
}

if (!in_array($mimeType, ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'])) {
    echo json_encode(['error' => 'Unsupported file type. Please upload a JPG, PNG, or WEBP image.']);
    exit;
}

$fileData = base64_encode(file_get_contents($tmpPath));
$dataUrl  = 'data:' . $mimeType . ';base64,' . $fileData;

// Build prompt
if ($type === 'purchase') {
    $prompt = <<<PROMPT
Extract data from this purchase invoice image. Output ONLY a raw JSON object — no markdown, no code fences, no explanation.

Use exactly this structure:
{"vendor_name":"...","supplier_invoice_no":"...","invoice_date":"YYYY-MM-DD","items":[{"product_name":"...","quantity":0,"purchase_price":0.00,"mrp":0.00,"gst_percent":0,"batch_no":""}]}

Rules:
- purchase_price = price per unit EXCLUDING GST
- mrp = Maximum Retail Price printed on packaging (null if not shown)
- gst_percent = combined GST rate (CGST% + SGST% if shown separately, e.g. 9+9=18)
- batch_no = batch/lot number if visible, else ""
- invoice_date = YYYY-MM-DD format, null if not found
- Only include actual product line items — skip subtotals, tax rows, and header rows
- If a field is missing use null for strings/numbers, "" for batch_no
- Output raw JSON only, nothing else
PROMPT;
} else {
    $prompt = <<<PROMPT
Extract data from this sales invoice image. Output ONLY a raw JSON object — no markdown, no code fences, no explanation.

Use exactly this structure:
{"client_name":"...","invoice_no":"...","invoice_date":"YYYY-MM-DD","items":[{"product_name":"...","quantity":0,"sell_price":0.00,"gst_percent":0}]}

Rules:
- sell_price = price per unit INCLUDING GST
- gst_percent = combined GST rate (CGST% + SGST% if shown separately, e.g. 9+9=18)
- invoice_date = YYYY-MM-DD format, null if not found
- Only include actual product line items — skip subtotals, tax rows, and header rows
- If a field is missing use null
- Output raw JSON only, nothing else
PROMPT;
}

$requestBody = json_encode([
    'model'      => 'meta-llama/llama-4-scout-17b-16e-instruct',
    'max_tokens' => 4096,
    'messages'   => [[
        'role'    => 'user',
        'content' => [
            ['type' => 'image_url', 'image_url' => ['url' => $dataUrl]],
            ['type' => 'text',      'text'      => $prompt],
        ],
    ]],
]);

$ch = curl_init('https://api.groq.com/openai/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $requestBody,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if (!$response) {
    echo json_encode(['error' => 'Failed to connect to Groq API. Check your internet connection.']);
    exit;
}

$apiResponse = json_decode($response, true);

if ($httpCode !== 200) {
    $msg = $apiResponse['error']['message'] ?? 'API error';
    echo json_encode(['error' => 'API error: ' . $msg]);
    exit;
}

$text = trim($apiResponse['choices'][0]['message']['content'] ?? '');

// Strip markdown code fences if present
$text = preg_replace('/^```(?:json)?\s*/i', '', $text);
$text = preg_replace('/\s*```$/', '', $text);
$text = trim($text);

$extracted = json_decode($text, true);
if (!$extracted) {
    echo json_encode(['error' => 'Could not parse extracted data. Try a clearer image.', 'raw' => $text]);
    exit;
}

echo json_encode(['success' => true, 'data' => $extracted]);
