<?php  
$data = urldecode($_REQUEST['data']);
$d = explode("|", $data);
$nb = getPssrEno($d[2]);
if ($_REQUEST['forwarder'] == "standalone") {
    $d[0] = $_REQUEST['clientnumber'];
    $d[4] = $_REQUEST['clientname'];
    $d[2] = $_REQUEST['asset'];
    $d[3] = $_REQUEST['assetName'];
    $cd['locnumber'] = $_REQUEST['site'];
    $cd['statuslive'] = "1";
} else {
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $d[2]);
$stmt->execute();
$recall = $stmt->get_result();
$stmt->close();
$cd = mysqli_fetch_array($recall);
if (!function_exists('enrep_itemdetails_pressure_from_record')) {
    require_once __DIR__ . '/../../functions/itemdetails_json.php';
}
if (is_array($cd)) {
    $cd = array_replace($cd, enrep_itemdetails_pressure_from_record($cd), enrep_itemdetails_lev_from_record($cd));
}

if (isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
    $assetPrefs = is_array($GLOBALS['assetPrefs'] ?? null) ? $GLOBALS['assetPrefs'] : [];
    $stmt = $GLOBALS['con']->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
    if ($stmt) {
        $stmt->execute();
        $stmt->bind_result($prefsJson);
        if ($stmt->fetch() && trim((string)$prefsJson) !== '') {
            $decodedPrefs = json_decode((string)$prefsJson, true);
            if (is_array($decodedPrefs)) {
                if (isset($decodedPrefs['model']) && !isset($decodedPrefs['make_model'])) {
                    $decodedPrefs['make_model'] = $decodedPrefs['model'];
                }
                foreach ($decodedPrefs as $prefKey => $prefValue) {
                    if (is_array($prefValue)) {
                        $assetPrefs[(string)$prefKey] = array_merge($assetPrefs[(string)$prefKey] ?? [], $prefValue);
                    }
                }
                $GLOBALS['assetPrefs'] = $assetPrefs;
            }
        }
        $stmt->close();
    }
}

$assetConditionColumnExists = false;
if (isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
    $stmt = $GLOBALS['con']->prepare("SHOW COLUMNS FROM `itemdetails` LIKE 'condition'");
    if ($stmt) {
        $stmt->execute();
        $assetConditionColumnExists = $stmt->get_result()->num_rows > 0;
        $stmt->close();
    }
}

if (!function_exists('asset_label')) {
    function asset_label(string $key, string $fallback): string
    {
        static $assetLabels = null;

        if ($assetLabels === null) {
            $assetLabels = [];
            if (isset($GLOBALS['con']) && $GLOBALS['con'] instanceof mysqli) {
                $stmt = $GLOBALS['con']->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
                if ($stmt) {
                    $stmt->execute();
                    $stmt->bind_result($prefsJson);
                    if ($stmt->fetch() && trim((string)$prefsJson) !== '') {
                        $decoded = json_decode((string)$prefsJson, true);
                        if (is_array($decoded)) {
                            foreach ($decoded as $prefKey => $prefValue) {
                                if (is_array($prefValue) && isset($prefValue['label'])) {
                                    $label = trim((string)$prefValue['label']);
                                    if ($label !== '') {
                                        $assetLabels[(string)$prefKey] = $label;
                                    }
                                }
                            }
                        }
                    }
                    $stmt->close();
                }
            }
        }

        return $assetLabels[$key] ?? $fallback;
    }
}
?>

<h2><span class="badge badge-info"><?= getItemName($d[2]) ?>:</span><span
        class="badge badge-dark ms-n1"><?= $cd['serialnumber'] ?></span></h2>
<form id="assetForm" class="form-horizontal">
    <fieldset>
        <div class="row">
            <?php require_once(ROOT_URL . '/forms/elements/personnel.frm'); ?>
            <?php require_once(ROOT_URL . '/forms/elements/asset_controls.frm'); ?>
            <?php require_once(ROOT_URL . '/forms/elements/asset_details.frm'); ?>
            <input type="hidden" name="clientnumber" id="clientnumber" value="<?= $d[0] ?>" />
            <input type="hidden" name="itemnumber" id="itemnumber" value="<?= $cd['itemnumber'] ?>" />
            <input type="hidden" name="FUNCTION" id="FUNCTION" value="update" />
            <input type="hidden" name="tenant" id="tenant" value="<?= TENANT_URL ?>" />
            <div class="col-md-12 text-center"><input id="btn-update" type="submit" style="display:none" /></div>
        </div>
    </fieldset>

</form>
<div class="row">
    <?php require_once(ROOT_URL . '/forms/elements/asset_image.frm'); ?>
    <?php require_once(ROOT_URL . '/includes/asset/asset_resources.php'); ?>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('assetForm').addEventListener('submit', function(event) {

            event.preventDefault();
            const actionButton = document.getElementById("actionButton");
            actionButton.disabled = true;

            const locNumber = document.getElementById('locnumber').value;
            if (locNumber === "") {
                showResponse('warning', 'Please specify a site before proceeding.');
                actionButton.disabled = false;
            } else {
                fetch(ROOT_URL + '/includes/asset/asset_functions.php', {
                        method: 'POST',
                        body: new FormData(document.getElementById('assetForm'))
                    })
                    .then(response => response.text())
                    .then(result => {

                        showResponse('success', 'Your changes have been saved successfully');
                        //debug(result);
                        window.location.href = '<?= $_SESSION['returnLanding'] ?>'
                    });
            }
        });




        const navBox = document.getElementById('navBox');
        const breadcrumbHTML = `
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&view=list">Client List</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $d[0] ?>&view=edit"><?= getClientName($d[0]) ?></a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>
    <li class="breadcrumb-item"><a href="index.php?t=includes/master&p=client.php&clientnumber=<?= $d[0] ?>&view=asset">Schedule</a><i class="fad fa-angle-double-right mx-2 mt-1"" aria-hidden="true"></i></li>
    <li class="breadcrumb-item active">Edit Asset - <?= getItemName($d[2]) ?></li>
  `;

        navBox.innerHTML = breadcrumbHTML;

        const footerControls = document.getElementById('footerControls');
        const buttonHTML =
            `<button id="actionButton" class="btn btn-secondary" onclick="triggerAction('btn-update')">UPDATE</button>`;

        footerControls.innerHTML = buttonHTML;
    });
</script>
