<?php
require_once __DIR__ . '/../config/user_functions.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/users_local.php';
require_once __DIR__ . '/../config/db_remote.php';

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

if (function_exists('user_has_permission') && !user_has_permission('reports')) {
    http_response_code(403);
    echo json_encode(['status'=>'forbidden']);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['status'=>'bad_request']);
    exit;
}

$code = trim((string)($data['code'] ?? ''));
$source = (string)($data['source'] ?? '');
$scan_function = (string)($data['scan_function'] ?? 'case_count');
$reader_code = $data['reader_code'] ?? null;

if ($code === '' || strlen($code) > 255) {
    http_response_code(422);
    echo json_encode(['status'=>'invalid_code']);
    exit;
}
if (!in_array($source, ['keyence','symcode','manual'], true)) {
    http_response_code(422);
    echo json_encode(['status'=>'invalid_source']);
    exit;
}
if (!in_array($scan_function, ['case_count','dump_bins','palletize','unknown'], true)) {
    $scan_function = 'case_count';
}
if ($reader_code !== null) {
    $reader_code = trim((string)$reader_code);
    if ($reader_code === '') $reader_code = null;
    if ($reader_code !== null && strlen($reader_code) > 50) $reader_code = substr($reader_code, 0, 50);
}

$stmt = $mysqli->prepare("
    INSERT IGNORE INTO barcode_scans (code, source, scan_function, reader_code)
    VALUES (?, ?, ?, ?)
");
if (!$stmt) {
    http_response_code(500);
    echo json_encode(['status'=>'db_error','error'=>'prepare_failed']);
    exit;
}
$stmt->bind_param("ssss", $code, $source, $scan_function, $reader_code);
$stmt->execute();
$inserted = ($stmt->affected_rows > 0);
$stmt->close();

$row = null;
$stmt2 = $mysqli->prepare("
    SELECT id, code, source, scan_function, reader_code, scanned_at
    FROM barcode_scans
    WHERE code = ?
    LIMIT 1
");
if ($stmt2) {
    $stmt2->bind_param("s", $code);
    $stmt2->execute();
    $res = $stmt2->get_result();
    $row = $res ? $res->fetch_assoc() : null;
    $stmt2->close();
}

function sp_table_has(mysqli $mysqli, string $table): bool {
    $db = $mysqli->query("SELECT DATABASE() AS d");
    $dbn = $db ? ($db->fetch_assoc()['d'] ?? '') : '';
    if ($db) $db->free();
    if ($dbn === '') return false;

    $stmt = $mysqli->prepare("SELECT 1 FROM information_schema.tables WHERE table_schema=? AND table_name=? LIMIT 1");
    if (!$stmt) return false;
    $stmt->bind_param("ss", $dbn, $table);
    $stmt->execute();
    $stmt->store_result();
    $ok = ($stmt->num_rows > 0);
    $stmt->close();
    return $ok;
}

function sp_cols(mysqli $mysqli, string $table): array {
    $cols = [];
    $db = $mysqli->query("SELECT DATABASE() AS d");
    $dbn = $db ? ($db->fetch_assoc()['d'] ?? '') : '';
    if ($db) $db->free();
    if ($dbn === '') return $cols;

    $stmt = $mysqli->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema=? AND table_name=?");
    if (!$stmt) return $cols;
    $stmt->bind_param("ss", $dbn, $table);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($res && ($r = $res->fetch_assoc())) $cols[] = $r['column_name'];
    $stmt->close();
    return $cols;
}

if (sp_table_has($mysqli, 'activity_log')) {
    $cols = sp_cols($mysqli, 'activity_log');
    $detail = json_encode([
        'code' => $code,
        'source' => $source,
        'scan_function' => $scan_function,
        'reader_code' => $reader_code,
        'result' => $inserted ? 'inserted' : 'duplicate',
        'ts' => date('c'),
        'user' => $_SESSION['username'] ?? ($_SESSION['user'] ?? null),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? null,
    ], JSON_UNESCAPED_SLASHES);

    $actionCol = in_array('action', $cols, true) ? 'action' : (in_array('event', $cols, true) ? 'event' : null);
    $detailCol = in_array('details', $cols, true) ? 'details' : (in_array('message', $cols, true) ? 'message' : null);
    $timeCol   = in_array('created_at', $cols, true) ? 'created_at' : (in_array('created_on', $cols, true) ? 'created_on' : null);
    $userCol   = in_array('user_id', $cols, true) ? 'user_id' : (in_array('username', $cols, true) ? 'username' : null);

    $fields = [];
    $place  = [];
    $vals   = [];
    $types  = '';

    if ($actionCol) { $fields[]=$actionCol; $place[]='?'; $vals[]='barcode_scan'; $types.='s'; }
    if ($detailCol) { $fields[]=$detailCol; $place[]='?'; $vals[]=$detail; $types.='s'; }
    if ($timeCol)   { $fields[]=$timeCol;   $place[]='NOW()'; }
    if ($userCol) {
        $fields[]=$userCol; $place[]='?';
        $vals[] = (string)($_SESSION['user_id'] ?? ($_SESSION['username'] ?? 'unknown'));
        $types .= 's';
    }

    if (!empty($fields)) {
        $sql = "INSERT INTO activity_log (" . implode(',', $fields) . ") VALUES (" . implode(',', $place) . ")";
        $stmt3 = $mysqli->prepare($sql);
        if ($stmt3) {
            if (!empty($vals)) {
                $stmt3->bind_param($types, ...$vals);
            }
            $stmt3->execute();
            $stmt3->close();
        }
    }
}

echo json_encode([
    'status' => $inserted ? 'inserted' : 'duplicate',
    'row' => $row,
]);
