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

$d=explode("|",$_REQUEST['data']);

switch($_REQUEST['mode']){
default:break;
case "mass";
$items=explode(",",$_REQUEST['items']);
$iCount=count($items);
?>
<div class="col-12 alert warning-color-dark text-light text-center p-0">This will replace the items code and and associated inspection period</div>
<p class="lead">You have chosen to change the code of the following <b><?= $iCount?></b> items</p>
<div class="row" style="max-height:200px; overflow:auto">
    <?php 
    foreach($items as $item){
    $item=str_replace("C","",$item);
    ?>
    <div class="col-md-4">
        <div class="card me-2 mb-2 p-2"><?= $item?> - <?= getItemDetails($item,'name')?></div>
    </div>

    <?php }?>
    <input id="itemList" type="hidden" value="<?= $_REQUEST['items']?>">
</div>
<div class="row p-3 mb-5">

    <div class="col-12 mt-3 mb-4">
        <div class="form-group row">
            <div class="col-md-2"><label class="control-label" for="code">Change code to:</label></div>
            <div class="col-md-9" data-mdb-select-init>
                <?php $stmt = $GLOBALS['con']->prepare("SELECT * FROM `dd_plant` ORDER BY `code` ASC")or die(mysqli_error($GLOBALS['con']));
            $stmt->execute();$cc=$stmt->get_result();$stmt->close();?>
                <select class="form-control form-control-sm" id="code" name="code">
                    <?php while($pd=mysqli_fetch_array($cc)){?>

                    <option value="<?= $pd['code']?>|<?= $pd['description']?>" title="<?= $pd['code']?>">| <?= $pd['code']?> | <?= $pd['description']?>&nbsp;&nbsp;&nbsp;&nbsp;(<?= $pd['frequency']?> months)</option>
                    <?php }?>
                </select>
            </div>
        </div>
    </div>
</div>

<script>
var codeSelect = new mdb.Select(document.getElementById('code'), {
    filter: true,
    container: "#popupBox"
});
var codeSelected = document.getElementById('code')
codeSelected.addEventListener('valueChanged.mdb.select', (e) => {
    changeCode()
})
</script>
<?php break;


case "massConfirm":?>
<?= $_REQUEST['data'];?>
<div class="row">
    <div class="col-12 text-center">
        <h1>Confirm changing Assets to<br></h1>
        <h1 class="badge badge-pill badge-primary"><span class="lead"><?= $_REQUEST['dest']?></span></h1>
    </div>
    <input id="itemList" type="hidden" value="<?= $_REQUEST['items']?>">
    <input id="itemDest" type="hidden" value="<?= $_REQUEST['dest']?>">
</div>
<?php break;


case "updateMass":
$data=explode("|",$_REQUEST['newCode']);
$r=mysqli_query($GLOBALS['con'],"UPDATE `itemdetails` SET `code`='".$data[0]."', `desc`='".$data[1]."' WHERE `itemnumber`='".$_REQUEST['itemnumber']."'");
$e=mysqli_error($GLOBALS['con']);
if(empty($e)){
echo "done";
exit;	
}

break;
}?>

<div id="erm" class="text-center"></div>
<script>
function changeCode() {
    var selectElement = document.getElementById('code');
    var selected = selectElement.value;
    var items = $('#itemList').val();
    var dest = encodeURI(ROOT_URL + "/includes/master/codeChange.php?mode=massConfirm&items=" + items + "&dest=" + selected + "&clientnumber=<?= $_REQUEST['clientnumber']?>&tenant=<?=$tenant?>")
    var modalElement = document.getElementById('popupBox');
    var modalInstance = mdb.Modal.getInstance(modalElement);

    if (modalInstance) {
        modalInstance.dispose();
    }
    loadModalContent(dest, "popupBox", "modal-md", 1060, "true", "Confirm code change", "cancelConfirm", confirmMassCodeChange);
}

function confirmMassCodeChange() {
    var items = document.getElementById('itemList').value;
    var dest = document.getElementById('itemDest').value;
    var arr = items.split(",");

    arr.forEach(function(value) {
        var i = value.replace('C', '');

        var formData = new FormData();
        formData.append('tenant', TENANT_URL);
        formData.append('mode', 'updateMass');
        formData.append('clientnumber', "<?= $_REQUEST['clientnumber']?>");
        formData.append('newCode', dest);
        formData.append('itemnumber', i);

        fetch(`${ROOT_URL}/includes/master/codeChange.php`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                // Handle the response data if needed
            })
            .catch(error => console.error('Error:', error));
    });

    setTimeout(function() {
        location.reload();
    }, 300);
}
</script>
