<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-tasks mr-2"></i> Process Details
        </h6>
        <button type="button" id="addProcess" class="btn btn-light btn-sm">
            <i class="fas fa-plus mr-1"></i> Add Process
        </button>
    </div>
    <div class="card-body" id="route_card_process_list">
        <div class="table-responsive">
            <table id="processTable" class="table table-bordered table-striped table-sm" width="100%">
                <thead class="thead-light">
                    <tr>
                        <th width="50">Sl No</th>
                        <th>Process</th>
                        <th>Source</th>
                        <th>Previous Process</th>
                        <th>Machine</th>
                        <th>Operator</th>
                        <th>Cycle Time</th>
                        <th>Status</th>
                        <th>Start Date</th>
                        <th>End Date</th>
                        <th>Description</th>
                        <th width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($routeCardProcesses as $routeCardProcess)
                        <tr id="row-{{ $routeCardProcess->id }}">
                            <td>{{ $loop->iteration }}</td>
                            <td>{{ $routeCardProcess->process ?? '-' }}</td>
                            <td style="text-transform: capitalize;">{{ $routeCardProcess->source ?? '-' }}</td>
                            <td>{{ $routeCardProcess->previousProcess->process ?? '-' }}</td>
                            <td>
                                @if($routeCardProcess->attchedMachine)
                                    [{{ $routeCardProcess->attchedMachine->machine_id }}] {{ $routeCardProcess->attchedMachine->machine_name }}
                                @else
                                    -
                                @endif
                            </td>
                            <td>{{ $routeCardProcess->attchedOperator->name ?? '-' }}</td>
                            <td>{{ str_pad($routeCardProcess->cycle_hours ?? 0, 2, '0', STR_PAD_LEFT) }}:{{ str_pad($routeCardProcess->cycle_minutes ?? 0, 2, '0', STR_PAD_LEFT) }}</td>
                            <td>
                                @if($routeCardProcess->status == 'completed')
                                    <span class="badge badge-success">Completed</span>
                                @elseif($routeCardProcess->status == 'in_progress')
                                    <span class="badge badge-warning">In Progress</span>
                                @else
                                    <span class="badge badge-secondary">{{ ucfirst($routeCardProcess->status ?? 'Pending') }}</span>
                                @endif
                            </td>
                            <td>{{ $routeCardProcess->start_date ? \Carbon\Carbon::parse($routeCardProcess->start_date)->format('d M Y H:i') : '-' }}</td>
                            <td>{{ $routeCardProcess->end_date ? \Carbon\Carbon::parse($routeCardProcess->end_date)->format('d M Y H:i') : '-' }}</td>
                            <td>{{ $routeCardProcess->description ?? '-' }}</td>
                            <td class="text-center" style="white-space: nowrap;">
                                <button type="button" class="btn btn-warning btn-sm editProcess" data-edit="{{ json_encode($routeCardProcess) }}" title="Edit">
                                    <i class="fa fa-edit"></i>
                                </button>
                                <form method="POST" action="{{ route('superadmin.routecard.process.delete', $routeCardProcess->id) }}" class="removeProcessForm d-inline">
                                    @csrf
                                    @method('DELETE')
                                    <input type="hidden" name="route_card_id" value="{{ $routeCardId }}" />
                                    <button type="submit" class="btn btn-danger btn-sm removeProcess" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const processModal = new bootstrap.Modal(document.querySelector("#routeFormProcessModal"));
    document.querySelector("#routeFormProcessModal").modal = processModal;

    const processTableInstance = $('#processTable').DataTable({
        responsive: true,
        autoWidth: false,
        destroy: true,
        paging: false,
        searching: false,
        info: false,
        ordering: false,
        columnDefs: [
            { orderable: false, targets: -1 },
            { className: 'align-middle', targets: '_all' }
        ],
        language: {
            emptyTable: "No processes added yet. Click 'Add Process' to get started."
        }
    });

    setTimeout(() => {
        $("#processTable .editProcess").on('click', function(event) {
            let row = JSON.parse(event.currentTarget.dataset.edit);
            $("#routeFormProcessModal").data('mode', 'edit');
            $("#routeFormProcessModal").data('data', row);
            processModal.show();
        });
    }, 500);

    $('#addProcess').on('click', function() {
        $("#routeFormProcessForm")[0].reset();
        $("#routeFormProcessModal").data('mode', 'add');
        let previousProcessData = processTableInstance.rows().data().toArray();
        let previousProcess = previousProcessData.length > 0 ? previousProcessData[previousProcessData.length - 1] : null;
        console.log('Previous Process:', previousProcess);
        let processIndex = processTableInstance.rows().count() + 1;
        processModal.show();
    });

    $("#processTable").on("change", "[data-source]", function() {
        const processIndex = $(this).data('index');
        const value = $(this).val();
        const machineSelect = $(`#processTable [name=machine_id\\[\\]][data-index=${processIndex}]`);
        const operatorSelect = $(`#processTable [name=operator_id\\[\\]][data-index=${processIndex}]`);
        if (value === 'outsourced') {
            machineSelect.attr('disabled', true).val('');
            operatorSelect.attr('disabled', true).val('');
        } else {
            machineSelect.removeAttr('disabled');
            operatorSelect.removeAttr('disabled');
        }
    });

    $("#processTable .removeProcessForm").on("submit", function(event) {
        event.preventDefault();
        let self = this;
        confirmAction({
            title: "Are you sure you want to delete this process?",
            confirmText: "Yes, delete it",
            denyText: "No, keep it"
        }).then(() => {
            self.submit();
        }).catch(err => {});
    });
});
</script>
