@extends('layouts.dashboard.managerapp')

@section('title', 'Edit Route Card')

@section('content')
@if (session('success'))
    <div class="alert alert-success">{{ session('success') }}</div>
@endif
@if (session('error'))
    <div class="alert alert-danger">{{ session('error') }}</div>
@endif
@if ($errors->any())
    <div class="alert alert-danger">
        <ul class="mb-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Edit Route Card" icon="route" iconColor="warning" />
<!-- Content Row -->
<div class="bg-white row">
    <div class="col-lg-12">
        <!-- Project Planning Start -->
        <div class="rc-form" id="rcContent">
            <h1 class="pt-5 pb-5">Edit Route Card</h1>
            <br>
            <form id="routeForm" method="POST" action="{{ route('manager.routecard.update', $card->id) }}">
                @csrf
                @method('PUT')
                <div id="input1" class="input-field">
                    <div class="row" id="IdDateFields">
                        <div class="col-md-6">
                            <label>RC ID <span class="required" title="required">*</span>
                                <input type="text" id="routeNo" name="route_no" value="{{ $card->route_no }}"
                                    readonly class="form-control" required>
                            </label>
                        </div>
                        <div class="col-md-6">
                            <label>RC Date <span class="required" title="required">*</span>
                                <input type="date" id="routeDate" name="route_date"
                                    value="{{ old('route_date', $card->route_date) }}"
                                    class="form-control" required>
                            </label>
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="grn-info">
                                <label>GRN ID <span class="required" title="required">*</span>
                                    <input type="text" id="grnNo" name="grn_no" placeholder="GRN ID" value="{{ $card->grn_no }}" required>
                                </label>
                                <ul id="grnList" class="order-dropdown"></ul>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label>GRN Date
                                <input type="date" id="grnDate" name="grn_date" placeholder="GRN Date" value="{{ $card->grn_date }}">
                            </label>
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="order-info">
                                <label>Order ID
                                    <input type="text" id="orderNo" name="order_no" placeholder="Order ID" value="{{ $card->order_no }}">
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label>Order Date
                                <input type="date" id="orderDate" name="order_date" placeholder="Order Date" value="{{ $card->order_date }}">
                            </label>
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <label>Order Company Name
                                <select id="companyNameSelect" name="company_name" class="form-control" required>
                                    <option value="">Select Company</option>
                                    @foreach ($companies as $company)
                                        <option value="{{ $company->company }}"
                                            data-address="{{ $company->billing_address }}"
                                            data-gst="{{ $company->gstno }}" data-email="{{ $company->email }}"
                                            data-mobile="{{ $company->mobile }}"
                                            {{ $company->company == $card->company_name ? 'selected' : '' }}>
                                            {{ $company->company }}
                                        </option>
                                    @endforeach
                                </select>
                            </label>
                        </div>
                        <div class="col-md-6">
                            <label>Order Reference No
                                <input type="text" id="orderRefNo" name="order_ref_no"
                                    placeholder="Order Reference No" class="form-control" value="{{ $card->order_ref_no }}">
                            </label>
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col-md-6">
                            <label>Address
                                <input type="text" id="companyAddress" name="company_address" placeholder="Address"
                                    class="form-control" value="{{ $card->company_address }}">
                            </label>
                        </div>
                        <div class="col-md-6">
                            <label>GST No
                                <input type="text" id="companyGSTN" name="company_gstn" placeholder="GST No"
                                    class="form-control" value="{{ $card->company_gstn }}">
                            </label>
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col-md-6">
                            <label>Email
                                <input type="email" id="companyEmail" name="company_email" placeholder="Email"
                                    class="form-control" value="{{ $card->company_email }}">
                            </label>
                        </div>
                        <div class="col-md-6">
                            <label>Contact Number
                                <input type="tel" id="companyPhone" name="company_phone"
                                    placeholder="Contact Number" class="form-control" value="{{ $card->company_phone }}">
                            </label>
                        </div>
                    </div>
                    <br>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="quotation-info">
                                <label>Quotation ID
                                    <input type="text" id="quotationNo" name="quotation_no"
                                        placeholder="Quotation ID" value="{{ $card->quotation_no }}">
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label>Quotation Date
                                <input type="date" id="quotationDate" name="quotation_date"
                                    placeholder="Quotation Date" value="{{ $card->quotation_date }}">
                            </label>
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <label for="rfqNo">RFQ No</label>
                            <input type="text" id="rfqNo" name="rfq_no" placeholder="RFQ No" value="{{ $card->rfq_no }}">
                        </div>
                        <div class="col-md-6">
                            <label for="rfqDate">RFQ Date</label>
                            <input type="date" id="rfqDate" name="rfq_date" placeholder="RFQ Date" value="{{ $card->rfq_date }}">
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <label for="partNo">Part No</label>
                            <input type="text" id="partNo" name="part_no" placeholder="Part No" value="{{ $card->part_no }}">
                        </div>
                        <div class="col-md-6">
                            <label for="project-materialNo">Project Material No</label>
                            <input type="text" id="project-materialNo" name="project_material_no"
                                placeholder="Project Material No" value="{{ $card->project_material_no }}">
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-6">
                            <label for="drawingNo">Drawing No</label>
                            <input type="text" id="drawingNo" name="drawing_no" placeholder="Drawing No" value="{{ $card->drawing_no }}">
                        </div>
                        <div class="col-md-6">
                            <label for="drawingRev">Drawing Revision</label>
                            <input type="text" id="drawingRev" name="drawing_rev" placeholder="Drawing Revision" value="{{ $card->drawing_rev }}">
                        </div>
                    </div><br>
                    <div class="row">
                        <div class="col-md-12">
                            <label for="description">Description</label>
                            <textarea id="description" name="description" rows="2" placeholder="Project Description">{{ $card->description }}</textarea>
                        </div>
                    </div>
                    <hr>
                    <!--<div class="row">-->
                    <!--    <div class="col-lg-12">-->
                    <!--        <h3>Product Details</h3>-->
                    <!--        <div class="product-selection">-->
                    <!--            <label for="productType">Product Type</label>-->
                    <!--            <input type="text" id="productType" name="product_type"-->
                    <!--                placeholder="Product Type" value="{{ $card->product_type }}">-->
                    <!--        </div>-->
                            
                            
                    <div class="row">
                        <div class="col-md-6">
                            <label>Product Type <span class="required">*</span></label>
                            <select id="productType" name="product_type" class="form-control" required>
                                <option value="">Select Product Type</option>
                                @foreach ($productTypes as $pt)
                                    <option value="{{ $pt->name }}" {{ $pt->name == $card->product_type ? 'selected' : '' }}>{{ $pt->name }}</option>
                                @endforeach
                            </select>
                        </div>
                         <div class="col-md-6">
        <label>Expected Project Start Date <span class="required">*</span></label>
        <input type="datetime-local" id="projectStart" name="project_start_date" required class="form-control"
            value="{{ old('project_start_date', \Carbon\Carbon::parse($card->project_start_date)->format('Y-m-d\TH:i')) }}">
    </div>
                    </div>
                    <hr>
                    <div class="row">
    <div class="col-lg-12">
        <h3>Process Details</h3>
        <table id="processTable" class="table table-bordered">
            <thead>
                <tr>
                    <th>Sl No.</th>
                    <th>Process</th>
                    <th>Source</th>
                    <th>Previous Process</th>
                    <th>Machine</th>
                    <th>Operator</th>
                    <th>Cycle Time (h:m)</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                @foreach($card->processes as $i => $process)
                <tr data-prev="{{ $process->previous_process_id ? $loop->index : '' }}">
                    <td class="sl-no">{{ $i + 1 }}</td>
                    <td>
                        <select name="processes[{{ $i }}][process]" class="form-control process-select" required data-selected="{{ $process->process }}">
                            <option value="">Select Process</option>
                            {{-- JS will fill --}}
                        </select>
                        <input type="text" name="processes[{{ $i }}][process_other]" class="form-control mt-2 process-other" style="display:none;" placeholder="Other process" value="{{ $process->process_other ?? '' }}">
                    </td>
                    <td>
                        <label>
                            <input type="radio" name="processes[{{ $i }}][source]" value="inhouse" @if ($process->source == 'inhouse') checked @endif> Inhouse
                        </label>
                        <label>
                            <input type="radio" name="processes[{{ $i }}][source]" value="outsourced" @if ($process->source == 'outsourced') checked @endif> Outsourced
                        </label>
                    </td>
                    <td class="prev-process-cell"></td>
                    <td>
                        <select name="processes[{{ $i }}][machine]" class="form-control machine-select" required>
                            <option value="">Select Machine</option>
                            @foreach ($machines as $machine)
                                <option value="{{ $machine->machine_id }}" @if ($machine->machine_id == $process->machine) selected @endif>
                                    {{ $machine->machine_id }} ({{ $machineAvailability[$machine->machine_id] ?? 'Available now' }})
                                </option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <select name="processes[{{ $i }}][operator]" class="form-control operator-select" required>
                            <option value="">Select Operator</option>
                            @foreach ($employees as $emp)
                                <option value="{{ $emp->id }}" @if ($emp->id == $process->operator) selected @endif>
                                    {{ $emp->name }} ({{ $operatorAvailability[$emp->id] ?? 'Available now' }})
                                </option>
                            @endforeach
                        </select>
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <input type="number" name="processes[{{ $i }}][cycle_hours]" class="form-control" placeholder="Hours" min="0" step="1" style="width: 45%;" value="{{ $process->cycle_hours }}">
                            <span>:</span>
                            <input type="number" name="processes[{{ $i }}][cycle_minutes]" class="form-control" placeholder="Minutes" min="0" max="59" step="1" style="width: 45%;" value="{{ $process->cycle_minutes }}">
                        </div>
                    </td>
                    <td>
                        <button class="btn btn-danger" type="button" onclick="deleteProcessRow(this)"><i class="fa fa-trash"></i></button>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
        <button type="button" class="btn btn-primary" id="addProcessRowBtn">Add Row</button>
    </div>
</div>

                    <hr>
                    <div class="row mt-5 mb-5">
                        <div class="col-xl-3">
                            <button type="submit" id="save-RC" class="btn btn-success">Update</button>
                        </div>
                        <div class="col-xl-3">
                            <a href="{{ route('manager.routecard.routecarddetails') }}" class="btn btn-danger">Cancel</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let rowIdx = {{ count($card->processes) }};
let productTypeProcesses = {};

function fillProcessDropdowns(processes) {
    $('#processTable tbody tr').each(function(i, row) {
        let $procSel = $(row).find('.process-select');
        let selectedVal = $procSel.data('selected') || $procSel.val();
        let options = '<option value="">Select Process</option>';
        if (processes.length > 0) {
            processes.forEach(function(proc) {
                options += `<option value="${proc}">${proc}</option>`;
            });
            options += '<option value="Other">Other</option>';
        } else {
            options += '<option value="Other">Other</option>';
        }
        $procSel.html(options);
        if (selectedVal) {
            $procSel.val(selectedVal);
        }
        if (selectedVal === "Other") {
            $(row).find('.process-other').show().prop('required', true);
        } else {
            $(row).find('.process-other').hide().prop('required', false);
        }
    });
}

function updateProcessDropdowns(productType) {
    if (!productType) {
        fillProcessDropdowns([]);
        return;
    }
    if (productTypeProcesses[productType]) {
        fillProcessDropdowns(productTypeProcesses[productType]);
        return;
    }
    $.get("{{ url('manager/routecard/get-process-list') }}", { product_type: productType }, function(processes) {
        productTypeProcesses[productType] = processes;
        fillProcessDropdowns(processes);
        updatePreviousProcessDropdowns();
    });
}

function handleSourceChange(radio) {
    let $row = $(radio).closest('tr');
    let $machine = $row.find('select.machine-select');
    let $operator = $row.find('select.operator-select');
    let val = $(radio).val();
    if (val === 'outsourced') {
        $machine.prop('disabled', true).val('');
        $operator.prop('disabled', true).val('');
    } else {
        $machine.prop('disabled', false);
        $operator.prop('disabled', false);
    }
}

$(document).on('change', 'input[type=radio][name^="processes"][name$="[source]"]', function() {
    handleSourceChange(this);
});

function updateSourceFields() {
    $('#processTable tbody tr').each(function() {
        let $checked = $(this).find('input[type=radio][name$="[source]"]:checked');
        if ($checked.length) handleSourceChange($checked[0]);
    });
}

function updatePreviousProcessDropdowns() {
    let rows = $('#processTable tbody tr');
    let processNames = [];
    rows.each(function(i, row) {
        let val = $(row).find('select.process-select').val() || $(row).find('.process-other').val() || `Process ${i+1}`;
        processNames.push(val);
    });
    rows.each(function(i, row) {
        let $cell = $(row).find('.prev-process-cell');
        let prevValue = $(row).data('prev');
        if (i === 0) {
            $cell.html('');
        } else {
            let options = '';
            for (let j = 0; j < i; j++) {
                options += `<option value="${j+1}" ${(prevValue == (j+1)) ? 'selected' : ''}>${processNames[j]}</option>`;
            }
            $cell.html(`<select name="processes[${i}][previous_process]" class="form-control prev-process-select">${options}</select>`);
            let $select = $cell.find('select');
            if ($select.length && !prevValue) $select.prop('selectedIndex', $select[0].options.length-1);
        }
    });
}

$('#processTable').on('change input', '.process-select, .process-other', function() {
    updatePreviousProcessDropdowns();
});

function updateSlNos() {
    $('#processTable tbody tr').each(function(i, row) {
        $(row).find('.sl-no').text(i + 1);
        $(row).find('input, select').each(function() {
            let name = $(this).attr('name');
            if (name) {
                name = name.replace(/processes\[\d+\]/g, `processes[${i}]`);
                $(this).attr('name', name);
            }
        });
        $(row).find('input[type=radio]').each(function() {
            let name = $(this).attr('name');
            if (name) {
                name = name.replace(/processes\[\d+\]\[source\]/g, `processes[${i}][source]`);
                $(this).attr('name', name);
            }
        });
    });
}

function disableDuplicateMachines() {
    let allSelects = document.querySelectorAll('.machine-select');
    let selected = [];
    allSelects.forEach(function(select) {
        selected.push(select.value);
    });
    allSelects.forEach(function(select) {
        let currentValue = select.value;
        Array.from(select.options).forEach(function(option) {
            option.disabled = false;
        });
        allSelects.forEach(function(otherSelect) {
            if (otherSelect !== select && otherSelect.value) {
                let val = otherSelect.value;
                Array.from(select.options).forEach(function(option) {
                    if (option.value == val && option.value !== currentValue && option.value !== "") {
                        option.disabled = true;
                    }
                });
            }
        });
    });
}
$(document).on('change', '.machine-select', disableDuplicateMachines);

$('#addProcessRowBtn').on('click', function() {
    let tbody = $('#processTable tbody');
    let machineOptions = `
        <option value="">Select Machine</option>
        @foreach ($machines as $machine)
            <option value="{{ $machine->machine_id }}">{{ $machine->machine_id }} ({{ $machineAvailability[$machine->machine_id] ?? 'Available now' }})</option>
        @endforeach
    `;
    let operatorOptions = `
        <option value="">Select Operator</option>
        @foreach ($employees as $emp)
            <option value="{{ $emp->id }}">{{ $emp->name }} ({{ $operatorAvailability[$emp->id] ?? 'Available now' }})</option>
        @endforeach
    `;
    let newRow = `
        <tr>
            <td class="sl-no">${rowIdx + 1}</td>
            <td>
                <select name="processes[${rowIdx}][process]" class="form-control process-select" required>
                    <option value="">Select Process</option>
                </select>
                <input type="text" name="processes[${rowIdx}][process_other]" class="form-control mt-2 process-other" style="display:none;" placeholder="Other process">
            </td>
            <td>
                <label>
                    <input type="radio" name="processes[${rowIdx}][source]" value="inhouse" checked> Inhouse
                </label>
                <label>
                    <input type="radio" name="processes[${rowIdx}][source]" value="outsourced"> Outsourced
                </label>
            </td>
            <td class="prev-process-cell"></td>
            <td>
                <select name="processes[${rowIdx}][machine]" class="form-control machine-select" required>
                    ${machineOptions}
                </select>
            </td>
            <td>
                <select name="processes[${rowIdx}][operator]" class="form-control operator-select" required>
                    ${operatorOptions}
                </select>
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <input type="number" name="processes[${rowIdx}][cycle_hours]" class="form-control" placeholder="Hours" min="0" step="1" style="width: 45%;">
                    <span>:</span>
                    <input type="number" name="processes[${rowIdx}][cycle_minutes]" class="form-control" placeholder="Minutes" min="0" max="59" step="1" style="width: 45%;">
                </div>
            </td>
            <td>
                <button class="btn btn-danger" type="button" onclick="deleteProcessRow(this)"><i class="fa fa-trash"></i></button>
            </td>
        </tr>
    `;
    tbody.append(newRow);
    rowIdx++;
    updateSlNos();
    updateProcessDropdowns($('#productType').val());
    disableDuplicateMachines();
    updateSourceFields();
    updatePreviousProcessDropdowns();
});

function deleteProcessRow(btn) {
    let tr = $(btn).closest('tr');
    if ($('#processTable tbody tr').length > 1) {
        tr.remove();
        rowIdx--;
        updateSlNos();
        disableDuplicateMachines();
        updatePreviousProcessDropdowns();
    } else {
        alert('At least one process row is required!');
    }
}

$(document).ready(function() {
    updateProcessDropdowns($('#productType').val());
    disableDuplicateMachines();
    updateSourceFields();
    updatePreviousProcessDropdowns();
});
</script>
@endsection