<?php
/**
 * GET /api/products/barcode_lookup.php?barcode=XXXXXXXXXXXXX
 *
 * Two lookup sources, checked in order:
 *   1. Ragreen's own catalog - if ANY seller has ever listed this exact
 *      barcode before (regardless of who, or whether that listing is still
 *      active), reuse its name/category/description. This matters a lot
 *      for regional/local products that Open Food Facts has never heard
 *      of - once one seller types it in manually, every future scan of
 *      the same barcode benefits, building up real product data over time
 *      instead of hitting "no match" forever for the same item.
 *   2. Open Food Facts (free, external, crowd-sourced) - used only if
 *      nothing in our own catalog matches yet.
 *
 * If neither has it, the front-end falls back to manual entry - expected,
 * not an error, especially for regional goods.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

require_login();

$barcode = trim($_GET['barcode'] ?? '');
if ($barcode === '' || !preg_match('/^[0-9]{6,14}$/', $barcode)) {
    send_error('Please provide a valid barcode (6-14 digits).', 422);
}

$pdo = Database::connect();

// --- 1. Check our own catalog first ---
$stmt = $pdo->prepare(
    'SELECT name, category_id, description FROM products WHERE barcode = ? ORDER BY created_at DESC LIMIT 1'
);
$stmt->execute([$barcode]);
$existing = $stmt->fetch();

if ($existing) {
    send_json(true, 'Found in your Ragreen catalog.', [
        'found'   => true,
        'source'  => 'ragreen',
        'barcode' => $barcode,
        'product' => [
            'name'        => $existing['name'],
            'category_id' => $existing['category_id'] ? (int) $existing['category_id'] : null,
            'description' => $existing['description'],
        ],
    ]);
}

// --- 2. Fall back to Open Food Facts ---
if (!function_exists('curl_init')) {
    // Defensive: some hosts don't have the curl extension enabled. Rather
    // than a fatal error, degrade to "not found" so manual entry still works.
    send_json(true, 'No match found - please complete the details manually.', [
        'found' => false,
        'barcode' => $barcode,
    ]);
}

$url = 'https://world.openfoodfacts.org/api/v2/product/' . urlencode($barcode) . '.json';

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 6,
    CURLOPT_HTTPHEADER     => ['User-Agent: Ragreen-MVP/1.0 (contact: raghadibrahim16@gmail.com)'],
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false) {
    // Network/timeout issue reaching Open Food Facts - not the user's fault.
    send_json(true, 'Lookup service unavailable, please enter details manually.', [
        'found' => false,
        'barcode' => $barcode,
    ]);
}

$data = json_decode($response, true);

if ($httpCode !== 200 || !isset($data['status']) || (int) $data['status'] !== 1) {
    send_json(true, 'No match found - please complete the details manually.', [
        'found' => false,
        'barcode' => $barcode,
    ]);
}

$product = $data['product'] ?? [];

send_json(true, 'Product found.', [
    'found'   => true,
    'source'  => 'openfoodfacts',
    'barcode' => $barcode,
    'product' => [
        'name'        => $product['product_name'] ?? '',
        'category'    => $product['categories'] ?? '',
        'image_url'   => $product['image_front_url'] ?? ($product['image_url'] ?? ''),
        'quantity'    => $product['quantity'] ?? '', // e.g. "500g" - informational only
        'brand'       => $product['brands'] ?? '',
    ],
]);
