<script>
// ---- Configuration ----
var _kitPrefix = "kit-";

var _resetBatchBarcode = "b123";
var _resetOrderBarcode = "o123";

var _msgItemAdded = "Item added.";
var _msgItemBlocked = "Scanned item is not approved.";
var _msgBatchComplete = "Batch Complete! All items packed for this batch.";
var _msgOrderComplete = "Order Complete! All kits packed for this order. Scan a new Kit ID to start another kit.";
var _msgOrderAlreadyComplete = "This kit's order is already complete. Scan a new Kit ID to start another kit.";
var _msgOrderReset = "You can start a new work order now.";
var _msgBatchReset = "You can start a new batch now.";
var _msgBatchResetFail = "There is no batch in progress to reset.";
var _msgWarnBadSession = "There is an issue with this Kit ID's database record.";

var _msgItemQtyComplete = "Required quantity for this item is already completed.";
var _msgItemNotInKit = "Scanned item is not part of this kit.";
var _msgKitNotFound = "Scanned value is not a recognized Kit ID.";
var _msgKitStarted = "Kit started. Scan items to begin packing.";
var _msgNoActiveKit = "Scan a Kit ID barcode to begin.";

var _storageKey = "cov_state";

function crCustomValidate(scan) {
var result = validateForKitting(scan);

// For reset and pure message cases, return plain text
if (result.scanStatus !== "1" || result.rawMessageOnly) {
return JSON.stringify(result);
}

// For successful kit-start / item scans, build a fully-rendered HTML response.
// (The in-app response viewer renders static HTML only — it does not
// execute <script> tags — so all substitution happens here, not client-side.)
var state = getState(scan);
state.message = result.scanResponse;
result.scanResponse = buildDisplayHtml(state);

return JSON.stringify(result);
}

function validateForKitting(scan) {
var state = getState(scan);
var scanValue = scan.scanValue;

// RESET ORDER
if (resetOrder(scan, state)) {
return { scanStatus: "0", scanResponse: _msgOrderReset, rawMessageOnly: true };
}

// RESET BATCH
if (resetBatch(scan, state)) {
return isBatchOngoing(state)
? { scanStatus: "0", scanResponse: _msgBatchReset, rawMessageOnly: true }
: { scanStatus: "0", scanResponse: _msgBatchResetFail, rawMessageOnly: true };
}

// KIT TRIGGER SCAN — a value with the "x-" prefix, e.g. "x-840570303855".
// This is also the database key directly (no parsing needed at scan time).
// The database record's response holds a plain-text description followed by
// the JSON kit record (description comes before the first "{").
// Always starts (or switches to) that kit, abandoning any in-progress kit.
if (isKitTriggerValue(scanValue)) {
var kitRecord = lookupKitRecord(scanValue);

if (kitRecord == null) {
return { scanStatus: "0", scanResponse: _msgKitNotFound, rawMessageOnly: true };
}

var kitUpc = scanValue.substring(_kitPrefix.length);
var session = buildSessionFromKitRecord(kitUpc, kitRecord);

if (!isValidSession(session)) {
return { scanStatus: "0", scanResponse: _msgWarnBadSession, rawMessageOnly: true };
}

var newState = {
totalCnt: 0,
session: session,
batch: {
packed: withValuesAsZero(session.kit),
id: genBatchId()
}
};
newState.batch.qty = getAdjustedBatchQty(newState);

saveState(newState);

return { scanStatus: "1", scanResponse: _msgKitStarted };
}

// ITEM SCAN — requires an active kit
if (!isValidStateObj(state)) {
return { scanStatus: "0", scanResponse: _msgNoActiveKit, rawMessageOnly: true };
}

if (isOrderComplete(state)) {
return { scanStatus: "0", scanResponse: _msgOrderAlreadyComplete, rawMessageOnly: true };
}

var activeSession = state.session;
activeSession.itemDescription = lookupItemDescription(scanValue);

if (activeSession.kit.hasOwnProperty(scanValue)) {
var updated = updateState(state, activeSession, scanValue);

if (updated != null) {
return respondToStateChange(updated);
} else {
return { scanStatus: "0", scanResponse: _msgItemQtyComplete, rawMessageOnly: true };
}
}

return { scanStatus: "0", scanResponse: _msgItemNotInKit, rawMessageOnly: true };
}

// ---- Kit lookup / session construction ----

function isKitTriggerValue(value) {
return typeof value === "string" && value.indexOf(_kitPrefix) === 0;
}

// The database response is plain-text description followed directly by the JSON
// kit record, e.g. "Bracelet Starter Kit {"orderId":"ORD-1006", ...}". Everything
// before the first "{" is the description; everything from the "{" onward is parsed
// as JSON. A record with no description (JSON starting at position 0) is also valid.
function parseKitRecordResponse(responseText) {
var braceIdx = responseText.indexOf("{");
if (braceIdx === -1) return null;

var description = responseText.substring(0, braceIdx).trim();

try {
var record = JSON.parse(responseText.substring(braceIdx));
record.description = description;
return record;
} catch (e) {
return null;
}
}

function lookupKitRecord(kitIdValue) {
try {
var raw = window.CRHOOK.dbSearch(kitIdValue, true, null, false, null, 1);
var lookup = JSON.parse(raw);
if (lookup.length > 0) {
return parseKitRecordResponse(lookup[0].response);
}
} catch (e) {}
return null;
}

function lookupItemDescription(upc) {
try {
var raw = window.CRHOOK.dbSearch(upc, true, null, false, null, 1);
var itemLookup = JSON.parse(raw);
if (itemLookup.length > 0) {
return itemLookup[0].response;
}
} catch (e) {}
return "";
}

function buildSessionFromKitRecord(kitIdValue, kitRecord) {
var session = {
orderId: (kitRecord.orderId || "").toString().trim(),
kitId: kitIdValue,
totalQty: parseInt(kitRecord.totalQty),
batchQty: parseInt(kitRecord.batchQty),
kit: kitRecord.kit || {},
kitDescription: kitRecord.description || "",
itemDescriptions: {}
};

for (var upc in session.kit) {
if (!session.kit.hasOwnProperty(upc)) continue;
session.itemDescriptions[upc] = lookupItemDescription(upc);
}

return session;
}

function isValidSession(session) {
try {
return (
session.orderId.length > 0 &&
session.totalQty > 0 &&
session.batchQty > 0 &&
sumValues(session.kit) > 0
);
} catch (e) {
return false;
}
}

// ---- Item counting / state transitions ----

function updateState(state, session, scanValue) {
if (isBatchComplete(state)) {
state.batch.id = genBatchId();
state.batch.packed = withValuesAsZero(session.kit);
}

state.session = session;
state.batch.qty = getAdjustedBatchQty(state);

var requiredQty = state.batch.qty * session.kit[scanValue];

if (state.batch.packed[scanValue] < requiredQty) {
state.batch.packed[scanValue] += 1;

if (isBatchComplete(state))
state.totalCnt += state.batch.qty;

return state;
}

return null;
}

function respondToStateChange(state) {
var msg = _msgItemAdded;

if (isOrderComplete(state)) {
state.__ORDER_COMPLETED__ = state.session.orderId;
msg = _msgOrderComplete;
}

if (isBatchComplete(state)) {
state.__BATCH_COMPLETED__ = state.batch.id;
msg = _msgBatchComplete;
}

saveState(state);

return { scanStatus: "1", scanResponse: msg };
}

// ---- State persistence (on-device) ----

function getState(scan) {
return JSON.parse(window.CRHOOK.getString(_storageKey, "{}"));
}

function isValidStateObj(state) {
return (
state.hasOwnProperty("totalCnt") &&
state.hasOwnProperty("session") &&
state.session.hasOwnProperty("kit")
);
}

function isOrderComplete(state) {
return isValidStateObj(state) && state.totalCnt == state.session.totalQty;
}

function resetOrder(scan, state) {
if (scan.scanValue == _resetOrderBarcode) {
saveState({});
return true;
}
return false;
}

function isBatchOngoing(state) {
var counts = getItemCounts(state);
return counts.kitItemCnt > 0 && counts.batchItemCnt < counts.batchItemQty;
}

function isBatchComplete(state) {
var counts = getItemCounts(state);
return counts.batchItemCnt == counts.batchItemQty;
}

function resetBatch(scan, state) {
if (scan.scanValue == _resetBatchBarcode) {
if (isBatchOngoing(state)) {
state.batch.id = genBatchId();
state.batch.qty = getAdjustedBatchQty(state);
state.batch.packed = withValuesAsZero(state.session.kit);
saveState(state);
}
return true;
}
return false;
}

function getItemCounts(state) {
var counts = {
kitItemCnt: 0,
batchItemQty: -1,
batchItemCnt: 0
};

if (isValidStateObj(state)) {
counts.kitItemCnt = sumValues(state.session.kit);
counts.batchItemQty = counts.kitItemCnt * state.batch.qty;
counts.batchItemCnt = sumValues(state.batch.packed);
}

return counts;
}

function getAdjustedBatchQty(state) {
var remaining = state.session.totalQty - state.totalCnt;
return remaining < state.session.batchQty
? remaining
: state.session.batchQty;
}

function sumValues(obj) {
var sum = 0;
for (var k in obj)
if (obj.hasOwnProperty(k))
sum += parseFloat(obj[k]);
return sum;
}

function withValuesAsZero(obj) {
var out = {};
for (var k in obj)
if (obj.hasOwnProperty(k))
out[k] = 0;
return out;
}

function saveState(state) {
window.CRHOOK.putString(_storageKey, JSON.stringify(state));
}

function genBatchId() {
return "BID" + Date.now();
}

// ---- HTML rendering (runs inside the COV script, not the response viewer) ----

function escapeHtml(str) {
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}

function buildDisplayHtml(state) {
var session = state.session;
var batch = state.batch;
var counts = getItemCounts(state);

var itemsHtml = "";
for (var upc in batch.packed) {
if (!batch.packed.hasOwnProperty(upc)) continue;

var required = session.kit[upc] * batch.qty;
var packed = batch.packed[upc];
var desc = (session.itemDescriptions && session.itemDescriptions[upc]) || "";
var statusColor =
packed >= required ? "#008000" :
packed > 0 ? "#CC8800" :
"#CC0000";

itemsHtml +=
'<div style="padding:10px 0;border-bottom:1px solid #ddd;">' +
'<span style="color:' + statusColor + ';font-weight:bold;">' +
escapeHtml(upc) + ' (' + packed + ' of ' + required + ')' +
'</span>' +
'<div style="color:#004CFF;font-weight:bold;font-size:16px;margin-top:4px;">' +
escapeHtml(desc) +
'</div>' +
'</div>';
}

return (
'<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>' +
'<body style="font-family:sans-serif;">' +
'<div style="border:2px solid black;padding:10px 15px;border-radius:15px;margin-bottom:15px;">' +
'<div style="font-size:18px;font-weight:bold;margin-bottom:8px;">' +
escapeHtml(state.message) +
'</div>' +
(session.itemDescription
? '<div style="color:#000000;font-weight:bold;margin-bottom:8px;">' +
escapeHtml(session.itemDescription) +
'</div>'
: '') +
'<div>Order: ' + escapeHtml(session.orderId) +
' &nbsp;|&nbsp; Kit: ' + escapeHtml(session.kitId) + '</div>' +
(session.kitDescription
? '<div style="color:#555555;font-style:italic;margin-bottom:4px;">' +
escapeHtml(session.kitDescription) +
'</div>'
: '') +
'<div>Kits Completed: ' + state.totalCnt + ' of ' + session.totalQty + '</div>' +
'<div>Batch: ' + escapeHtml(batch.id) + ' (size ' + batch.qty + ')</div>' +
'<div>Batch Items Packed: ' + counts.batchItemCnt + ' of ' + counts.batchItemQty + '</div>' +
'</div>' +
itemsHtml +
'</body></html>'
);
}
</script>
