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

$code = trim((string)($_POST['code'] ?? ''));
$fn   = trim((string)($_POST['fn'] ?? 'case_count'));

if ($code === '') {
  http_response_code(400);
  exit('Missing code');
}

$allowed = ['case_count','bin_select','palletize'];
if (!in_array($fn, $allowed, true)) $fn = 'case_count';

$tbl = null;
$q = $mysqli->query("SHOW TABLES LIKE 'barcode_readings'");
if ($q && $q->num_rows > 0) $tbl = 'barcode_readings';
$q = $mysqli->query("SHOW TABLES LIKE 'barcode_scans'");
if (!$tbl && $q && $q->num_rows > 0) $tbl = 'barcode_scans';

if (!$tbl) {
  http_response_code(500);
  exit('No scan table found');
}

if ($tbl === 'barcode_readings') {
  $stmt = $mysqli->prepare("INSERT INTO barcode_readings (code, source_code, read_time) VALUES (?, 'MANUAL', NOW())");
  $stmt->bind_param('s', $code);
} else {
  $stmt = $mysqli->prepare("INSERT IGNORE INTO barcode_scans (code, source, scan_function, scanned_at) VALUES (?, 'manual', ?, NOW())");
  $stmt->bind_param('ss', $code, $fn);
}
$stmt->execute();
$stmt->close();

echo "OK";
