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

function assetNotesFail(string $message, int $statusCode = 400): void
{
    http_response_code($statusCode);
    echo $message;
    exit;
}

if (!isset($GLOBALS['con'])) {
    assetNotesFail('Database connection unavailable.', 500);
}

$type = (string)($_REQUEST['type'] ?? '');
$notes = (string)($_REQUEST['notes'] ?? '');

if ($type === 'itemdetails') {
    $item = (int)($_REQUEST['item'] ?? 0);
    if ($item < 1) {
        assetNotesFail('Missing item number.');
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `itemnotes`=? WHERE `itemnumber`=?");
    if (!$stmt) {
        assetNotesFail(mysqli_error($GLOBALS['con']), 500);
    }

    $stmt->bind_param('si', $notes, $item);
    if (!$stmt->execute()) {
        $error = $stmt->error ?: 'Unable to update item notes.';
        $stmt->close();
        assetNotesFail($error, 500);
    }
    $stmt->close();
    echo 'success ' . $item;
    exit;
}

if ($type === 'locations') {
    $location = (int)($_REQUEST['location'] ?? 0);
    if ($location < 1) {
        assetNotesFail('Missing location number.');
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `locations` SET `locnotes`=? WHERE `locnumber`=?");
    if (!$stmt) {
        assetNotesFail(mysqli_error($GLOBALS['con']), 500);
    }

    $stmt->bind_param('si', $notes, $location);
    if (!$stmt->execute()) {
        $error = $stmt->error ?: 'Unable to update location notes.';
        $stmt->close();
        assetNotesFail($error, 500);
    }
    $stmt->close();
    echo 'success ' . $location;
    exit;
}

assetNotesFail('Unknown notes type.');
