@using Berufsschule_HAM.Services
@using Microsoft.AspNetCore.Mvc.Localization
@using Berufsschule_HAM.Models
@model HomeIndexViewModel
@inject IViewLocalizer T
@inject LdapService ldap
@{
    ViewData["Title"] = T["Assets"];
    var adminSettingsModel = await ldap.GetAdminSettingsModelAsync();
    string barcodeType = adminSettingsModel.BarcodeType ?? "EAN13";
    string barcodeText = adminSettingsModel.BarcodeText ?? "HAM";
}
<link href="https://cdn.jsdelivr.net/npm/tom-select/dist/css/tom-select.bootstrap5.min.css" rel="preload" as="style" onload="this.onload=null;this.rel='stylesheet'"/>
<script src="/js/tom-select.min.js" defer></script>

<partial name="_BatchButton"/>

<div class="container py-4">
    <h2 class="mb-3">@T["Assets"]</h2>

    
    <div class="mb-4 d-flex flex-wrap gap-2">
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createAssetModal">
            @T["Create asset"]
        </button>
    </div>

    
    <div class="table-responsive">
        <table class="table table-striped align-middle">
            <thead>
                <tr>
                    <th>@T["Owner"]</th>
                    <th>@T["Asset ID"]</th>
                    <th>@T["Asset Name"]</th>
                    <th>@T["Location"]</th>
                    <th class="text-center">@T["Action"]</th>
                </tr>
                <tr>
                    <th><input type="text" class="form-control form-control-sm column-filter" placeholder="@T["Owner"]" data-column="0" /></th>
                    <th><input type="text" class="form-control form-control-sm column-filter" placeholder="@T["Asset ID"]" data-column="1" /></th>
                    <th><input type="text" class="form-control form-control-sm column-filter" placeholder="@T["Asset Name"]" data-column="2" /></th>
                    <th><input type="text" class="form-control form-control-sm column-filter" placeholder="@T["Location"]" data-column="3" /></th>
                    <th class="text-center">-</th>
                </tr>
            </thead>
            <tbody>
            @{
                foreach (AssetsTableViewModel assetsTableViewModel in Model.AssetsTableViewModels)
                {
                <tr class="asset-row" data-asset-id="@assetsTableViewModel.AssetCn">
                    <td>@assetsTableViewModel.UserUID</td>
                    <td>@assetsTableViewModel.AssetCn</td>
                    <td>@assetsTableViewModel.AssetName</td>
                    <td>@assetsTableViewModel.LocationName</td>
                    <td>
                        <div class="d-flex gap-2 justify-content-center">
                            <button class="btn btn-sm btn-warning btn-update"
                                data-asset-id="@assetsTableViewModel.AssetCn"
                                data-bs-toggle="modal"
                                data-bs-target="#updateAssetModal">
                                @T["Update"]
                            </button>
                            <button class="btn btn-sm btn-danger btn-delete" 
                                data-asset-id="@assetsTableViewModel.AssetCn"
                                data-bs-toggle="modal"
                                data-bs-target="#deleteModal">
                                @T["Delete"]
                            </button>
                        </div>
                    </td>
                </tr>
                }
            }
            </tbody>
        </table>
    </div>
</div>

<!-- Asset Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h3 class="modal-title" id="deleteModalLabel">@T["Confirm Delete"]</h3>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>@T["AssetDeleteConfirmation1"] <strong id="assetName"></strong> (ID: <span id="assetId"></span>)@T["AssetDeleteConfirmation2"]</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Cancel"]</button>
                <form id="deleteForm" method="post" action="">
                    <button type="submit" class="btn btn-danger">@T["Yes, Delete"]</button>
                </form>
            </div>
        </div>
    </div>
</div>


<script>
    document.addEventListener('DOMContentLoaded', () => {
        const deleteModal = document.getElementById('deleteModal');
        let currentButton = null; // The delete button that opened the modal

        deleteModal.addEventListener('show.bs.modal', event => {
            currentButton = event.relatedTarget; // Button that triggered the modal
            const assetId = currentButton.getAttribute('data-asset-id');
            const assetName = currentButton.getAttribute('data-asset-name');

            deleteModal.querySelector('#assetId').textContent = assetId;
            deleteModal.querySelector('#assetName').textContent = assetName;

            // Store the delete URL for later use
            deleteModal.querySelector('#deleteForm').dataset.url = `/Assets/Delete?cn=${assetId}`;
        });

        // Handle submit of deleteForm via fetch()
        const deleteForm = document.getElementById('deleteForm');
        deleteForm.addEventListener('submit', async e => {
            e.preventDefault();

            const url = deleteForm.dataset.url;
            const assetId = deleteModal.querySelector('#assetId').textContent;

            try {
                const response = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    }//,
                    //body: JSON.stringify({ id: assetId }) // Use this for Post requests with [FromBody] parameters like in /Groups/Update
                });

                const result = await response.json();

                if (result.success) {
                    // Close the modal
                    const modal = bootstrap.Modal.getInstance(deleteModal);
                    modal.hide();

                    // Remove the row from the table
                    const row = currentButton.closest('tr');
                    row.classList.add('table-danger');
                    setTimeout(() => row.remove(), 300);

                    showToast('@T["Asset deleted successfully"]', 'success');
                } else {
                    showToast(`${result.reason}: ${result.exception || '@T["Unknown error"]'}`, 'danger');
                }
            } catch (error) {
                console.error(error);
                showToast('@T["Error contacting server"]', 'danger');
            }
        });
    });
</script>

<!-- Asset Create Modal -->
<div class="modal fade" id="createAssetModal" tabindex="-1" aria-labelledby="createAssetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h3 class="modal-title" id="createAssetModalLabel">@T["Create asset"]</h3>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <form id="createAssetForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <!-- Basic Info -->
                        <div class="col-md-6">
                            <label class="form-label" for="createName">@T["Name"]</label>
                            <input type="text" class="form-control" id="createName" name="Name" />
                        </div>

                        <div class="col-md-6">
                            <label class="form-label" for="createLocationSelect">@T["Location"]</label>
                            <select class="form-select" name="Location" aria-label="@T["Location"]" id="createLocationSelect">
                                <option value="">@T["Select location"]</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createUsersSelect">@T["Owner"]</label>
                            <select class="form-select" name="Owner" aria-label="@T[name: "Owner"]" id="createUsersSelect">
                                <option value="">@T["Select owner"]</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createSerialNumber">@T["Serial Number"]</label>
                            <input type="text" class="form-control" id="createSerialNumber" name="SerialNumber" />
                        </div>

                        <hr class="my-3" />

                        <h4 class="fw-bold">@T["Preset"]</h4>
                        <div class="col-md-8">
                            <select class="form-select" name="Preset" aria-label="@T["Preset"]" id="createPresetSelect">
                                <option value="">@T["Select preset"]</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <button type="button" id="createPresetApply" class="btn btn-sm btn-warning">@T["Apply preset"]</button>
                        </div>

                        <hr class="my-3" />

                        <!-- Description Section -->
                        <h4 class="fw-bold">@T["Description"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="createType">@T["Type"]</label>
                            <input type="text" class="form-control" id="createType" name="Description.Type" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createMake">@T["Make"]</label>
                            <input type="text" class="form-control" id="createMake" name="Description.Make" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createModel">@T["Model"]</label>
                            <input type="text" class="form-control" id="createModel" name="Description.Model" />
                        </div>


                        <!-- Attributes Section -->
                        <div class="col-12 mt-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h4 class="fw-bold mb-0">@T["Attributes"]</h4>
                            </div>
                            <div id="attributesContainer" class="d-flex flex-column gap-2">
                                <!-- Dynamic attribute rows will appear here -->
                            </div>
                            <button type="button" class="btn btn-sm btn-primary mt-3" id="addAttributeBtn">
                                @T["Add Attribute"]
                            </button>
                        </div>

                        <hr class="my-3" />

                        <!-- Purchase Info -->
                        <h4 class="fw-bold">@T["Purchase Information"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="createPurchaseDate">@T["Purchase Date"]</label>
                            <input type="date" class="form-control" id="createPurchaseDate" name="Description.Purchase.PurchaseDate" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createPurchaseValue">@T["Purchase Value"]</label>
                            <input type="text" class="form-control" id="createPurchaseValue" name="Description.Purchase.PurchaseValue" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createPurchaseAt">@T["Purchased At"]</label>
                            <input type="text" class="form-control" id="createPurchaseAt" name="Description.Purchase.PurchaseAt" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="createPurchaseBy">@T["Purchased By"]</label>
                            <input type="text" class="form-control" id="createPurchaseBy" name="Description.Purchase.PurchaseBy" />
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Cancel"]</button>
                    <button type="submit" class="btn btn-primary">@T["Create"]</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script defer>
document.addEventListener('DOMContentLoaded', () => {
    });

    document.addEventListener('DOMContentLoaded', async () => {
        const createModal = document.getElementById('createAssetModal');
        createModal.addEventListener('show.bs.modal', async () => {
            const selectLocations = createModal.querySelector('#createLocationSelect');
            await loadLocationsIntoSelect(selectLocations);
            const selectPresets = createModal.querySelector('#createPresetSelect');
            await loadPresetsIntoSelect(selectPresets);        
            const selectUsers = createModal.querySelector('#createUsersSelect');
            await loadUsersIntoSelect(selectUsers);
        });
        // Open modal if URL contains parameter: CreateModal=true
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('CreateModal') === 'true') {
            const button = document.querySelector('[data-bs-toggle="modal"][data-bs-target="#createAssetModal"]');
            if (button) {
                button.click();
                urlParams.delete('CreateModal');
                const newUrl = window.location.pathname + '?' + urlParams.toString();
                history.replaceState({}, '', newUrl);
            }
        }
        const attributesContainer = document.getElementById('attributesContainer');
        const addAttributeBtn = document.getElementById('addAttributeBtn');

        addAttributeBtn.addEventListener('click', () => {
            const row = document.createElement('div');
            row.className = 'd-flex gap-2 align-items-center attribute-row';
            row.innerHTML = `
                <input type="text" class="form-control" placeholder="@T["Attribute name"]" data-attr-name />
                <input type="text" class="form-control" placeholder="@T["Attribute value"]" data-attr-value />
                <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
            `;
            attributesContainer.appendChild(row);
        });

        attributesContainer.addEventListener('click', (e) => {
            if (e.target.classList.contains('btn-remove-attribute')) {
                e.target.closest('.attribute-row').remove();
            }
        });

        const createForm = document.getElementById('createAssetForm');
        const originalHandler = createForm.onsubmit;
        createForm.addEventListener('submit', (e) => {
            const formData = new FormData(createForm);
            const jsonData = {};

            for (const [key, value] of formData.entries()) {
                if (!value) continue;
                const keys = key.split('.');
                let target = jsonData;
                for (let i = 0; i < keys.length - 1; i++) {
                    target[keys[i]] = target[keys[i]] || {};
                    target = target[keys[i]];
                }
                target[keys[keys.length - 1]] = value;
            }

            const attributes = {};
            document.querySelectorAll('#attributesContainer .attribute-row').forEach(row => {
                const name = row.querySelector('[data-attr-name]').value.trim();
                const value = row.querySelector('[data-attr-value]').value.trim();
                if (name) attributes[name] = value;
            });

            if (Object.keys(attributes).length > 0) {
                jsonData.Description = jsonData.Description || {};
                jsonData.Description.Attributes = attributes;
            }

            e.preventDefault();

            fetch('/Assets/Create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(jsonData)
            })
            .then(res => res.json())
            .then(result => {
                const createModalEl = document.getElementById('createAssetModal');
                if (result.success) {
                    bootstrap.Modal.getInstance(createModalEl).hide();
                    createForm.reset();
                    attributesContainer.innerHTML = '';
                    const tableBody = document.querySelector('table tbody');
                    if (tableBody) {
                        const newRow = document.createElement('tr');
                        newRow.innerHTML = `
                            <td>${jsonData.Owner || ''}</td>
                            <td>${result.assetId || ''}</td>
                            <td>${jsonData.Name || ''}</td>
                            <td>${jsonData.Location || ''}</td>
                            <td>
                                <div class="d-flex gap-2 justify-content-center">
                                    <button class="btn btn-sm btn-warning btn-update"
                                        data-asset-id="${result.assetId}"
                                        data-bs-toggle="modal"
                                        data-bs-target="#updateAssetModal">
                                        @T["Update"]
                                    </button>
                                    <button class="btn btn-sm btn-danger btn-delete"
                                        data-asset-id="${result.assetId}"
                                        data-asset-name="${jsonData.Name || ''}"
                                        data-bs-toggle="modal"
                                        data-bs-target="#deleteModal">
                                        @T["Delete"]
                                    </button>
                                </div>
                            </td>
                        `;

                        newRow.classList.add('asset-row');
                        newRow.classList.add('table-success');
                        newRow.setAttribute("data-asset-id", result.assetId);
                        registerRowDetailviewClick(newRow);
                        setTimeout(() => {
                            newRow.classList.toggle('table-success');
                        }, 500);
                        tableBody.append(newRow);
                    }
                    showToast('@T["Asset created successfully"]', 'success');
                } else {
                    showToast(`${result.reason || '@T["Error creating asset"]'}`, 'danger');
                }
            })
            .catch(err => {
                console.error(err);
                showToast('@T["Error contacting server"]', 'danger');
            });
        });
    });
</script>


<div class="modal fade" id="updateAssetModal" tabindex="-1" aria-labelledby="updateAssetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h3 class="modal-title" id="updateAssetModalLabel">@T["Update Asset"]</h3>
                <button type="button" class="btn-close" style="filter: invert(0);" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <form id="updateAssetForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label" for="updateName">@T["Name"]</label>
                            <input type="text" class="form-control" id="updateName" name="Name" />
                        </div>

                        <div class="col-md-6">
                            <label class="form-label" for="updateLocationSelect">@T["Location"]</label>
                            <select class="form-select" name="Location" aria-label="@T["Location"]" id="updateLocationSelect">
                                <option value="">@T["Select location"]</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateUsersSelect">@T["Owner"]</label>
                            <select class="form-select" name="Owner" aria-label="@T["Owner"]" id="updateUsersSelect">
                                <option value="">@T["Select owner"]</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateSerialNumber">@T["Serial Number"]</label>
                            <input type="text" class="form-control" id="updateSerialNumber" name="SerialNumber" />
                        </div>

                        <hr class="my-3" />

                        <h4 class="fw-bold">@T["Description"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="updateType">@T["Type"]</label>
                            <input type="text" class="form-control" id="updateType" name="Description.Type" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateMake">@T["Make"]</label>
                            <input type="text" class="form-control" id="updateMake" name="Description.Make" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updateModel">@T["Model"]</label>
                            <input type="text" class="form-control" id="updateModel" name="Description.Model" />
                        </div>

                        <div class="col-12 mt-3">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <h4 class="fw-bold mb-0">@T["Attributes"]</h4>
                            </div>
                            <div id="updateAttributesContainer" class="d-flex flex-column gap-2"></div>
                            <button type="button" class="btn btn-sm btn-primary mt-3" id="updateAddAttributeBtn">
                                @T["Add Attribute"]
                            </button>
                        </div>

                        <hr class="my-3" />

                        <h4 class="fw-bold">@T["Purchase Information"]</h4>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseDate">@T["Purchase Date"]</label>
                            <input type="date" class="form-control" id="updatePurchaseDate" name="Description.Purchase.PurchaseDate" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseValue">@T["Purchase Value"]</label>
                            <input type="text" class="form-control" id="updatePurchaseValue" name="Description.Purchase.PurchaseValue" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseAt">@T["Purchased At"]</label>
                            <input type="text" class="form-control" id="updatePurchaseAt" name="Description.Purchase.PurchaseAt" />
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="updatePurchaseBy">@T["Purchased By"]</label>
                            <input type="text" class="form-control" id="updatePurchaseBy" name="Description.Purchase.PurchaseBy" />
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Cancel"]</button>
                    <button type="submit" class="btn btn-warning">@T["Save Changes"]</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const updateButtons = document.querySelectorAll('.btn-update');
    const updateModal = document.getElementById('updateAssetModal');
    const updateForm = document.getElementById('updateAssetForm');
    const updateAttributesContainer = document.getElementById('updateAttributesContainer');
    const addAttrBtn = document.getElementById('updateAddAttributeBtn');
    let assetId = null;

    addAttrBtn.addEventListener('click', () => {
        const row = document.createElement('div');
        row.className = 'd-flex gap-2 align-items-center attribute-row';
        row.innerHTML = `
            <input type="text" class="form-control" placeholder="@T["Attribute name"]" aria-label="@T["Attribute name"]" data-attr-name />
            <input type="text" class="form-control" placeholder="@T["Attribute value"]" aria-label="@T["Attribute value"]" data-attr-value />
            <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
        `;
        updateAttributesContainer.appendChild(row);
    });

    updateAttributesContainer.addEventListener('click', e => {
        if (e.target.classList.contains('btn-remove-attribute')) {
            e.target.closest('.attribute-row').remove();
        }
    });

    updateModal.addEventListener('show.bs.modal', async event => {
        const button = event.relatedTarget;
        assetId = button.getAttribute('data-asset-id');

        updateAttributesContainer.innerHTML = '';
        updateForm.reset();
        try {
            const response = await fetch(`/Assets/Get?cn=${assetId}`);
            const responseJson = await response.json();
            const asset = responseJson.assetsModel;
            
            const locationSelect = updateForm.querySelector('#updateLocationSelect');
            const usersSelect = updateForm.querySelector('#updateUsersSelect');
            await Promise.all([
                loadLocationsIntoSelect(locationSelect, asset.Location),
                loadUsersIntoSelect(usersSelect, asset.Owner)
            ]);

            for (const [key, value] of Object.entries(asset)) {
                const input = updateForm.querySelector(`[name="${key}"]`);
                if (input) input.value = value;
            }

            // Handle nested description fields
            if (asset.Description) {
                for (const [descKey, descVal] of Object.entries(asset.Description)) {
                    const field = updateForm.querySelector(`[name="Description.${descKey}"]`);
                    if (field && typeof descVal === 'string') field.value = descVal;
                }

                // Attributes
                if (asset.Description.Attributes) {
                    for (const [attrName, attrValue] of Object.entries(asset.Description.Attributes)) {
                        const row = document.createElement('div');
                        row.className = 'd-flex gap-2 align-items-center attribute-row';
                        row.innerHTML = `
                            <input type="text" class="form-control" value="${attrName}" aria-label="@T["Attribute name"]" data-attr-name />
                            <input type="text" class="form-control" value="${attrValue}" aria-label="@T["Attribute value"]" data-attr-value />
                            <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
                        `;
                        updateAttributesContainer.appendChild(row);
                    }
                }

                // Purchase info
                if (asset.Description.Purchase) {
                    for (const [pKey, pValue] of Object.entries(asset.Description.Purchase)) {
                        const field = updateForm.querySelector(`[name="Description.Purchase.${pKey}"]`);
                        if (field) field.value = pValue;
                    }
                }
            }
        } catch (err) {
            console.error(err);
            showToast('@T["Error loading asset data"]', 'danger');
        }
    });

    updateForm.addEventListener('submit', async e => {
        e.preventDefault();

        const formData = new FormData(updateForm);
        const jsonData = {"Cn": assetId};
        for (const [key, value] of formData.entries()) {
            if (!value) continue;
            const keys = key.split('.');
            let target = jsonData;
            for (let i = 0; i < keys.length - 1; i++) {
                target[keys[i]] = target[keys[i]] || {};
                target = target[keys[i]];
            }
            target[keys[keys.length - 1]] = value;
        }

        const attributes = {};
        document.querySelectorAll('#updateAttributesContainer .attribute-row').forEach(row => {
            const name = row.querySelector('[data-attr-name]').value.trim();
            const value = row.querySelector('[data-attr-value]').value.trim();
            if (name) attributes[name] = value;
        });

        if (Object.keys(attributes).length > 0) {
            jsonData.Description = jsonData.Description || {};
            jsonData.Description.Attributes = attributes;
        }

        try {
            const response = await fetch('/Assets/Update', {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
                body: JSON.stringify(jsonData)
            });
            const result = await response.json();

            if (result.success) {
                bootstrap.Modal.getInstance(updateModal).hide();
                showToast('@T["Asset updated successfully"]', 'success');

                const row = [...document.querySelectorAll('tr')]
                    .find(r => r.querySelector(`[data-asset-id="${jsonData.Cn}"]`));
                if (row) {
                    row.children[0].textContent = jsonData.Owner || '';
                    row.children[1].textContent = jsonData.Cn || '';
                    row.children[2].textContent = jsonData.Name || '';
                    row.children[3].textContent = jsonData.Location || '';
                }
            } else {
                showToast(result.reason || '@T["Error updating asset"]', 'danger');
            }
        } catch (err) {
            console.error(err);
            showToast('@T["Error contacting server"]', 'danger');
        }
    });
});
</script>

<!-- Detail view -->
<div class="modal fade" id="viewAssetModal" tabindex="-1" aria-labelledby="viewAssetModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-info text-dark">
                <h3 class="modal-title" id="viewAssetModalLabel">@T["Asset Details"]</h3>
                <button type="button" class="btn-close btn-close-white" style="filter: invert(0);" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div id="viewAssetContent">
                    <p class="text-center text-muted">@T["Loading..."]</p>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">@T["Close"]</button>
            </div>
        </div>
    </div>
</div>

<style>
.asset-row > td:not(:last-child) {
    cursor: pointer;
}
.asset-row > td {    
    transition: 0.1s ease;
}
.asset-row:has(td:not(:last-child):hover) > td {
    background-color: #17a2b8;
}
</style>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js" defer></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const rows = document.querySelectorAll('.asset-row');
    rows.forEach(row => registerRowDetailviewClick(row));
});

function registerRowDetailviewClick(row) {
    const viewModal = document.getElementById('viewAssetModal');
    const viewContent = document.getElementById('viewAssetContent');
    row.addEventListener('click', async (e) => {
        // Avoid clicks on buttons inside the row
        if (e.target.closest('button')) return;

        const assetId = row.getAttribute('data-asset-id');
        viewContent.innerHTML = '<p class="text-center text-muted">@T["Loading..."]</p>';

        const modal = new bootstrap.Modal(viewModal);
        modal.show();

        try {
            const response = await fetch(`/Assets/Get?cn=${assetId}`);
            const json = await response.json();
            const asset = json.assetsModel;

            if (!asset) {
                viewContent.innerHTML = `<p class="text-danger text-center">@T["Asset not found."]</p>`;
                return;
            }

            const html = `
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Barcode"]</h4>
                    <div class="col-md-6">
                        <svg id="@barcodeType" class="form-control" name="Barcode" />
                    </div>
                    <div class="col-md-6">
                        <button id="downloadBtn" class="form-control my-2 btn btn-primary">@T["Download Barcode"]</button>
                        <button id="printBtn" class="form-control my-2 btn btn-primary">@T["Add Barcode to print batch"]</button>
                    </div>
                </div>
                <hr class="my-3" />
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Inventory"]</h4>
                    <div class="col-md-6">
                        <label class="form-label">@T["Name"]</label>
                        <input type="text" class="form-control" name="Name" value="${asset.Description.Inventory.PersonUid || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Date"]</label>
                        <input type="text" class="form-control" name="Name" value="${new Intl.DateTimeFormat('de-DE', {year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit"}).format(new Date(asset.Description.Inventory.Date)) || ''}" disabled />
                    </div>
                </div>
                <hr class="my-3" />
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Information"]</h4>
                    <div class="col-md-6">
                        <label class="form-label">@T["Name"]</label>
                        <input type="text" class="form-control" name="Name" value="${asset.Name || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Location"]</label>
                        <input type="text" class="form-control" name="Location" value="${asset.Location || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Owner"]</label>
                        <input type="text" class="form-control" name="Owner" value="${asset.Owner || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Serial Number"]</label>
                        <input type="text" class="form-control" name="SerialNumber" value="${asset.SerialNumber || ''}" disabled />
                    </div>
                </div>
                <hr class="my-3" />
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Description"]</h4>
                    <div class="col-md-6">
                        <label class="form-label">@T["Type"]</label>
                        <input type="text" class="form-control" name="Description.Type" value="${asset.Description?.Type || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Make"]</label>
                        <input type="text" class="form-control" name="Description.Make" value="${asset.Description?.Make || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Model"]</label>
                        <input type="text" class="form-control" name="Description.Model" value="${asset.Description?.Model || ''}" disabled />
                    </div>
                </div>
                ${asset.Description?.Attributes ? `
                <hr class="my-3" />
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Attributes"]</h4>
                        ${Object.entries(asset.Description.Attributes)
                            .map(([k,v]) => `
                            <div class="d-flex gap-2 align-items-center attribute-row">
                                <input type="text" class="form-control w-50" placeholder="@T["Attribute name"]" data-attr-name disabled value="${k}" />:
                                <input type="text" class="form-control" placeholder="@T["Attribute value"]" data-attr-value disabled value="${v}" />
                            </div>`)
                            .join('')}
                    </div>` : ''}
                            
                ${asset.Description?.Purchase ? `
                <hr class="my-3" />
                <div class="row g-3">
                    <h4 class="fw-bold">@T["Purchase Information"]</h4>
                    <div class="col-md-6">
                        <label class="form-label">@T["Purchase Date"]</label>
                        <input type="date" class="form-control" name="Description.Purchase.PurchaseDate" value="${asset.Description.Purchase.PurchaseDate || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Purchase Value"]</label>
                        <input type="text" class="form-control" name="Description.Purchase.PurchaseValue" value="${asset.Description.Purchase.PurchaseValue || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Purchased At"]</label>
                        <input type="text" class="form-control" name="Description.Purchase.PurchaseAt" value="${asset.Description.Purchase.PurchaseAt || ''}" disabled />
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">@T["Purchased By"]</label>
                        <input type="text" class="form-control" name="Description.Purchase.PurchaseBy" value="${asset.Description.Purchase.PurchaseBy || ''}" disabled />
                    </div>
                </div>` : ''}
            </div>`;
            viewContent.innerHTML = html;
            JsBarcode("#@barcodeType", getBarcodeValue("@barcodeType", asset.Cn), {
                format: "@barcodeType",
                lineColor: "#000",
                width: 2,
                height: 80,
                displayValue: true
            });
            document.getElementById("downloadBtn").addEventListener("click", () => {
                downloadBarcode("@barcodeType", getBarcodeValue("@barcodeType", asset.Cn));                    
            });
            document.getElementById("printBtn").addEventListener("click", () => {
                addAssetIdToBatch(asset.Cn);
                showToast("@T["Successfully added barcode to print batch"]", "success");
                bootstrap.Modal.getInstance('#viewAssetModal').hide();
            });
        } catch (err) {
            console.error(err);
            viewContent.innerHTML = `<p class="text-danger text-center">@T["Error loading asset details"]</p>`;
        }
    });
}


document.addEventListener('DOMContentLoaded', () => {
    const presetApplyButton = document.getElementById('createPresetApply');
    presetApplyButton.addEventListener('click', async () => {
        const response = await fetch('/Settings/Presets');
        const responseJson = await response.json();
        const presetSelect = document.getElementById('createPresetSelect');
        const presetSelectValue = presetSelect.value;
        if (responseJson[presetSelectValue]) {
            const attributesContainer = document.getElementById('attributesContainer');
            var attributes = responseJson[presetSelectValue].attribute;
            for (var attributeKey in attributes) {
                var attributeValue = attributes[attributeKey];
                if (attributeKey == "Type" || attributeKey == "@T["Type"]") {
                    document.getElementById("createType").setAttribute("value", attributeValue);
                } else if (attributeKey == "Make" || attributeKey == "@T["Make"]") {
                    document.getElementById("createMake").setAttribute("value", attributeValue);
                } else if (attributeKey == "Model" || attributeKey == "@T["Model"]") {
                    document.getElementById("createModel").setAttribute("value", attributeValue);
                } else if (attributeKey == "Purchase Date" || attributeKey == "@T["Purchase Date"]") {
                    document.getElementById("createPurchaseDate").setAttribute("value", attributeValue);
                } else if (attributeKey == "Purchase Value" || attributeKey == "@T["Purchase Value"]") {
                    document.getElementById("createPurchaseValue").setAttribute("value", attributeValue);
                } else if (attributeKey == "Purchased At" || attributeKey == "@T["Purchased At"]") {
                    document.getElementById("createPurchaseAt").setAttribute("value", attributeValue);
                } else if (attributeKey == "Purchased By" || attributeKey == "@T["Purchased By"]") {
                    document.getElementById("createPurchaseBy").setAttribute("value", attributeValue);
                } else if (attributeKey == "Location" || attributeKey == "@T["Location"]") {
                    document.getElementById("createLocationSelect-ts-control").value = attributeValue;
                    document.getElementById("createLocationSelect").value = attributeValue;
                } else if (attributeKey == "User" || attributeKey == "@T["User"]") {
                    document.getElementById("createUsersSelect-ts-control").value = attributeValue;
                    document.getElementById("createUsersSelect").value = attributeValue;
                } else if (attributeKey == "Name" || attributeKey == "@T["Name"]") {
                    document.getElementById("createName").value = attributeValue;
                } else if (attributeKey == "Serial Number" || attributeKey == "@T["Serial Number"]") {
                    document.getElementById("createSerialNumber").value = attributeValue;
                } else {
                    var nameInputs = attributesContainer.querySelectorAll("input[data-attr-name]");
                    var anyEquals = false;
                    var anyEqualsElement = null;
                    nameInputs.forEach(element => {
                        if (element.value == attributeKey) {
                            anyEquals = true;
                            anyEqualsElement = element.nextElementSibling;
                            return;
                        }
                    });
                    if (anyEquals) {
                        anyEqualsElement.value = attributeValue;
                    } else {
                        const row = document.createElement('div');
                        row.className = 'd-flex gap-2 align-items-center attribute-row';
                        row.innerHTML = `
                            <input type="text" class="form-control" placeholder="@T["Attribute name"]" data-attr-name value="${attributeKey}" />
                            <input type="text" class="form-control" placeholder="@T["Attribute value"]" data-attr-value value="${attributeValue}" />
                            <button type="button" class="btn btn-danger btn-sm btn-remove-attribute">@T["Remove"]</button>
                        `;
                        attributesContainer.appendChild(row);
                    }
                }
            }
        }
    });
});
</script>
<!-- TomSelect dropdowns -->
<script>
    // Locations dropdowns
    document.addEventListener('DOMContentLoaded', () => {
        const createLocationSelect = document.getElementById('createLocationSelect');
        const updateLocationSelect = document.getElementById('updateLocationSelect');

        async function initLocationSelect(selectElement) {
            if (!selectElement) return;
            await loadLocationsIntoSelect(selectElement);
            new TomSelect(selectElement, {
                plugins: ['clear_button'],
                create: false,
                sortField: { field: 'text', direction: 'asc' },
                placeholder: '@T["Select location"]',
                maxOptions: 500, // avoid performance hit if there are many
                render: {
                    no_results: function(data, escape) {
                        return `<div class="no-results">@T["No locations found"]</div>`;
                    }
                }
            });
        }

        initLocationSelect(createLocationSelect);
        initLocationSelect(updateLocationSelect);
        
        // Users dropdowns
        const createUsersSelect = document.getElementById('createUsersSelect');
        const updateUsersSelect = document.getElementById('updateUsersSelect');

        async function initUsersSelect(selectElement) {
            if (!selectElement) return;
            await loadUsersIntoSelect(selectElement);
            new TomSelect(selectElement, {
                plugins: ['clear_button'],
                create: false,
                sortField: { field: 'text', direction: 'asc' },
                placeholder: '@T["Select user"]',
                maxOptions: 500, // avoid performance hit if there are many
                render: {
                    no_results: function(data, escape) {
                        return `<div class="no-results">@T["No users found"]</div>`;
                    }
                }
            });
        }

        initUsersSelect(createUsersSelect);
        initUsersSelect(updateUsersSelect);

        const createPresetsSelect = document.getElementById('createPresetsSelect');

        async function initPresetsSelect(selectElement) {
            if (!selectElement) return;
            await loadPresetsIntoSelect(selectElement);
            new TomSelect(selectElement, {
                plugins: ['clear_button'],
                create: false,
                sortField: { field: 'text', direction: 'asc' },
                placeholder: '@T["Select preset"]',
                maxOptions: 500, // avoid performance hit if there are many
                render: {
                    no_results: function(data, escape) {
                        return `<div class="no-results">@T["No presets found"]</div>`;
                    }
                }
            });
        }

        initPresetsSelect(createPresetsSelect);

    });

</script>


<partial name="_Batch"/>