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

switch ($_REQUEST['mode']) {
    default:
        $d = explode("|", $_REQUEST['data']);

     if ($_REQUEST['mode'] === 'update') {
    if ($_REQUEST['statuslive'] === 'archive') {
        $sl = 0;
        $dt = time();
    } elseif ($_REQUEST['statuslive'] === 'activate') {
        $sl = 1;
        $dt = null;     // will write SQL NULL
    } else {
        exit('bad statuslive');
    }

    $itemnumber = (int)($_REQUEST['itemnumber'] ?? 0);

    $stmt = $GLOBALS['con']->prepare(
        "UPDATE `itemdetails` SET `statuslive` = ?, `archived` = ? WHERE `itemnumber` = ?"
    );
    $stmt->bind_param('iii', $sl, $dt, $itemnumber);
    $stmt->execute();
    $stmt->close();

    echo 'done';
    exit;
}


        if ($_REQUEST['mode'] == "updateClient") {
            if ($_REQUEST['statuslive'] == "archive") {
                $sl = 0;
            }
            if ($_REQUEST['statuslive'] == "activate") {
                $sl = 1;
            }
            $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `statuslive`='" . $sl . "' WHERE `clientnumber`=?") or die(mysqli_error($GLOBALS['con']));
            $stmt->bind_param('i', $_REQUEST['clientnumber']);
            $stmt->execute();
            $stmt->close();
            //genClients($_REQUEST['clientnumber']);
            echo "done";
            exit();
        }

        if ($d[1] == "CLIENT") { ?>
<div class="row">
    <?php if ($d[3] == "archive") { ?>
    <div class="col-12 text-center">
        <h2>Confirm archiving client</h2>
        <h5><?= getClientName($d['0'], 'name') ?><br></h5>
    </div>
    <?php } ?>
    <?php if ($d[3] == "activate") { ?>
    <div class="col-12 text-center">
        <h2>Confirm reinstating client</h2>
        <h5><?= getClientName($d['0'], 'name') ?><br></h5>
    </div>
    <?php } ?>
    <div class="col-12"> <br></div>
    <div class="col-6 text-center"><a id="btnConfirm" href="javascript:void(0)" class="btn btn-success">Confirm</a>
    </div>
    <div class="col-6 text-center"><a id="btnCancel" href="javascript:void(0)" class="btn btn-danger">Cancel</a></div>
</div>
<div id="erm" class="text-center"></div>


<script>

$("#btnConfirm").click(function() {

    $.post(ROOT_URL + '/includes/master/archive.php', {
        tenant: "<?= $systemUser ?>",
        mode: "updateClient",
        clientnumber: <?= $d['0'] ?>,
        itemnumber: "<?= $d['2'] ?>",
        statuslive: "<?= $d['3'] ?>"
    }, function(data) { //alert(data)
        if ($.trim(data) == "error") {
            $("#erm").fadeIn(1000);
            $("#erm").addClass('alert-danger');
            $("#erm").html('<p>There has been an error</p>');
            $("#erm").fadeOut(8000)
        }
        if ($.trim(data) == "done") {
            $("#erm").fadeIn(1000);
            $("#erm").removeClass('alert-danger');
            $("#erm").addClass('alert-success');
            $("#erm").html('<p>Item updated successfully</p>');
            setTimeout(function() {
                location.reload();
            }, 300)
        }
    })

})
</script>

<?php } else {

            require_once('form_functions.php');
            if ($d[3] == "archive") { ?>

<div class="row">
    <div class="col-12 text-center">
        <h2>Confirm archiving asset</h2>from<br>
        <h5><?= getItemLocation($d['2'], 'name') ?><br></h5>
    </div>
    <div class="col-12"> <br></div>
    <div class="col-6 text-center"><a id="btnConfirm" href="javascript:void(0)" class="btn btn-success">Confirm</a>
    </div>
    <div class="col-6 text-center"><a id="btnCancel" href="javascript:void(0)" class="btn btn-danger">Cancel</a></div>
</div>
<div id="erm" class="text-center"></div>
<?php }

            if ($d[3] == "activate") { ?>

<div class="row">
    <div class="col-12 text-center">
        <h2>Confirm reinstating asset</h2>to<br>
        <h5><?= getItemLocation($d['2'], 'name') ?><br></h5>
    </div>
    <div class="col-12"> <br></div>
    <div class="col-6 text-center"><a id="btnConfirm" href="javascript:void(0)" class="btn btn-success">Confirm</a>
    </div>
    <div class="col-6 text-center"><a id="btnCancel" href="javascript:void(0)" class="btn btn-danger">Cancel</a></div>
</div>
<div id="erm" class="text-center"></div>

<?php } ?>

<script>
$("#btnConfirm").click(function() {

    $.post(ROOT_URL + '/includes/master/archive.php', {
        tenant: "<?= $systemUser ?>",
        mode: "update",
        clientnumber: <?= $d['0'] ?>,
        itemnumber: "<?= $d['2'] ?>",
        statuslive: "<?= $d['3'] ?>"
    }, function(data) {
        //alert(data)
        if ($.trim(data) == "error") {
            $("#erm").fadeIn(1000);
            $("#erm").addClass('alert-danger');
            $("#erm").html('<p>There has been an error</p>');
            $("#erm").fadeOut(8000)
        }
        if ($.trim(data) == "done") {
            $("#erm").fadeIn(1000);
            $("#erm").removeClass('alert-danger');
            $("#erm").addClass('alert-success');
            $("#erm").html('<p>Item updated successfully</p>');
            setTimeout(function() {
                location.reload();
            }, 300)
        }
    })

})
</script>
<?php }
        break;

    case "mass":
        $items = explode(",", $_REQUEST['items']);
        $iCount = count($items);
        ?>
<p class="lead">You have chosen to mass archive 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="col-12 text-center"><a class="btn btn-info waves-effect"
        onClick="confirmMassArchive('<?= $_REQUEST['items'] ?>')">Confirm Archive</a></div>

<?php break;

    case "reinstate":
        $items = explode(",", $_REQUEST['items']);
        $iCount = count($items);
    ?>
<p class="lead">You have chosen to mass archive 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="col-12 text-center"><a class="btn btn-info waves-effect"
        onClick="confirmMassReinstate('<?= $_REQUEST['items'] ?>')">Confirm Reinstate</a></div>
<script>
$('#popupBox .modal-header').html(
    '<a href="javascript:void(0)" class="sa">Mass Asset Reinstate</a><div class="col-md-7 pull-right text-end" style="margin-top:30px"><h6>[ <?= $d[3] ?> ]</h6></div></div>'
);
</script>
<?php break;

    case "massArchiveConfirm": ?>
<?php
        $items = explode(",", $_REQUEST['data']);
        $count = count($items);
        ?>
<div class="row">
    <div class="col-12 text-center mb-4">
        <h2>Confirm mass archiving of <span class="badge badge-pill badge-dark"><?= $count ?></span> items</h2>
    </div>
    <div class="row mb-4">
        <div class="col-6 text-center"><a id="btnMassArchiveConfirm" href="javascript:void(0)"
                class="btn btn-success waves-effect">Confirm</a></div>
        <div class="col-6 text-center"><a id="btnCancel" href="javascript:void(0)"
                class="btn btn-danger waves-effect">Cancel</a></div>
    </div>
    <input id="itemList" type="hidden" value="<?= $_REQUEST['data'] ?>">
</div>
<?php break;

    case "massReinstateConfirm": ?>
<?php
        $items = explode(",", $_REQUEST['data']);
        $count = count($items);
        ?>

<div class="row">
    <div class="col-12 text-center">
        <h1>Confirm mass reinstating of <span class="badge badge-pill badge-dark"><?= $count ?></span> items</h2>
    </div>
    <div class="col-12"> <br></div>
    <div class="col-6 text-center"><a id="btnMassReinstateConfirm" href="javascript:void(0)"
            class="btn btn-success waves-effect">Confirm</a></div>
    <div class="col-6 text-center"><a id="btnCancel" href="javascript:void(0)"
            class="btn btn-danger waves-effect">Cancel</a></div>
    <input id="itemList" type="hidden" value="<?= $_REQUEST['data'] ?>">
</div>
<?php break;

    case "updateMassArchive":
        $items = explode(",", $_REQUEST['itemsList']);
        foreach ($items as $itemnumber) {
            $itemnumber = str_replace("C", "", $itemnumber);
            $r = mysqli_query($GLOBALS['con'], "UPDATE `itemdetails` SET `statuslive`='0', `archived`='" . strtotime('now') . "' WHERE `itemnumber`='" . $itemnumber . "'");
            $e = mysqli_error($GLOBALS['con']);
            $r = mysqli_query($GLOBALS['con'], "SELECT `clientnumber` FROM `itemdetails` WHERE `itemnumber`='" . $itemnumber . "'");
            $cd = mysqli_fetch_array($r);
            if (empty($e)) { //genSchedule($cd['clientnumber']);
            }
        }
        echo "s";
        exit;
        break;

    case "updateMassReinstate":
        $items = explode(",", $_REQUEST['itemsList']);
        foreach ($items as $itemnumber) {
            $itemnumber = str_replace("C", "", $itemnumber);
            $r = mysqli_query($GLOBALS['con'], "UPDATE `itemdetails` SET `statuslive`='1', `archived`=NULL WHERE `itemnumber`='" . $itemnumber . "'");
            $e = mysqli_error($GLOBALS['con']);
            $r = mysqli_query($GLOBALS['con'], "SELECT `clientnumber` FROM `itemdetails` WHERE `itemnumber`='" . $itemnumber . "'");
            $cd = mysqli_fetch_array($r);
            if (empty($e)) { //genSchedule($cd['clientnumber']);
            }
        }
        echo "s";
        exit;
        break;
}
?>

<script>
function confirmMassArchive(i) {
    var target = ROOT_URL + '/includes/master/archive.php';
    var dest = encodeURI(target + "?mode=massArchiveConfirm&data=" + i + "&tenant=<?= $_REQUEST['tenant'] ?>")
    //$('#popupBox').modal('show');
    $('#popupBox .modal-body').load(dest);
}

function confirmMassReinstate(i) {
    var target = ROOT_URL + '/includes/master/archive.php';
    var dest = encodeURI(target + "?mode=massReinstateConfirm&data=" + i + "&tenant=<?= $_REQUEST['tenant'] ?>")
    //$('#popupBox').modal('show');
    $('#popupBox .modal-body').load(dest);
}

$("#btnCancel").click(function() {
    $('#popupBox').modal('hide');
})

$("#btnMassArchiveConfirm").click(function() {
    var items = $('#itemList').val();
    $('#popupBox .modal-body').html(
        '<h1 class="text-center"><i class="fad fa-file-archive fa-spin fa-3x fa-fw" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Archiving Assets <br><small>Please wait</small><span class="sr-only">Moving...</span></h1>'
    );
    $.post(ROOT_URL + '/includes/master/archive.php', {
        tenant: "<?= $_REQUEST['tenant'] ?>",
        mode: "updateMassArchive",
        itemsList: items
    }, function(data) {
        // debug(data)
        if ($.trim(data) == "s") {
            location.reload();
        }
    })
})

$("#btnMassReinstateConfirm").click(function() {
    var items = $('#itemList').val();
    $('#popupBox .modal-body').html(
        '<h1 class="text-center"><i class="fad fa-file-archive fa-spin fa-3x fa-fw" style="--fa-primary-color: #0055A6; --fa-secondary-color: gray;"></i><br>Reinstating Assets <br><small>Please wait</small><span class="sr-only">Moving...</span></h1>'
    );
    $.post(ROOT_URL + '/includes/master/archive.php', {
        tenant: "<?= $_REQUEST['tenant'] ?>",
        mode: "updateMassReinstate",
        itemsList: items
    }, function(data) { //debug(data)
        if ($.trim(data) == "s") {
            location.reload();
        }
    })
})
</script>