<?php
// /smproduce/api/scan.php
// Inserts a barcode scan.
// Compatibility: supports both legacy `barcode_scans` and newer `barcode_readings`.

require_once __DIR__ . '/../config/db_remote.php';

header('Content-Type: application/json; charset=utf-8');

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'DB not available']);
    exit;
}

$code   = trim((string)($_POST['code'] ?? ''));
$source = trim((string)($_POST['source_code'] ?? ($_POST['source'] ?? '')));
$scanFn = trim((string)($_POST['scan_function'] ?? ($_POST['function'] ?? '')));

if ($code === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Empty code']);
    exit;
}

if ($source === '') $source = 'MANUAL';

// Determine which table is available.
$tbl = null;
$check = $mysqli->query("SHOW TABLES LIKE 'barcode_readings'");
if ($check && $check->num_rows > 0) {
    $tbl = 'barcode_readings';
}
$check = $mysqli->query("SHOW TABLES LIKE 'barcode_scans'");
if (!$tbl && $check && $check->num_rows > 0) {
    $tbl = 'barcode_scans';
}

if (!$tbl) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'No scan table found (barcode_readings/barcode_scans)']);
    exit;
}

// Insert (server-side timestamp)
if ($tbl === 'barcode_readings') {
    $stmt = $mysqli->prepare("INSERT INTO barcode_readings (code, source_code, read_time) VALUES (?, ?, NOW())");
} else {
    // legacy: duplicates should be ignored
    $stmt = $mysqli->prepare("INSERT IGNORE INTO barcode_scans (code, source, scan_function, scanned_at) VALUES (?, ?, ?, NOW())");
}
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Prepare failed']);
    exit;
}

if ($tbl === 'barcode_readings') {
    $stmt->bind_param('ss', $code, $source);
} else {
    if ($scanFn === '') $scanFn = 'case_count';
    $stmt->bind_param('sss', $code, $source, $scanFn);
}
$ok = $stmt->execute();
$stmt->close();

echo json_encode(['ok' => (bool)$ok, 'table' => $tbl]);
