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

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

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

if ($code === '') {
    echo json_encode(['ok'=>false,'err'=>'empty']);
    exit;
}

$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);
    echo json_encode(['ok'=>false,'err'=>'no_scan_table']);
    exit;
}

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

echo json_encode(['ok'=>true]);
