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

$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$setId = (int)($_REQUEST['set_id'] ?? 0);
$tenant = (string)($_REQUEST['tenant'] ?? '');

if ($clientnumber <= 0) {
    echo '<div class="p-3 text-danger">Invalid client.</div>';
    exit;
}

$setRow = [
    'id' => 0,
    'template_id' => 0,
    'set_title' => '',
    'itemnumbers_json' => '[]',
    'status' => 1
];

if ($setId > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT `id`, `template_id`, `set_title`, `itemnumbers_json`, `status`
        FROM `puwer_item_sets`
        WHERE `id` = ? AND `clientnumber` = ?
        LIMIT 1
    ") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $setId, $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $tmp = mysqli_fetch_assoc($res);
    if (is_array($tmp)) {
        $setRow = array_merge($setRow, $tmp);
    }
}

$selectedItems = json_decode((string)$setRow['itemnumbers_json'], true);
if (!is_array($selectedItems)) {
    $selectedItems = [];
}
$selectedItems = array_values(array_unique(array_map('intval', $selectedItems)));
$selectedLookup = array_flip($selectedItems);

$templates = [];
$resTemplates = mysqli_query(
    $GLOBALS['con'],
    "SELECT `id`, `template_title`
     FROM `puwer_templates`
     WHERE `status` = 1
     ORDER BY `sort_order` ASC, `id` ASC"
) or die(mysqli_error($GLOBALS['con']));

while ($row = mysqli_fetch_assoc($resTemplates)) {
    $templates[] = $row;
}

$assignedItemIds = [];
$stmtAssigned = $GLOBALS['con']->prepare("
    SELECT `id`, `itemnumbers_json`
    FROM `puwer_item_sets`
    WHERE `clientnumber` = ?
      AND `status` = 1
      AND `id` != ?
") or die(mysqli_error($GLOBALS['con']));
$stmtAssigned->bind_param('ii', $clientnumber, $setId);
$stmtAssigned->execute();
$resAssigned = $stmtAssigned->get_result();
$stmtAssigned->close();

while ($row = mysqli_fetch_assoc($resAssigned)) {
    $items = json_decode((string)($row['itemnumbers_json'] ?? '[]'), true);
    if (!is_array($items)) {
        continue;
    }

    foreach ($items as $itemId) {
        $itemId = (int)$itemId;
        if ($itemId > 0) {
            $assignedItemIds[$itemId] = true;
        }
    }
}

$items = [];
$stmtItems = $GLOBALS['con']->prepare("
    SELECT `itemnumber`, `plantnumber`, `desc`, `serialnumber`, `locnumber`, `subloc`
    FROM `itemdetails`
    WHERE `clientnumber` = ?
      AND `statuslive` = 1
    ORDER BY `plantnumber` ASC, `desc` ASC, `itemnumber` ASC
") or die(mysqli_error($GLOBALS['con']));
$stmtItems->bind_param('i', $clientnumber);
$stmtItems->execute();
$resItems = $stmtItems->get_result();
$stmtItems->close();

while ($row = mysqli_fetch_assoc($resItems)) {
    $itemnumber = (int)$row['itemnumber'];

    if (isset($assignedItemIds[$itemnumber]) && !isset($selectedLookup[$itemnumber])) {
        continue;
    }

    $items[] = $row;
}
?>

<div class="p-3">
   
    <input type="hidden" id="puwerSetId" value="<?= (int)$setRow['id'] ?>">
    <input type="hidden" id="puwerSetClientNumber" value="<?= $clientnumber ?>">
    <input type="hidden" id="puwerSetTenant" value="<?= htmlspecialchars($tenant, ENT_QUOTES) ?>">
<div class="row">
    <div class="col-12 col-md-6">
    <div class="mb-3">
        <label class="form-label">Set Title</label>
        <input type="text" class="form-control" id="puwerSetTitle" value="<?= htmlspecialchars((string)$setRow['set_title'], ENT_QUOTES) ?>">
    </div>
</div>
<div class="col-12 col-md-6">
    <div class="mb-3">
        <label class="form-label">Template Set</label>
        <select class="form-control" id="puwerSetTemplateId">
            <option value="">Select template</option>
            <?php foreach ($templates as $template) { ?>
                <option value="<?= (int)$template['id'] ?>" <?= (int)$setRow['template_id'] === (int)$template['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars((string)$template['template_title'], ENT_QUOTES) ?>
                </option>
            <?php } ?>
        </select>
    </div>
    </div>
    </div>

    <div class="mb-3">
        <label class="form-label">Linked Items</label>

        <div class="row g-3 puwer-set-columns">
            <div class="col-12 col-lg-6">
                <div class="border rounded h-100">
                    <div class="px-3 py-2 bg-light border-bottom d-flex justify-content-between align-items-center">
                        <strong>Available Items</strong>
                        <span class="badge bg-secondary" id="puwerAvailableCount">0</span>
                    </div>
                    <div class="p-2 border-bottom">
                        <div class="input-group input-group-sm">
                            <input type="text"
                                   class="form-control puwer-set-filter"
                                   id="puwerAvailableFilter"
                                   data-filter-target="puwerAvailableItems"
                                   placeholder="Search available items">
                            <button type="button"
                                    class="btn btn-light puwer-set-filter-clear"
                                    data-clear-filter="puwerAvailableFilter"
                                    title="Clear available item search">
                                <i class="fad fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="p-2 puwer-set-list" id="puwerAvailableItems">
                        <?php foreach ($items as $row) {
                            $itemId = (int)$row['itemnumber'];
                            if (isset($selectedLookup[$itemId])) {
                                continue;
                            }
                            $label = trim((string)($row['plantnumber'] ?? ''));
                            $desc = trim((string)($row['desc'] ?? ''));
                            $serial = trim((string)($row['serialnumber'] ?? ''));
                            $subloc = trim((string)($row['subloc'] ?? ''));
                            $searchText = strtolower(trim($label . ' ' . $desc . ' ' . $serial . ' ' . $subloc));
                        ?>
                        <div class="puwer-set-item-row" data-item-id="<?= $itemId ?>" data-search="<?= htmlspecialchars($searchText, ENT_QUOTES) ?>">
                            <button type="button" class="btn btn-success btn-sm puwer-item-add" title="Add item">
                                <i class="fad fa-plus"></i>
                            </button>
                            <div class="puwer-set-item-copy">
                                <div class="fw-bold"><?= htmlspecialchars($label !== '' ? $label : ('Item ' . $itemId), ENT_QUOTES) ?></div>
                                <?php if ($desc !== '') { ?><div><?= htmlspecialchars($desc, ENT_QUOTES) ?></div><?php } ?>
                                <div class="small text-muted">
                                    <?php if ($serial !== '') { ?>S/N: <?= htmlspecialchars($serial, ENT_QUOTES) ?><?php } ?>
                                    <?php if ($subloc !== '') { ?> <?= $serial !== '' ? ' | ' : '' ?><?= htmlspecialchars($subloc, ENT_QUOTES) ?><?php } ?>
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>

            <div class="col-12 col-lg-6">
                <div class="border rounded h-100">
                    <div class="px-3 py-2 bg-light border-bottom d-flex justify-content-between align-items-center">
                        <strong>Items In Set</strong>
                        <span class="badge bg-info" id="puwerSelectedCount">0</span>
                    </div>
                    <div class="p-2 border-bottom">
                        <div class="input-group input-group-sm">
                            <input type="text"
                                   class="form-control puwer-set-filter"
                                   id="puwerSelectedFilter"
                                   data-filter-target="puwerSelectedItems"
                                   placeholder="Search items in set">
                            <button type="button"
                                    class="btn btn-light puwer-set-filter-clear"
                                    data-clear-filter="puwerSelectedFilter"
                                    title="Clear selected item search">
                                <i class="fad fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="p-2 puwer-set-list" id="puwerSelectedItems">
                        <?php foreach ($items as $row) {
                            $itemId = (int)$row['itemnumber'];
                            if (!isset($selectedLookup[$itemId])) {
                                continue;
                            }
                            $label = trim((string)($row['plantnumber'] ?? ''));
                            $desc = trim((string)($row['desc'] ?? ''));
                            $serial = trim((string)($row['serialnumber'] ?? ''));
                            $subloc = trim((string)($row['subloc'] ?? ''));
                            $searchText = strtolower(trim($label . ' ' . $desc . ' ' . $serial . ' ' . $subloc));
                        ?>
                        <div class="puwer-set-item-row" data-item-id="<?= $itemId ?>" data-search="<?= htmlspecialchars($searchText, ENT_QUOTES) ?>">
                            <button type="button" class="btn btn-danger btn-sm puwer-item-remove" title="Remove item">
                                <i class="fad fa-minus"></i>
                            </button>
                            <div class="puwer-set-item-copy">
                                <div class="fw-bold"><?= htmlspecialchars($label !== '' ? $label : ('Item ' . $itemId), ENT_QUOTES) ?></div>
                                <?php if ($desc !== '') { ?><div><?= htmlspecialchars($desc, ENT_QUOTES) ?></div><?php } ?>
                                <div class="small text-muted">
                                    <?php if ($serial !== '') { ?>S/N: <?= htmlspecialchars($serial, ENT_QUOTES) ?><?php } ?>
                                    <?php if ($subloc !== '') { ?> <?= $serial !== '' ? ' | ' : '' ?><?= htmlspecialchars($subloc, ENT_QUOTES) ?><?php } ?>
                                </div>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
        <small class="text-muted">Items already assigned to another active PUWER set are omitted.</small>
    </div>

    <div class="form-check mb-3">
        <input class="form-check-input" type="checkbox" id="puwerSetStatus" <?= !empty($setRow['status']) ? 'checked' : '' ?>>
        <label class="form-check-label" for="puwerSetStatus">Active</label>
    </div>

    <div class="d-flex gap-2">
        <button type="button" class="btn btn-info" id="savePuwerSetBtn">Save</button>
        <?php if ($setId > 0) { ?>
            <button type="button" class="btn btn-danger" id="deletePuwerSetBtn">Delete</button>
        <?php } ?>
        <button type="button" class="btn btn-secondary" onClick="killModal('popupBox')">Close</button>
    </div>
</div>

<style>
.puwer-set-list {
    max-height: 360px;
    overflow: auto;
}
.puwer-set-item-row {
    display: grid;
    grid-template-columns: 38px minmax(0, 1fr);
    gap: .5rem;
    align-items: start;
    padding: .5rem;
    border-bottom: 1px solid rgba(0, 0, 0, .08);
}
.puwer-set-item-row:last-child {
    border-bottom: 0;
}
.puwer-set-item-row .btn {
    width: 32px;
    height: 32px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 0;
}
.puwer-set-item-copy {
    min-width: 0;
    overflow-wrap: anywhere;
}
.puwer-set-empty {
    padding: .75rem;
    color: #6c757d;
}
</style>

<script>
(function () {
    const endpoint = ROOT_URL + '/includes/puwer/puwer_set_functions.php';

    function filterPuwerSetList(input) {
        if (!input) return;

        const targetId = input.getAttribute('data-filter-target');
        const target = targetId ? document.getElementById(targetId) : null;
        if (!target) return;

        const term = input ? input.value.trim().toLowerCase() : '';

        target.querySelectorAll('.puwer-set-item-row').forEach(function (row) {
            const haystack = row.getAttribute('data-search') || '';
            row.style.display = term === '' || haystack.indexOf(term) !== -1 ? '' : 'none';
        });
    }

    function filterPuwerSetItems() {
        document.querySelectorAll('.puwer-set-filter').forEach(filterPuwerSetList);
    }

    function getSelectedItemIds() {
        return [...document.querySelectorAll('#puwerSelectedItems .puwer-set-item-row')].map(function (row) {
            return parseInt(row.getAttribute('data-item-id') || '0', 10);
        }).filter(Boolean);
    }

    function setItemMode(row, mode) {
        const btn = row.querySelector('button');
        if (!btn) return;

        btn.className = mode === 'selected'
            ? 'btn btn-danger btn-sm puwer-item-remove'
            : 'btn btn-success btn-sm puwer-item-add';
        btn.title = mode === 'selected' ? 'Remove item' : 'Add item';
        btn.innerHTML = mode === 'selected'
            ? '<i class="fad fa-minus"></i>'
            : '<i class="fad fa-plus"></i>';
    }

    function moveItem(row, targetId) {
        const target = document.getElementById(targetId);
        if (!row || !target) return;

        setItemMode(row, targetId === 'puwerSelectedItems' ? 'selected' : 'available');
        row.style.display = '';
        target.appendChild(row);
        sortPuwerList(target);
        updatePuwerCounts();
        filterPuwerSetItems();
    }

    function sortPuwerList(list) {
        [...list.querySelectorAll('.puwer-set-item-row')]
            .sort(function (a, b) {
                return (a.getAttribute('data-search') || '').localeCompare(b.getAttribute('data-search') || '');
            })
            .forEach(function (row) {
                list.appendChild(row);
            });
    }

    function updatePuwerCounts() {
        const availableCount = document.querySelectorAll('#puwerAvailableItems .puwer-set-item-row').length;
        const selectedCount = document.querySelectorAll('#puwerSelectedItems .puwer-set-item-row').length;
        const availableBadge = document.getElementById('puwerAvailableCount');
        const selectedBadge = document.getElementById('puwerSelectedCount');

        if (availableBadge) availableBadge.textContent = availableCount;
        if (selectedBadge) selectedBadge.textContent = selectedCount;
    }

    function postPuwerSet(data) {
        fetch(endpoint, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams(data)
        })
        .then(r => r.json())
        .then(j => {
            showResponse(
                j.status === 'success' ? 'success' : (j.status === 'warning' ? 'warning' : 'danger'),
                j.message
            );

            if (j.status === 'success') {
                killModal('popupBox');
                if (typeof loadPuwerData === 'function') {
                    loadPuwerData('');
                }
            }
        })
        .catch(() => showResponse('danger', 'There was a problem processing the request'));
    }

    document.querySelectorAll('.puwer-set-filter').forEach(function (filterInput) {
        filterInput.addEventListener('input', function () {
            filterPuwerSetList(filterInput);
        });
    });

    document.querySelectorAll('.puwer-set-filter-clear').forEach(function (clearBtn) {
        clearBtn.addEventListener('click', function () {
            const input = document.getElementById(clearBtn.getAttribute('data-clear-filter'));
            if (!input) return;

            input.value = '';
            filterPuwerSetList(input);
            input.focus();
        });
    });

    const columns = document.querySelector('.puwer-set-columns');
    if (columns) {
        columns.addEventListener('click', function (event) {
            const addBtn = event.target.closest('.puwer-item-add');
            if (addBtn) {
                moveItem(addBtn.closest('.puwer-set-item-row'), 'puwerSelectedItems');
                return;
            }

            const removeBtn = event.target.closest('.puwer-item-remove');
            if (removeBtn) {
                moveItem(removeBtn.closest('.puwer-set-item-row'), 'puwerAvailableItems');
            }
        });
    }

    const saveBtn = document.getElementById('savePuwerSetBtn');
    if (saveBtn) {
        saveBtn.addEventListener('click', function () {
            postPuwerSet({
                FUNCTION: 'savePuwerSet',
                tenant: document.getElementById('puwerSetTenant').value,
                set_id: document.getElementById('puwerSetId').value,
                clientnumber: document.getElementById('puwerSetClientNumber').value,
                template_id: document.getElementById('puwerSetTemplateId').value,
                set_title: document.getElementById('puwerSetTitle').value,
                itemnumbers_json: JSON.stringify(getSelectedItemIds()),
                status: document.getElementById('puwerSetStatus').checked ? '1' : ''
            });
        });
    }

    const deleteBtn = document.getElementById('deletePuwerSetBtn');
    if (deleteBtn) {
        deleteBtn.addEventListener('click', function () {
            if (!confirm('Delete this PUWER set?')) return;

            postPuwerSet({
                FUNCTION: 'deletePuwerSet',
                tenant: document.getElementById('puwerSetTenant').value,
                set_id: document.getElementById('puwerSetId').value,
                clientnumber: document.getElementById('puwerSetClientNumber').value
            });
        });
    }

    updatePuwerCounts();
})();
</script>
