@{
    var workersList = ViewBag.Workers;
    var _isMobile = Request.Browser.IsMobileDevice;
}

<div class="modal" id="add-workers-modal" role="dialog" aria-hidden="true">
    <div class="modal-dialog" style="@(_isMobile ? "width: 100%; margin: 10px auto;" : "width: 50%")">
        <div class="modal-content">
            <div class="modal-header">
                <div class="row" style="padding:0px 15px">
                    <div>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h3>@Loc.AddWorker</h3>
                    </div>

                    @* Workers list *@
                    <div class="daily-plan-workers">
                        @if (workersList != null)
                        {
                            for (var i = 0; i < workersList.Count; i++)
                            {
                                var worker = workersList[i];
                                <div id="worker_@i" class="worker-item">
                                    @if (!string.IsNullOrWhiteSpace(worker.Icon))
                                    {
                                        <img class="map-round-icon" src="@worker.Icon" style="margin-right: 10px;" />
                                    }
                                    else
                                    {
                                        <i class="fal fa-user-circle fa-3x text-muted" style="opacity:0.5; margin-right: 10px;"></i>
                                    }
                                    <label class="control-label">@worker.Worker</label>
                                </div>
                            }
                        }
                    </div>

                    <br />
                    <button type="button" id="submit-btn" class="btn btn-primary pull-right @(_isMobile ? "btn-rounded" : string.Empty)">
                        <i class="fa fa-check m-r-xs" id="submit-btn-icon"></i>@Loc.Confirm
                    </button>
                    <button type="button" data-dismiss="modal" class="btn btn-link pull-right @(_isMobile ? "btn-rounded" : string.Empty)">
                        <i class="fa fa-times m-r-xs text-primary"></i>@Loc.Cancel
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var selectedWorkerNames = [];
    var AWMDate;
    var AWMAnNo;
    var AWMSelectedRow;
    var AWMSelectedDate;
    var AWMSelectedAcKey;
    var AWMSelectedWoExQId;
    var AWMSelectedItemQId;
    var AWMSelectedItemResourceQId;

    $(document).ready(function () {

        $('#add-workers-modal').on('shown.bs.modal', function () {
            $('.daily-plan-workers').scrollTop(0);
            getSelectedWorkers();
        });

        $('.daily-plan-workers').on('click', '.worker-item', function () {
            let workerName = $(this).text().trim();
            $(this).toggleClass('worker-item-selected');
            toggleWorkerSelection(workerName);
        });

        $('#submit-btn').click(function () {
            saveWorkers();
        });

        $('#add-workers-modal').on('hidden.bs.modal', function () {
            clearSelections();
        });
    });

    function getSelectedWorkers() {
        $.ajax({
            url: '@Url.Action("GetDailyPlanWorkers", "Manufacturing")',
            type: 'POST',
            async: false,
            data: {
                filterModel: {
                    Key: AWMSelectedAcKey,
                    No: AWMSelectedItemQId
                }
            },
            success: function (response) {
                response.forEach(function (worker) {
                    $('.worker-item').each(function () {
                        if ($(this).text().trim() === worker) {
                            $(this).addClass('worker-item-selected');
                            selectedWorkerNames.push(worker);
                        }
                    });
                });
            }
        });
    }

    function toggleWorkerSelection(workerName) {
        let index = selectedWorkerNames.indexOf(workerName);

        if (index !== -1) {
            selectedWorkerNames.splice(index, 1);
        } else {
            selectedWorkerNames.push(workerName);
        }
    }

    function clearSelections() {
        $('.worker-item-selected').removeClass('worker-item-selected');
        selectedWorkerNames = [];
        AWMDate = null;
        AWMAnNo = null;
        AWMSelectedRow = null;
        AWMSelectedDate = null;
        AWMSelectedAcKey = null;
        AWMSelectedWoExQId = null;
        AWMSelectedItemQId = null;
        AWMSelectedItemResourceQId = null;
    }

    function saveWorkers() {
        var formData = new FormData();
        selectedWorkerNames.forEach(function (workerName) {
            formData.append('workers[]', workerName);
        });
        formData.append('date', AWMSelectedDate);
        formData.append('woExQId', AWMSelectedWoExQId);
        formData.append('woExItemQId', AWMSelectedItemQId);
        formData.append('woExItemResourceQId', AWMSelectedItemResourceQId);

        $.ajax({
            cache: false,
            type: "POST",
            url: '@Url.Action("SaveDailyPlanWorkersByAcKey", "Manufacturing")',
            processData: false,
            contentType: false,
            data: formData,
            success: function (response) {
                if (response.Status) {
                    renderWorkerIcons(AWMSelectedAcKey, AWMSelectedItemQId, AWMSelectedItemResourceQId, AWMSelectedWoExQId, AWMDate, AWMAnNo, AWMSelectedRow);
                } else {
                    $().customModal({
                        destroyOnClose: true,
                        showCloseButton: true,
                        type: "error",
                        text:  '@Loc.ErrorSaving',
                        buttons: [
                            {
                                icon: 'fa fa-check',
                                text: '@Loc.OK',
                                closeOnAction: true,
                                type: 'primary'
                            }
                        ]
                    });
                }

                $('#add-workers-modal').modal('hide');
            },
            error: function (error) {
                console.error(error);
            }
        });
    }

    function renderWorkerIcons(acKey, itemQId, itemResourceQId, woExQId, date, anNo, selectedRowId) {
        $.ajax({
            url: '@Url.Action("GetDailyPlanWorkers", "Manufacturing")',
            type: 'POST',
            async: false,
            data: {
                filterModel: {
                    Key: acKey,
                    No: itemQId
                }
            },
            success: function (response) {
                let workerIcons = getWorkerIcons(response, acKey, woExQId, itemQId, itemResourceQId, date, anNo);
                $('#' + selectedRowId).find('#operWorker').html(workerIcons);

                if (openInfoWindow) {
                    $('#infoWindowWorkers').html(workerIcons);
                }
            }
        });
    }
</script>
