<?php
if ($_REQUEST['dataLoad'] != "") {
    $d[2] = $_REQUEST['dataLoad'];
    $_REQUEST['itemnumber'] = $_REQUEST['dataLoad'];
    if (file_exists('../../..' . $_REQUEST['tenant'] . '/config.php')) {
        require_once('../../..' . $_REQUEST['tenant'] . '/config.php');
    }
    if (file_exists('/config.php')) {
        require_once('/config.php');
    }
    require('../../includes/master/form_functions.php');
    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `itemdetails` WHERE `itemnumber`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('i', $_REQUEST['itemnumber']);
    $stmt->execute();
    $rc = $stmt->get_result();
    $stmt->close();
    $cd = mysqli_fetch_array($rc);
}
?>
<div class="row">
    <div class="col-12 mb-3"> <a id="editBtn" href="javascript:void(0)" class="btn btn-info btn-sm float-end"><i
                class="fad fa-pencil fa-sm text-light"></i> Edit Details</a></div>
</div>
<div class="row mb-2">
    <div class="bg-white rounded">
        <table class="table table-sm table-striped">
            <tr>
                <th><strong>Description</strong></th>
                <td><?= $cd['desc'] ?></td>
                <th><strong>Date of Manufacture</th>
                <td><?php if ($cd['dateofmanf'] == "" || $cd['dateofmanf'] == "Not Marked") {
                        echo "Not Known";
                    } else {
                        echo $cd['dateofmanf'];
                    } ?></td>
            </tr>
            <tr>
                <th><strong>Plant Number</strong></th>
                <td><?= $cd['plantnumber'] ?></td>
                <th><strong>Model</th>
                <td><?= $cd['model'] ?></td>
            </tr>
            <tr>
                <th><strong>Serial</strong></th>
                <td><?= $cd['serialnumber'] ?></td>
                <th><strong>Location</th>
                <td><?= getItemLocation($cd['itemnumber'], "name") ?></td>
            </tr>
            <tr>
                <th><strong>Manufacturer</strong></th>
                <td><?= $cd['manf'] ?></td>
                <th><strong>Location on Site</strong></th>
                <td><?= $cd['subloc'] ?></td>
            </tr>
            <tr>
                <th><strong>SWL</strong></th>
                <td><?= $cd['swl'] ?></td>
                <th></th>
                <td></td>
            </tr>
        </table>
    </div>
</div>
<div class="row mb-2 mt-2">
    <div class="text-center">
        <h6>Item located at <strong><?= getItemLocation($cd['itemnumber'], 'itemDetail') ?><?php if ($cd['subloc'] != "") { ?>
                <br>Sublocation:
                <?= $cd['subloc'];
                                                                                        } ?>
            </strong><br>
            <?php if (getItemInsp($cd['itemnumber'], 'name') == "0") { ?>
            <span class="text-danger">No inspection stored for this asset and report type</span>
            <?php } else { ?>
            Last inspected by <strong><?= getItemInsp($cd['itemnumber'], 'name') ?>
                <?php } ?>
            </strong>
        </h6>
    </div>
</div>
<script>
document.getElementById('editBtn').addEventListener('click', function() {
    // Get the target element
    const targetElement = document.getElementById('D<?= $d[2] ?>');

    // Define the URL to fetch the content from
    const url = ROOT_URL + '/forms/elements/form_details_edit.php?itemnumber=<?= $d[2] ?>&tenant=' + TENANT_URL;

    // Use fetch API to get the content
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.text();
        })
        .then(html => {
            // Set the inner HTML of the target element
            targetElement.innerHTML = html;

            // Initialize the form behavior after content is loaded
            initializeFormBehavior(targetElement);
        })
        .catch(error => {
            console.error('There has been a problem with your fetch operation:', error);
        });
});

function initializeFormBehavior(formContainer) {
    const form = formContainer.querySelector('#itemEditForm');

    // Attach event listener for form submission
    form.addEventListener('submit', function(event) {
        event.preventDefault(); // Prevent the default form submission

        const formData = new FormData(form); // Serialize form data
        const url = `${ROOT_URL}/includes/master/form_functions.php`; // Correct path without leading `../../`

        fetch(url, {
                method: 'POST',
                body: formData,
            })
            .then(response => response.text())
            .then(result => {
                if (result.trim() === "success") {
                    showResponse('success', 'Your changes have been saved successfully');
                    loadFormDetails('<?= $d[2] ?>'); // Reload form details after successful save
                } else {
                    showResponse('danger', 'Your changes have not been saved successfully ' + result);
                }
            })
            .catch(error => console.error('Error:', error));
    });

    // Function to reload form details
    function loadFormDetails(itemNumber) {

        const url = `${ROOT_URL}/forms/elements/form_details.php?dataLoad=${itemNumber}&tenant=${TENANT_URL}`;
        fetch(url)
            .then(response => response.text())
            .then(html => {
                formContainer.innerHTML = html; // Update the form container with new content
            })
            .catch(error => console.error('Error loading form details:', error));
    }

    // Function to cancel edit and reload form details
    window.cancelEdit = function() {
        loadFormDetails('<?= $d[2] ?>');
    };
}
</script>