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

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
require_once __DIR__ . '/../plant_changes/plant_change_helpers.php';

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

enrep_require_user();

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

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

function archive_data_parts(): array
{
    return array_pad(explode('|', enrep_request_string('data', '', 500)), 4, '');
}

function archive_status_from_request(): string
{
    $status = enrep_request_enum('statuslive', ['archive', 'activate'], '');
    if ($status === '') {
        enrep_fail(400, 'Invalid archive status');
    }
    return $status;
}

function archive_update_item(int $itemnumber, string $statuslive): void
{
    if ($itemnumber < 1) {
        enrep_fail(400, 'Invalid item');
    }

    $plantChangeOldSnapshot = plantChangeSnapshot($itemnumber);

    if ($statuslive === 'archive') {
        $archived = time();
        $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `statuslive`=0, `archived`=?, `linked`='' WHERE `itemnumber`=?");
        if (!$stmt) {
            enrep_fail(500, 'Update failed');
        }
        $stmt->bind_param('ii', $archived, $itemnumber);
    } else {
        $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `statuslive`=1, `archived`=NULL, `linked`='' WHERE `itemnumber`=?");
        if (!$stmt) {
            enrep_fail(500, 'Update failed');
        }
        $stmt->bind_param('i', $itemnumber);
    }

    if (!$stmt->execute()) {
        $stmt->close();
        enrep_fail(500, 'Update failed');
    }
    $stmt->close();
    plantChangeLogUpdate($plantChangeOldSnapshot, $itemnumber, $statuslive === 'archive' ? 'asset_archive' : 'asset_reinstate');
}

function archive_update_client(int $clientnumber, string $statuslive): void
{
    if ($clientnumber < 1) {
        enrep_fail(400, 'Invalid client');
    }

    $status = $statuslive === 'archive' ? 0 : 1;
    $stmt = $GLOBALS['con']->prepare("UPDATE `clientdetails` SET `statuslive`=? WHERE `clientnumber`=?");
    if (!$stmt) {
        enrep_fail(500, 'Update failed');
    }
    $stmt->bind_param('ii', $status, $clientnumber);

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

function archive_update_mass(array $items, string $statuslive): void
{
    if (empty($items)) {
        enrep_fail(400, 'No items selected');
    }

    $source = $statuslive === 'archive' ? 'asset_mass_archive' : 'asset_mass_reinstate';

    if ($statuslive === 'archive') {
        $archived = time();
        $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `statuslive`=0, `archived`=? WHERE `itemnumber`=?");
        if (!$stmt) {
            enrep_fail(500, 'Update failed');
        }

        foreach ($items as $itemnumber) {
            $plantChangeOldSnapshot = plantChangeSnapshot((int)$itemnumber);
            $stmt->bind_param('ii', $archived, $itemnumber);
            if (!$stmt->execute()) {
                $stmt->close();
                enrep_fail(500, 'Update failed');
            }
            plantChangeLogUpdate($plantChangeOldSnapshot, (int)$itemnumber, $source);
        }
        $stmt->close();
        return;
    }

    $stmt = $GLOBALS['con']->prepare("UPDATE `itemdetails` SET `statuslive`=1, `archived`=NULL WHERE `itemnumber`=?");
    if (!$stmt) {
        enrep_fail(500, 'Update failed');
    }

    foreach ($items as $itemnumber) {
        $plantChangeOldSnapshot = plantChangeSnapshot((int)$itemnumber);
        $stmt->bind_param('i', $itemnumber);
        if (!$stmt->execute()) {
            $stmt->close();
            enrep_fail(500, 'Update failed');
        }
        plantChangeLogUpdate($plantChangeOldSnapshot, (int)$itemnumber, $source);
    }
    $stmt->close();
}

function archive_render_confirm_styles(): void
{
?>
    <style>
        .archive-confirm {
            max-width: 620px;
            margin: 0 auto;
            padding: 12px 10px 4px;
            text-align: center;
        }

        .archive-confirm__icon {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 58px;
            height: 58px;
            margin-bottom: 14px;
            border-radius: 50%;
            color: #ffffff;
            background: #1f3f5f;
            box-shadow: 0 10px 22px rgba(31, 63, 95, 0.22);
        }

        .archive-confirm__icon i {
            font-size: 1.55rem;
        }

        .archive-confirm--archive .archive-confirm__icon {
            background: #34495e;
        }

        .archive-confirm--reinstate .archive-confirm__icon {
            background: #168754;
        }

        .archive-confirm__eyebrow {
            margin: 0 0 6px;
            color: #607080;
            font-size: 0.78rem;
            font-weight: 700;
            text-transform: uppercase;
        }

        .archive-confirm__title {
            margin: 0;
            color: #233446;
            font-size: 1.45rem;
            font-weight: 700;
            line-height: 1.25;
        }

        .archive-confirm__count {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 42px;
            height: 34px;
            margin: 0 4px;
            padding: 0 12px;
            border-radius: 18px;
            color: #ffffff;
            background: #233446;
            font-size: 1rem;
            font-weight: 700;
            vertical-align: middle;
        }

        .archive-confirm__detail {
            max-width: 500px;
            margin: 12px auto 0;
            padding: 12px 16px;
            border: 1px solid #d7dee6;
            border-radius: 8px;
            color: #2f3c4a;
            background: #f7f9fb;
            font-size: 1rem;
            font-weight: 600;
        }
    </style>
<?php
}

function archive_render_confirm_panel(string $tone, string $eyebrow, string $titleHtml, string $detailHtml, string $itemList = ''): void
{
    $icon = $tone === 'reinstate' ? 'fa-undo' : 'fa-archive';
    archive_render_confirm_styles();
?>
    <div class="archive-confirm archive-confirm--<?= archive_e($tone) ?>">
        <div class="archive-confirm__icon"><i class="fad <?= archive_e($icon) ?>"></i></div>
        <p class="archive-confirm__eyebrow"><?= archive_e($eyebrow) ?></p>
        <h2 class="archive-confirm__title"><?= $titleHtml ?></h2>
        <?php if ($detailHtml !== '') { ?>
            <div class="archive-confirm__detail"><?= $detailHtml ?></div>
        <?php } ?>
        <?php if ($itemList !== '') { ?>
            <input id="itemList" type="hidden" value="<?= archive_e($itemList) ?>">
        <?php } ?>
    </div>
    <?php
}

$mode = enrep_request_string('mode', '', 80);
$tenantUrl = archive_tenant_url($tenant);
$parts = archive_data_parts();
$clientnumberFromData = (int)$parts[0];
$itemnumberFromData = (int)$parts[2];
$statusFromData = in_array((string)$parts[3], ['archive', 'activate'], true) ? (string)$parts[3] : 'archive';

switch ($mode) {
    case 'update':
        archive_update_item(enrep_request_int('itemnumber'), archive_status_from_request());
        echo 'done';
        exit;

    case 'updateClient':
        archive_update_client(enrep_request_int('clientnumber'), archive_status_from_request());
        echo 'done';
        exit;

    case 'updateMassArchive':
        archive_update_mass(enrep_request_int_list('itemsList'), 'archive');
        echo 's';
        exit;

    case 'updateMassReinstate':
        archive_update_mass(enrep_request_int_list('itemsList'), 'activate');
        echo 's';
        exit;

    case 'mass':
        $items = enrep_request_int_list('items');
        $itemsValue = implode(',', $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) { ?>
                <div class="col-md-3">
                    <div class="card me-2 mb-2 p-2"><?= (int)$item ?> - <?= archive_e(getItemDetails((int)$item, 'name')) ?></div>
                </div>
            <?php } ?>
            <input id="itemList" type="hidden" value="<?= archive_e($itemsValue) ?>">
        </div>
    <?php
        break;

    case 'reinstate':
        $items = enrep_request_int_list('items');
        $itemsValue = implode(',', $items);
        $iCount = count($items);
    ?>
        <p class="lead">You have chosen to mass reinstate 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-4">
                    <div class="card me-2 mb-2 p-2"><?= (int)$item ?> - <?= archive_e(getItemDetails((int)$item, 'name')) ?></div>
                </div>
            <?php } ?>
            <input id="itemList" type="hidden" value="<?= archive_e($itemsValue) ?>">
        </div>
        <script>
            $('#popupBox .modal-header').html('<a href="javascript:void(0)" class="sa">Mass Asset Reinstate</a>');
        </script>
<?php
        break;

    case 'massArchiveConfirm':
        $itemsValue = implode(',', enrep_request_int_list('data'));
        $count = count(enrep_int_list_from_mixed($itemsValue));
        archive_render_confirm_panel(
            'archive',
            'Mass archive',
            'Archive <span class="archive-confirm__count">' . (int)$count . '</span> selected items?',
            'These assets will be moved out of the active schedule.',
            $itemsValue
        );
        break;

    case 'massReinstateConfirm':
        $itemsValue = implode(',', enrep_request_int_list('data'));
        $count = count(enrep_int_list_from_mixed($itemsValue));
        archive_render_confirm_panel(
            'reinstate',
            'Mass reinstate',
            'Reinstate <span class="archive-confirm__count">' . (int)$count . '</span> selected items?',
            'These assets will be returned to the active schedule.',
            $itemsValue
        );
        break;

    default:
        if ($clientnumberFromData < 1 || $itemnumberFromData < 1 || !in_array($statusFromData, ['archive', 'activate'], true)) {
            enrep_fail(400, 'Invalid archive request');
        }

        if (strtoupper((string)$parts[1]) === 'CLIENT') {
            $isArchive = $statusFromData === 'archive';
            archive_render_confirm_panel(
                $isArchive ? 'archive' : 'reinstate',
                $isArchive ? 'Archive client' : 'Reinstate client',
                $isArchive ? 'Archive this client?' : 'Reinstate this client?',
                archive_e(getClientName($clientnumberFromData, 'name'))
            );
        } else {
            require_once __DIR__ . '/form_functions.php';
            $isArchive = $statusFromData === 'archive';
            archive_render_confirm_panel(
                $isArchive ? 'archive' : 'reinstate',
                $isArchive ? 'Archive asset' : 'Reinstate asset',
                $isArchive ? 'Archive this asset?' : 'Reinstate this asset?',
                ($isArchive ? 'From ' : 'To ') . archive_e(getItemLocation($itemnumberFromData, 'name'))
            );
        }
        break;
}
?>

<script>
    (function() {
        const archiveTenant = <?= json_encode($tenantUrl) ?>;

        window.confirmMassArchive = function(items) {
            killModal('popupBox');
            const target = ROOT_URL + '/includes/master/archive.php';
            const dest = target + '?mode=massArchiveConfirm&data=' + encodeURIComponent(items) + '&tenant=' +
                encodeURIComponent(archiveTenant);
            loadModalContent(dest, 'archiveConfirmBox', 'modal-md', 1070, 'true', 'Confirm archive',
                'cancelConfirm',
                function() {
                    archiveRunMassUpdate(items, 'updateMassArchive', 'Archiving Assets');
                });
        };

        window.confirmMassReinstate = function(items) {
            const target = ROOT_URL + '/includes/master/archive.php';
            const dest = target + '?mode=massReinstateConfirm&data=' + encodeURIComponent(items) + '&tenant=' +
                encodeURIComponent(archiveTenant);
            loadModalContent(dest, 'archiveConfirmBox', 'modal-md', 1070, 'true', 'Confirm reinstate',
                'cancelConfirm',
                function() {
                    archiveRunMassUpdate(items, 'updateMassReinstate', 'Reinstating Assets');
                });
        };

        function archiveRunMassUpdate(items, mode, label) {
            const confirmBox = document.querySelector('#archiveConfirmBox .modal-body');
            const targetBox = confirmBox || document.querySelector('#popupBox .modal-body');
            if (targetBox) {
                targetBox.innerHTML =
                    '<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>' +
                    label + ' <br><small>Please wait</small></h1>';
            }
            $.post(ROOT_URL + '/includes/master/archive.php', {
                tenant: archiveTenant,
                mode: mode,
                itemsList: items
            }, function(data) {
                if ($.trim(data) == "s") {
                    location.reload();
                }
            });
        }
    })();
</script>