<div class="modal fade" id="routeFormProcessModal" tabindex="-1" role="dialog" aria-labelledby="processModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <form id="routeFormProcessForm" class="modal-content" action="{{ route('superadmin.routecard.process.create', $routeCardId) }}" method="POST">
            @csrf
            <input type="hidden" name="route_card_id" value="{{ $routeCardId }}" />

            <div class="modal-header" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
                <h5 class="modal-title text-white" id="processModalLabel">
                    <i class="fas fa-cogs mr-2"></i> Add Process
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <div id="processMessage" class="alert d-none mb-3"></div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Process <span class="text-danger">*</span></label>
                        <select class="form-control" id="process" name="process" required>
                            <option value="">Select Process</option>
                            @foreach ($processes as $process)
                                <option value="{{ $process->id }}">{{ $process->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Source <span class="text-danger">*</span></label>
                        <select class="form-control" id="source" name="source" required>
                            <option value="inhouse">Inhouse</option>
                            <option value="outsourced">Outsourced</option>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Previous Process</label>
                        <select class="form-control" id="previous_process_id" name="previous_process_id">
                            <option value="">None (First Process)</option>
                            @foreach ($routeCardProcesses as $process)
                                <option value="{{ $process->id }}" {{ isset($lastRouteCardProcess['id']) && $lastRouteCardProcess['id'] == $process->id ? 'selected' : '' }}>
                                    {{ $process->process }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Description</label>
                        <input type="text" class="form-control" id="modal_description" name="description" placeholder="Enter description">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Machine</label>
                        <select class="form-control" id="machine" name="machine">
                            <option value="">Select Machine</option>
                            @foreach ($machines as $machine)
                                <option value="{{ $machine->id }}" data-machine="{{ json_encode($machine) }}">
                                    {{ $machine->machine_name }} [{{ $machine->machine_id }}] {{ $machine->available_by ? '(@ ' . $machine->available_by . ')' : '' }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Operator</label>
                        <select class="form-control" id="operator" name="operator">
                            <option value="">Select Operator</option>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3 mb-3">
                        <label class="small font-weight-bold">Cycle Time (Hours) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="ct_hours" name="cycle_hours" min="0" value="1" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="small font-weight-bold">Cycle Time (Minutes) <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="ct_minutes" name="cycle_minutes" min="0" max="59" value="0" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="small font-weight-bold">Shift Start</label>
                        <input type="time" class="form-control" id="actual_start" name="actual_start" value="09:00">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="small font-weight-bold">Shift End</label>
                        <input type="time" class="form-control" id="actual_end" name="actual_end" value="18:00">
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Expected Start Date <span class="text-danger">*</span></label>
                        <input type="datetime-local" class="form-control" id="start_date" name="start_date"
                            value="{{ $lastRouteCardProcess['end_date'] ?? ($routeCard['project_start_date'] . 'T09:00') }}"
                            data-min="{{ $lastRouteCardProcess['end_date'] ?? $routeCard['project_start_date'] }}" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="small font-weight-bold">Expected End Date</label>
                        <input type="datetime-local" class="form-control" id="end_date" name="end_date" readonly>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                    <i class="fa fa-times mr-1"></i> Cancel
                </button>
                <button type="submit" class="btn btn-success btn-sm" id="saveProcessBtn">
                    <i class="fa fa-save mr-1"></i> Save Process
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log("Process modal script loaded");

    $('#routeFormProcessModal').on('show.bs.modal', function() {
        let mode = $("#routeFormProcessModal").data('mode');
        let data = $("#routeFormProcessModal").data('data');

        if (mode == "edit") {
            $("#processModalLabel").html('<i class="fas fa-edit mr-2"></i> Edit Process');
        } else {
            $("#processModalLabel").html('<i class="fas fa-cogs mr-2"></i> Add Process');
        }

        if (data && mode == "edit") {
            fillFormData($("#routeFormProcessForm"), data, mappedKeys, mappedValueResolver);
        }

        $("#routeFormProcessModal #start_date").trigger('change');
    });

    $("#routeFormProcessModal #routeFormProcessForm").on("submit", function(event) {
        event.preventDefault();
        const formData = getFormData(event.target);
        console.log("Process form submitted", formData);
        this.submit();
    });

    $("#routeFormProcessModal #start_date, #routeFormProcessModal #ct_hours, #routeFormProcessModal #ct_minutes, #routeFormProcessModal #actual_start, #routeFormProcessModal #actual_end")
    .on("change", function(event) {
        let expectedStartDate = $("#routeFormProcessModal #start_date").val();
        let cycleHours = +$("#routeFormProcessModal #ct_hours").val();
        let cycleMinutes = +$("#routeFormProcessModal #ct_minutes").val();
        let shiftEndTime = $("#routeFormProcessModal #actual_end").val();
        let shiftStartTime = $("#routeFormProcessModal #actual_start").val();

        if (time2Date(shiftStartTime).getHours() > (new Date(expectedStartDate)).getHours()) {
            expectedStartDate = formatDate(setTime(expectedStartDate, shiftStartTime), "yyyy-mm-ddThh:ii");
            $("#routeFormProcessModal #start_date").val(expectedStartDate);
        } else {
            shiftStartTime = formatDate(new Date(expectedStartDate), "hh:ii");
            $("#routeFormProcessModal #actual_start").val(shiftStartTime);
        }

        if (shiftStartTime && shiftEndTime) {
            let workHours = getHourDifference(shiftStartTime, shiftEndTime);
            $("#routeFormProcessModal #workingHourLabel").text(workHours);
        }

        if (expectedStartDate && cycleHours >= 0 && cycleMinutes >= 0 && shiftEndTime && shiftStartTime) {
            let expectedEndDate = calculateExpectedEnd({
                shiftStartTime,
                shiftEndTime,
                cycleHours,
                cycleMinutes,
                expectedStartDate
            });
            let endDate = formatDate(expectedEndDate, "yyyy-mm-ddThh:ii");
            $("#routeFormProcessModal #end_date").val(endDate);
        }
    });

    $("#routeFormProcessModal #source").on("change", function(event) {
        let value = event.target.value;
        if (value == "inhouse") {
            $("#routeFormProcessModal #operator").attr('required', true).removeAttr('disabled');
            $("#routeFormProcessModal #machine").attr('required', true).removeAttr('disabled');
        } else {
            $("#routeFormProcessModal #operator").removeAttr('required').attr('disabled', true);
            $("#routeFormProcessModal #machine").removeAttr('required').attr('disabled', true);
        }
    });

    $("#routeFormProcessModal #process").on("change", function(event) {
        let selectedProcess = $(this).find('option:selected');
        let machineSelection = $("#routeFormProcessModal #machine");
        machineSelection.find('option').each(function() {
            let machineData = $(this).data('machine');
            let flag = machineData && machineData.processes && machineData.processes.map(v => v.id).includes(+selectedProcess.val());
            if (flag) {
                $(this).removeAttr('disabled');
            } else {
                $(this).attr('disabled', true);
            }
        });
        $("#routeFormProcessModal #machine").val('');
        $("#routeFormProcessModal #operator").val('');
    });

    $("#routeFormProcessModal #machine").on("change", function(event) {
        let selectedMachine = $(this).find('option:selected');
        let machineData = selectedMachine.data('machine');
        if (machineData) {
            console.log("Selected Machine Data:", machineData);
            let machineStartDate = new Date(machineData.available_by);
            let expectedStartDate = new Date($("#routeFormProcessModal #start_date").val());
            if (machineStartDate.getTime() > expectedStartDate.getTime()) {
                $("#routeFormProcessModal #start_date").val(machineData.available_by);
            }
            populateOperators(machineData.id, machineData);
        } else {
            $("#routeFormProcessModal #operator").empty().append('<option value="">Select Operator</option>');
        }
    });

    $("#routeFormProcessModal #operator").on("change", function(event) {
        let selectedOperator = $(this).find('option:selected');
        let operatorData = selectedOperator.data('operator');
        if (operatorData) {
            console.log("Selected Operator Data:", operatorData);
            let operatorStartDate = new Date(operatorData.available_by);
            let expectedStartDate = new Date($("#routeFormProcessModal #start_date").val());
            if (operatorStartDate.getTime() > expectedStartDate.getTime()) {
                $("#routeFormProcessModal #start_date").val(operatorData.available_by);
            }
        }
    });

    function populateOperators(machineId, machineData) {
        const operatorSelect = $("#routeFormProcessModal #operator");
        operatorSelect.empty();
        operatorSelect.append('<option value="">Select Operator</option>');
        machineData?.operators?.forEach(function(operator) {
            operatorSelect.append(`<option value="${operator.id}" data-operator='${JSON.stringify(operator)}'>${operator.name} ${operator.available_by ? '(@ ' + operator.available_by + ')' : ''}</option>`);
        });
    }
});
</script>
