<?php
// includes/master/asset_nfc_functions.php

if (file_exists('../../../' . ($_REQUEST['tenant'] ?? '') . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

header('Content-Type: text/plain; charset=utf-8');

if (!isset($_REQUEST['FUNCTION'])) {
    echo 'No FUNCTION specified';
    exit;
}

$fn = $_REQUEST['FUNCTION'];

if (!isset($con) || !($con instanceof mysqli)) {
    echo 'Database connection not available';
    exit;
}

switch ($fn) {
    case 'set_nfc': {
        $itemnumber   = (int)($_POST['itemnumber'] ?? 0);
        $clientnumber = (int)($_POST['clientnumber'] ?? 0); // for future checks if needed
        $locnumber    = (int)($_POST['locnumber'] ?? 0);    // for future checks if needed
        $tag          = trim($_POST['tag'] ?? '');

        if ($itemnumber <= 0 || $tag === '') {
            echo 'Invalid parameters';
            exit;
        }

        $stmt = $con->prepare("UPDATE `itemdetails` SET `nfc` = ? WHERE `itemnumber` = ? LIMIT 1");
        if (!$stmt) {
            echo 'DB error (prepare)';
            exit;
        }

        $stmt->bind_param('si', $tag, $itemnumber);
        if ($stmt->execute()) {
            echo 'success';
        } else {
            echo 'DB error (execute)';
        }
        $stmt->close();
        break;
    }

    case 'clear_nfc': {
        $itemnumber = (int)($_POST['itemnumber'] ?? 0);

        if ($itemnumber <= 0) {
            echo 'Invalid parameters';
            exit;
        }

        $empty = '';
        $stmt = $con->prepare("UPDATE `itemdetails` SET `nfc` = ? WHERE `itemnumber` = ? LIMIT 1");
        if (!$stmt) {
            echo 'DB error (prepare)';
            exit;
        }

        $stmt->bind_param('si', $empty, $itemnumber);
        if ($stmt->execute()) {
            echo 'success';
        } else {
            echo 'DB error (execute)';
        }
        $stmt->close();
        break;
    }

    default:
        echo 'Unknown FUNCTION';
        break;
}
