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

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_plant` WHERE `id`='".$_REQUEST['id']."'")or die(mysqli_error($GLOBALS['con']));
$stmt->execute();$rslt=$stmt->get_result();
$d=mysqli_fetch_array($rslt);

?>
<form id="newForm">
    <div class="row">
        <div class="col-12 col-md-6 mb-2">
            <span>Code</span>
            <input type="text" class="form-control form-control-sm" aria-label="code" id="newcode" name="code" value="" />
        </div>
        <div class="col-12 col-md-6 mb-2">
            <span>Description</span>
            <input type="text" class="form-control form-control-sm" aria-label="formtype" id="newdesc" name="desc" value="" />
        </div>
        <div class="col-12 col-md-6 mb-2">
            <span>Frequency</span>
            <input type="text" class="form-control form-control-sm" aria-label="frequency" id="newfreq" name="freq" value="" />
        </div>
        <div class="col-12 col-md-6 mb-2">
            <span>Size</span>
            <input type="text" class="form-control form-control-sm" aria-label="size" name="size" value="" />
        </div>
        <div class="col-12 col-md-6 mb-2">
            <span>IU</span>
            <input type="text" class="form-control form-control-sm" aria-label="units" name="units" value="" />
        </div>
        <input type="hidden" name="mode" value="plant">
        <input type="hidden" name="tenant" value="<?= $systemUser ?>">
        <input type="hidden" name="tenant" value="<?=TENANT_URL?>">
        <input type="hidden" name="FCN" value="save">
    </div>
</form>
<script>
(() => {

    window.updateEntryPlant = (event) => {
        const dest = '<p>Sure you wish to save this entry?</p>';
        loadModalContent(dest, "confirmBox", "modal-md", 1060, "true", "Update Entry", "cancelConfirm", 'saveItem');

    };

    window.saveItem = async function(event) {

        const newCode = document.getElementById('newcode').value;
        const newDesc = document.getElementById('newdesc').value;
        const newFreq = document.getElementById('newfreq').value;

        if (!newCode || !newDesc || !newFreq) {
            showResponse('warning', 'You must have a valid CODE, DESCRIPTION and FREQUENCY to save a new code');
            killModal('confirmBox')
            return;
        }

        try {
            const formData = new FormData(document.getElementById('newForm'));
            const ajaxResponse = await fetch(`${ROOT_URL}/includes/jump/jump_functions.php`, {
                method: 'POST',
                body: formData
            });

            const result = await ajaxResponse.text();

            if (result.trim() === 's') {
                const postResponse = await fetch(`${ROOT_URL}/includes/jump/jump_new_functions.php`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: new URLSearchParams({
                        FCN: 'genNewLists',
                        tenant: TENANT_URL
                    })
                });

                const ret = await postResponse.text();

                showResponse('success', 'Your code has been saved successfully');
                killModal('confirmBox')

                const myObject = ret.trim().split('[SPLIT]');
                document.getElementById('code').innerHTML = myObject[0];
                document.getElementById('desc').innerHTML = myObject[1];

                // Destroy previous MDB instances if they exist:
                const codeEl = document.getElementById('code');
                const descEl = document.getElementById('desc');
                const codeOldInstance = mdb.Select.getInstance(codeEl);
                if (codeOldInstance) codeOldInstance.dispose();
                const descOldInstance = mdb.Select.getInstance(descEl);
                if (descOldInstance) descOldInstance.dispose();

                // Re-initialize
                const codeInstance = new mdb.Select(codeEl);
                const descInstance = new mdb.Select(descEl);

                // Select the new options
                codeInstance.setValue([newCode]);
                descInstance.setValue([newDesc]);
                killModal('codeBox')
            } else {
                showResponse('danger', 'The code is already in the system');
            }
        } catch (error) {
            console.error('AJAX Error:', error);
            showResponse('danger', 'An error occurred while saving.');
        }
    };


})();
</script>