<?php
require_once '../../functions/security.php';

$tenantSegment = enrep_tenant_segment();
if ($tenantSegment !== '' && file_exists('../../../' . $tenantSegment . '/config.php')) {
    require_once('../../../' . $tenantSegment . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}

enrep_require_user();

function transfer_e($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function transfer_tenant_url(string $tenant): string
{
    return defined('TENANT_URL') ? (string)TENANT_URL : '/' . $tenant;
}

function transfer_data_parts(): array
{
    return array_pad(explode('|', enrep_request_string('data', '', 600)), 5, '');
}

function transfer_mdb_select_html(string $html): string
{
    $html = str_replace(' data-mdb-select-init', '', $html);
    $html = str_replace(
        'id="transferSelect" class="form-control transferOption"',
        'id="transferSelect" class="form-control transferOption" data-mdb-filter="true"',
        $html
    );
    return str_replace(
        'id="transferSelect" class="form-control massTransferOption" ',
        'id="transferSelect" class="form-control massTransferOption" data-mdb-filter="true" ',
        $html
    );
}

function transfer_update_single(int $oldLocation, int $newLocation, int $itemnumber): void
{
    if ($oldLocation < 1 || $newLocation < 1 || $itemnumber < 1) {
        enrep_fail(400, 'Invalid transfer request');
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `locnumber`=? WHERE `locnumber`=? AND `itemnumber`=?");
    if (!$stmt) {
        enrep_fail(500, 'Transfer failed');
    }
    $stmt->bind_param('iii', $newLocation, $oldLocation, $itemnumber);

    if (!$stmt->execute()) {
        $stmt->close();
        enrep_fail(500, 'Transfer failed');
    }
    $stmt->close();
}

function transfer_update_item(int $newLocation, int $itemnumber): void
{
    if ($newLocation < 1 || $itemnumber < 1) {
        enrep_fail(400, 'Invalid transfer request');
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `locnumber`=? WHERE `itemnumber`=?");
    if (!$stmt) {
        enrep_fail(500, 'Transfer failed');
    }
    $stmt->bind_param('ii', $newLocation, $itemnumber);

    if (!$stmt->execute()) {
        $stmt->close();
        enrep_fail(500, 'Transfer failed');
    }
    $stmt->close();
}

$mode = enrep_request_string('mode', '', 80);
$tenantUrl = transfer_tenant_url($tenantSegment);
$parts = transfer_data_parts();
$clientnumber = enrep_request_int('clientnumber', (int)$parts[0]);
$currentLocation = (int)$parts[1];
$targetLocation = $mode === 'confirm' ? (int)$parts[2] : 0;
$itemnumber = $mode === 'confirm' ? (int)$parts[3] : (int)$parts[2];
$itemDescription = $mode === 'confirm' ? $parts[4] : $parts[3];

switch ($mode) {
    case 'confirm':
        if ($clientnumber < 1 || $currentLocation < 1 || $targetLocation < 1 || $itemnumber < 1) {
            enrep_fail(400, 'Invalid transfer request');
        }
        ?>
<div class="row">
    <div class="col-12 text-center">
        <h1>Confirm moving asset from<br></h1>
        <span class="lead"><?= transfer_e(getLocation($currentLocation)) ?></span>&nbsp;&nbsp;&nbsp;<i
            class="fa fa-angle-double-right fa-2x" aria-hidden="true"></i>&nbsp;&nbsp;&nbsp;<span class="lead">
            <?= transfer_e(getLocation($targetLocation)) ?></span>
    </div>
</div>
<?php
        break;

    case 'update':
        transfer_update_single(
            enrep_request_int('itemlocationOld'),
            enrep_request_int('itemlocationNew'),
            enrep_request_int('itemnumber')
        );
        echo 'done';
        exit;

    case 'mass':
        $items = enrep_request_int_list('items');
        $itemsValue = implode(',', $items);
        $iCount = count($items);
        $clientnumber = enrep_request_int('clientnumber', $clientnumber);
        if ($clientnumber < 1) {
            enrep_fail(400, 'Invalid client');
        }
        ?>
<p class="lead">You have chosen to mass relocate the following <b><?= $iCount ?></b> items</p>
<div class="row" style="max-height:200px; overflow:auto">
    <?php foreach ($items as $item) { ?>
    <div class="col-md-3">
        <div class="card me-2 mb-2 p-2 border border-info"><?= (int)$item ?> -
            <?= transfer_e(getItemDetails((int)$item, 'name')) ?></div>
    </div>
    <?php } ?>
    <input id="itemList" type="hidden" value="<?= transfer_e($itemsValue) ?>">
</div>
<div class="row p-3">
    <div class="col-12">
        <span class="lead">Select a location to relocate the items to</span>
    </div>
    <div class="col-12 mt-3 mb-4">
        <?= transfer_mdb_select_html(listClientLocationsMass($clientnumber)) ?>
    </div>
</div>
<script>
$('#popupBox .modal-header').html('<a href="javascript:void(0)" class="sa">Mass Asset Transfer</a>');
</script>
<?php
        break;

    case 'massConfirm':
        $itemsValue = implode(',', enrep_request_int_list('items'));
        $dest = enrep_request_int('dest');
        $clientnumber = enrep_request_int('clientnumber', $clientnumber);
        if ($dest < 1 || $clientnumber < 1) {
            enrep_fail(400, 'Invalid transfer request');
        }
        ?>
<script>
$('#popupBox .modal-header').html('<a href="javascript:void(0)" class="sa">Mass Asset Transfer</a>');
</script>
<div class="row">
    <div class="col-12 text-center">
        <h1>Confirm moving assets to<br></h1>
        <h1 class="badge badge-pill badge-primary"><span class="lead"><?= transfer_e(getLocation($dest)) ?></span></h1>
    </div>
    <input id="itemList" type="hidden" value="<?= transfer_e($itemsValue) ?>">
    <input id="itemDest" type="hidden" value="<?= (int)$dest ?>">
</div>
<?php
        break;

    case 'updateMass':
        transfer_update_item(enrep_request_int('itemlocationNew'), enrep_request_int('itemnumber'));
        echo 'done';
        exit;

    default:
        if ($clientnumber < 1 || $currentLocation < 1) {
            enrep_fail(400, 'Invalid transfer request');
        }
        ?>
<div class="row">
    <div class="form-group col-12">
        <p><strong>Current location:</strong> <?= transfer_e(getLocation($currentLocation)) ?></p>
        <div id="transferRow">
            <?= transfer_mdb_select_html(listClientLocations($clientnumber, $currentLocation, $itemnumber, $itemDescription)) ?>
        </div>
    </div>
</div>
<?php
        break;
}
?>

<div id="erm" class="text-center"></div>
<script>
(function() {
    const transferTenant = <?= json_encode($tenantUrl) ?>;
    const transferClientnumber = <?= (int)$clientnumber ?>;
    const confirmPayload = {
        oldLocation: <?= (int)$currentLocation ?>,
        newLocation: <?= (int)$targetLocation ?>,
        itemnumber: <?= (int)$itemnumber ?>
    };

    $(".singleTransferOption").off('click').on('click', function() {
        openTransferConfirm($(this).data('string'));
    });

    $(".transferOption").off('change').on('change', function() {
        openTransferConfirm($(this).find(':selected').data('string'));
    });

    $(".massTransferOption").off('change').on('change', function() {
        killModal('transferBox');
        const target = ROOT_URL + '/includes/master/transfer.php';
        const selectedDest = $(this).find(':selected').data('string');
        const items = $('#itemList').val();
        const dest = target + "?mode=massConfirm&items=" + encodeURIComponent(items) + "&dest=" + encodeURIComponent(selectedDest) + "&clientnumber=" + transferClientnumber + "&tenant=" + encodeURIComponent(transferTenant);
        loadModalContent(dest, "popupBox", "modal-md", 1060, "true", 'Transfer Selected Items', 'cancelConfirm', transferMassConfirmAction);
    });

    $(".massTransferSingle").off('click').on('click', function() {
        killModal('transferBox');
        const target = ROOT_URL + '/includes/master/transfer.php';
        const selectedDest = $(this).data('string');
        const items = $('#itemList').val();
        const dest = target + "?mode=massConfirm&items=" + encodeURIComponent(items) + "&dest=" + encodeURIComponent(selectedDest) + "&clientnumber=" + transferClientnumber + "&tenant=" + encodeURIComponent(transferTenant);
        loadModalContent(dest, "popupBox", "modal-md", 1060, "true", 'Transfer Selected Items', 'cancelConfirm', transferMassConfirmAction);
    });

    function openTransferConfirm(dataString) {
        const payloadParts = String(dataString || '').split('|');
        if ((parseInt(payloadParts[1], 10) || 0) < 1 || (parseInt(payloadParts[2], 10) || 0) < 1 || (parseInt(payloadParts[3], 10) || 0) < 1) {
            if (typeof showResponse === 'function') {
                showResponse('warning', 'Please select a valid destination location.');
            }
            return;
        }

        killModal('transferBox');
        const target = ROOT_URL + '/includes/master/transfer.php';
        const dest = target + "?mode=confirm&data=" + encodeURIComponent(dataString) + "&clientnumber=" + transferClientnumber + "&tenant=" + encodeURIComponent(transferTenant);
        loadModalContent(dest, "popupBox", "modal-md", 1060, "true", 'Transfer Single Item', 'cancelConfirm', function() {
            transferConfirmAction(dataString);
        });
    }

    function transferConfirmAction(dataString) {
        const payloadParts = String(dataString || '').split('|');
        const transferPayload = {
            oldLocation: parseInt(payloadParts[1], 10) || confirmPayload.oldLocation,
            newLocation: parseInt(payloadParts[2], 10) || confirmPayload.newLocation,
            itemnumber: parseInt(payloadParts[3], 10) || confirmPayload.itemnumber
        };

        $.post(ROOT_URL + '/includes/master/transfer.php', {
            mode: "update",
            clientnumber: transferClientnumber,
            itemlocationOld: transferPayload.oldLocation,
            itemlocationNew: transferPayload.newLocation,
            itemnumber: transferPayload.itemnumber,
            tenant: transferTenant
        }, function(data) {
            if ($.trim(data) == "error") {
                $("#erm").fadeIn(1000).addClass('alert-danger').html('<p>There has been an error</p>').fadeOut(8000);
            }
            if ($.trim(data) == "done") {
                $("#erm").fadeIn(1000).removeClass('alert-danger').addClass('alert-success').html('<p>Item moved successfully</p>');
                setTimeout(function() { location.reload(); }, 300);
            }
        });
    }

    function transferMassConfirmAction() {
        const items = $('#itemList').val();
        const dest = $('#itemDest').val();
        const arr = items.split(",");
        $.each(arr, function(index, value) {
            const i = String(value).replace('C', '');
            $.post(ROOT_URL + '/includes/master/transfer.php', {
                mode: "updateMass",
                clientnumber: transferClientnumber,
                itemlocationNew: dest,
                itemnumber: i,
                tenant: transferTenant
            }, function(data) {});
        });
        setTimeout(function() {
            location.reload();
        }, 300);
    }

    const transferSelect = document.getElementById('transferSelect');
    if (transferSelect && window.mdb && mdb.Select && !transferSelect.classList.contains('select-initialized')) {
        transferSelect.setAttribute('data-mdb-filter', 'true');
        new mdb.Select(transferSelect, {
            filter: true
        });
    }
})();
</script>
