<link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css" />
<script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

@section('styles')
    <style>
        /* Main table styling - no scrolling */
        #operatorsSummaryTable_wrapper {
            overflow: hidden !important;
        }

        /* Operator display container */
        .operators-main-display {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            padding: 8px 0;
        }

        /* Individual operator badge */
        .operator-badge {
            background: #f0f0f0;
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 0.85rem;
            white-space: nowrap;
            margin-right: 5px;
        }

        /* "More" dropdown trigger */
        .more-operators-btn {
            background: #e0e0e0;
            border: none;
            padding: 4px 8px;
            border-radius: 12px;
            cursor: pointer;
            font-size: 0.85rem;
        }

        /* Dropdown container */
        .operators-dropdown {
            position: absolute;
            background: white;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 8px;
            /* box-shadow: 0 4px 8px rgba(0,0,0,0.1); */
            /* z-index: 100; */
            /* width: calc(100% - 24px); */
            left: 12px;
            display: none;
            flex-wrap: wrap;
            gap: 8px;
            max-height: none;
        }

        /* Row details container */
        .row-details {
            padding: 12px;
            background: #f9f9f9;
            border-top: 1px solid #eee;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .operators-main-display {
                flex-direction: column;
            }
        }
    </style>
@endsection

<div class="modal fade" id="viewOperatorsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assigned Operators</h5>
                <button type="button" class="btn-close" data-dismiss="modal"><span>×</span></button>
            </div>
            <div class="modal-body p-3">
                <div class="table-container" style="overflow:hidden">
                    <table class="table table-bordered" id="operatorsSummaryTable" width="100%">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 60px;">Sl No</th>
                                <th>Machine Name</th>
                                <th>Assigned Operators</th>
                                <th style="width: 120px;">Actions</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

@section('viewoperators_scripts')
    <script>
        $(function() {
            $('[data-toggle="tooltip"]').tooltip();
        });

        let operatorDataCache = [];

        const operatorsSummaryTableInstance = $('#operatorsSummaryTable').DataTable({
            responsive: true,
            scrollX: false,
            autoWidth: false,
            columnDefs: [
                {
                    targets: 0,
                    className: 'control',
                    orderable: false,
                    render: function(data, type, row, meta) {
                        return type === 'display' ?
                            `<span>${meta.row + 1}</span>
                            <i class="fas toggle-row-details ms-2 fa-chevron-down" data-row-index="${meta.row}"></i>` :
                            meta.row + 1;
                    }
                }
            ],
            order: [
                [1, 'asc']
            ]
        });

        // Handle dropdown arrow clicks
        $(document).on('click', '.toggle-row-details', function() {
            const rowIndex = $(this).data('row-index');
            const row = operatorsSummaryTableInstance.row(rowIndex);
            const brow = operatorsSummaryTableInstance.backdata[rowIndex];
            const $icon = $(this);
            if (row.child.isShown()) {
                row.child.hide();
                $icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
            } else {
                //const rowData = row.data();
                const detailsContent = `
                    <div class="row-details">
                        <h6>Operator Details</h6>
                        ${formatOperators(brow.operators.map(v=>v.name),0)}
                    </div>
                `;
                row.child(detailsContent).show();
                $icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
            }
        });

        // Handle "more operators" button
        $(document).on('click', '.more-operators-btn', function(e) {
            e.stopPropagation();
            $(this).next('.operators-dropdown').toggle();
        });

        // Close dropdown when clicking elsewhere
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.more-operators-btn, .operators-dropdown').length) {
                $('.operators-dropdown').hide();
            }
        });

        // EDIT OPERATOR FUNCTIONALITY
        const machineModel = new bootstrap.Modal(document.getElementById('machineModel'));
        $(document).on('click', '.edit-operator-btn', function() {
            const machineId = $(this).data('machine');
            const operators = $(this).data('operators').toString().split(',').map(Number);
            machineModel.show();
            document.querySelector("#viewOperatorsModal .btn-close").click();
            $('#machineSelect').val(machineId);
            $('#operatorSelect').val(operators);
            $('#machineSelect,#operatorSelect').selectpicker('refresh');
        });

        // DELETE OPERATOR FUNCTIONALITY
        $(document).on('click', '.delete-operator-btn', function() {
            const machineId = $(this).data('machine');
            if (confirm(`Are you sure to remove all operators?`)) {
                fetch(`{{ route('superadmin.machine.dismissAssignment') }}/${machineId}`, {
                        method: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': "{{ csrf_token() }}"
                        }
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.success) {
                            document.querySelector("#viewOperatorsModal .btn-close").click();
                            operatorsSummaryTableInstance.ajax.reload(); // Refresh table
                        } else {
                            alert('Error: ' + data.message);
                        }
                    });
            }
        });

        // Load data when modal opens
        $('#viewOperatorsModal').on('show.bs.modal', function() {
            fetch("{{ route('superadmin.process.viewOperatorsSummary') }}")
                .then(res => res.json())
                .then(data => {
                    operatorDataCache = data.data;
                    operatorsSummaryTableInstance.clear();
                    operatorsSummaryTableInstance.backdata = {}
                    data.data.forEach((row, index) => {
                        operatorsSummaryTableInstance.backdata[index] = row;
                        operatorsSummaryTableInstance.row.add([
                            index + 1,
                            row.machine_name,
                            formatOperators(row.operators.map(v => v.name), 3), `
                        <div class="text-end">
                            <button class="btn btn-info btn-sm edit-operator-btn" 
                                data-machine="${row.id}" 
                                data-operators="${row.operators.map(v => v.id).join(', ')}">
                                <i class="fa fa-edit"></i>
                            </button>
                            <button class="btn btn-danger btn-sm delete-operator-btn" 
                                data-machine="${row.id}">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                        `
                        ]);
                    });
                    operatorsSummaryTableInstance.draw();
                })
                .catch(err => {
                    console.error("Error loading operator summary:", err);
                    alert("Failed to load data.");
                });
        });
    </script>
@endsection
