@extends('layouts.dashboard.adminapp')

@section('title', '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
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Route Card</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></div>
    </div>

    <div class="bg-white row">
        <div class="col-lg-12">
            <div class="rc-form" id="rcContent">
                <h1 class="pt-5 pb-5">Route Card</h1>
                <br>
                <form id="routeForm" method="POST" action="{{ route('admin.routecard.store') }}">
                    @csrf
                    <div id="input1" class="input-field">
                        <div class="row">
                            <div class="col-md-6">
                                <label>RC ID <span class="required">*</span>
                                    <input type="text" id="routeNo" name="route_no" value="{{ $nextRouteNo }}"
                                        readonly required class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>RC Date <span class="required">*</span>
                                    <input type="date" id="routeDate" name="route_date" required class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>GRN ID <span class="required">*</span>
                                    <select id="grnNo" name="grn_no" class="form-control" required>
                                        <option value="">Select GRN</option>
                                        @foreach ($availableGrns as $grn)
                                            <option value="{{ $grn->grn_no }}" data-date="{{ $grn->grn_date }}"
                                                data-order-no="{{ $grn->order_no }}"
                                                data-order-date="{{ $grn->order_date }}"
                                                data-company="{{ $grn->company_name }}"
                                                data-address="{{ $grn->company_address }}"
                                                data-gst="{{ $grn->company_gst }}" data-email="{{ $grn->company_email }}"
                                                data-phone="{{ $grn->company_phone }}"
                                                data-order-ref-no="{{ $grn->order_ref_no }}"
                                                data-quotation-no="{{ $grn->quotation_no }}"
                                                data-quotation-date="{{ $grn->quotation_date }}"
                                                data-rfq-no="{{ $grn->rfq_no }}" data-rfq-date="{{ $grn->rfq_date }}"
                                                data-part-no="{{ $grn->part_no }}"
                                                data-project-material-no="{{ $grn->project_material_no }}"
                                                data-drawing-no="{{ $grn->drawing_no }}"
                                                data-drawing-rev="{{ $grn->drawing_rev }}"
                                                data-description="{{ $grn->description }}"
                                                data-product-type="{{ $grn->product_type }}">
                                                {{ $grn->grn_no }}
                                            </option>
                                        @endforeach
                                    </select>
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>GRN Date
                                    <input type="date" id="grnDate" name="grn_date" class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Order ID
                                    <input type="text" id="orderNo" name="order_no" class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>Order Date
                                    <input type="date" id="orderDate" name="order_date" class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Order Company Name
                                    <input type="text" id="companyName" name="company_name" class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>Order Reference No
                                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Address
                                    <input type="text" id="companyAddress" name="company_address" class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>GST No
                                    <input type="text" id="companyGSTN" name="company_gstn" class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Email
                                    <input type="email" id="companyEmail" name="company_email" class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>Contact Number
                                    <input type="tel" id="companyPhone" name="company_phone" class="form-control">
                                </label>
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-6">
                                <label>Quotation ID
                                    <input type="text" id="quotationNo" name="quotation_no" class="form-control">
                                </label>
                            </div>
                            <div class="col-md-6">
                                <label>Quotation Date
                                    <input type="date" id="quotationDate" name="quotation_date" class="form-control">
                                </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" class="form-control">
                            </div>
                            <div class="col-md-6">
                                <label for="rfqDate">RFQ Date</label>
                                <input type="date" id="rfqDate" name="rfq_date" class="form-control">
                            </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" class="form-control">
                            </div>
                            <div class="col-md-6">
                                <label for="project-materialNo">Project Material No</label>
                                <input type="text" id="project-materialNo" name="project_material_no"
                                    class="form-control">
                            </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" class="form-control">
                            </div>
                            <div class="col-md-6">
                                <label for="drawingRev">Drawing Revision</label>
                                <input type="text" id="drawingRev" name="drawing_rev" class="form-control">
                            </div>
                        </div>
                        <br>
                        <div class="row">
                            <div class="col-md-12">
                                <label for="description">Description</label>
                                <textarea id="description" name="description" rows="2" class="form-control"></textarea>
                            </div>
                        </div>
                        <br>
                        <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 }}</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">
                            </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>
                                        <tr>
                                            <td class="sl-no">1</td>
                                            <td>
                                                <select name="processes[0][process]" class="form-control process-select"
                                                    required onchange="handleProcessOther(this)">
                                                    <option value="">Select Process</option>
                                                </select>
                                                <input type="text" name="processes[0][process_other]"
                                                    class="form-control mt-2 process-other" style="display:none;"
                                                    placeholder="Other process">
                                            </td>
                                            <td>
                                                <label>
                                                    <input type="radio" name="processes[0][source]" value="inhouse"
                                                        checked onchange="handleSourceChange(this)"> Inhouse
                                                </label>
                                                <label>
                                                    <input type="radio" name="processes[0][source]" value="outsourced"
                                                        onchange="handleSourceChange(this)"> Outsourced
                                                </label>
                                            </td>
                                            <td class="prev-process-cell"></td>
                                            <td>
                                                <select name="processes[0][machine]" class="form-control machine-select">
                                                    <option value="">Select Machine</option>
                                                    @foreach ($machines as $machine)
                                                        <option value="{{ $machine->machine_id }}">
                                                            {{ $machine->machine_id }}
                                                            ({{ $machineAvailability[$machine->machine_id] ?? 'Now' }})
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td>
                                                <select name="processes[0][operator]" class="form-control operator-select">
                                                    <option value="">Select Operator</option>
                                                    @foreach ($employees as $emp)
                                                        <option value="{{ $emp->id }}">
                                                            {{ $emp->name }} ({{ $operatorAvailability[$emp->id] ?? 'Now' }})
                                                        </option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <input type="number" name="processes[0][cycle_hours]"
                                                        class="form-control" placeholder="Hours" min="0"
                                                        step="1" style="width: 45%;">
                                                    <span>:</span>
                                                    <input type="number" name="processes[0][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>
                                </table>
                                <button type="button" class="btn btn-primary" onclick="addProcessRow()">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">Save</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Set today's date for routeDate
    function setTodayDate(id) {
        let today = new Date().toISOString().split('T')[0];
        document.getElementById(id).value = today;
    }
    setTodayDate('routeDate');

    // Auto-fill details from selected GRN
    document.getElementById('grnNo').addEventListener('change', function() {
        const opt = this.selectedOptions[0];
        if (!opt) return;
        document.getElementById('grnDate').value = opt.getAttribute('data-date') || '';
        document.getElementById('orderNo').value = opt.getAttribute('data-order-no') || '';
        document.getElementById('orderDate').value = opt.getAttribute('data-order-date') || '';
        document.getElementById('companyName').value = opt.getAttribute('data-company') || '';
        document.getElementById('companyAddress').value = opt.getAttribute('data-address') || '';
        document.getElementById('companyGSTN').value = opt.getAttribute('data-gst') || '';
        document.getElementById('companyEmail').value = opt.getAttribute('data-email') || '';
        document.getElementById('companyPhone').value = opt.getAttribute('data-phone') || '';
        document.getElementById('orderRefNo').value = opt.getAttribute('data-order-ref-no') || '';
        document.getElementById('quotationNo').value = opt.getAttribute('data-quotation-no') || '';
        document.getElementById('quotationDate').value = opt.getAttribute('data-quotation-date') || '';
        document.getElementById('rfqNo').value = opt.getAttribute('data-rfq-no') || '';
        document.getElementById('rfqDate').value = opt.getAttribute('data-rfq-date') || '';
        document.getElementById('partNo').value = opt.getAttribute('data-part-no') || '';
        document.getElementById('project-materialNo').value = opt.getAttribute('data-project-material-no') || '';
        document.getElementById('drawingNo').value = opt.getAttribute('data-drawing-no') || '';
        document.getElementById('drawingRev').value = opt.getAttribute('data-drawing-rev') || '';
        document.getElementById('description').value = opt.getAttribute('data-description') || '';
        // Set product type dropdown and trigger change event to load process list
        const typeVal = opt.getAttribute('data-product-type') || '';
        document.getElementById('productType').value = typeVal;
        $('#productType').trigger('change');
        updateProcessDropdowns();
    });

    // Product Type: show/hide "other" input, fetch process list from server
    $('#productType').on('change', function() {
        if ($(this).val() === 'Other') {
            $('#productTypeOther').show();
        } else {
            $('#productTypeOther').hide();
        }
        // update process dropdowns for all rows
        updateProcessDropdowns();
    });

    // Fetch process list from server based on product type
    function updateProcessDropdowns() {
        var type = $('#productType').val();
        if (!type) {
            $('.process-select').each(function() {
                $(this).html('<option value="">Select Process</option>');
            });
            return;
        }
        $.get("{{ url('admin/routecard/get-process-list') }}", {
            product_type: type
        }, function(processes) {
            $('.process-select').each(function() {
                let sel = $(this);
                let currVal = sel.val();
                let options = '<option value="">Select Process</option>';
                processes.forEach(function(proc) {
                    options += `<option value="${proc}">${proc}</option>`;
                });
                options += '<option value="Other">Other</option>';
                sel.html(options);
                sel.val(currVal);
                sel.trigger('change');
            });
        });
    }

    // Add row logic with process dropdown (not static text)
    function addProcessRow() {
        let table = document.getElementById('processTable').getElementsByTagName('tbody')[0];
        let idx = table.rows.length;
        let row = table.insertRow();
        row.innerHTML = `
        <td class="sl-no">${idx+1}</td>
        <td>
            <select name="processes[${idx}][process]" class="form-control process-select" required onchange="handleProcessOther(this)">
                <option value="">Select Process</option>
            </select>
            <input type="text" name="processes[${idx}][process_other]" class="form-control mt-2 process-other" style="display:none;" placeholder="Other process">
        </td>
        <td>
            <label><input type="radio" name="processes[${idx}][source]" value="inhouse" checked onchange="handleSourceChange(this)"> Inhouse</label>
            <label><input type="radio" name="processes[${idx}][source]" value="outsourced" onchange="handleSourceChange(this)"> Outsourced</label>
        </td>
        <td class="prev-process-cell"></td>
        <td>
            <select name="processes[${idx}][machine]" class="form-control machine-select">
                <option value="">Select Machine</option>
                @foreach ($machines as $machine)
                    <option value="{{ $machine->machine_id }}">
                        {{ $machine->machine_id }} 
                        ({{ $machineAvailability[$machine->machine_id] ?? 'Now' }})
                    </option>
                @endforeach
            </select>
        </td>
        <td>
            <select name="processes[${idx}][operator]" class="form-control operator-select">
                <option value="">Select Operator</option>
                @foreach ($employees as $emp)
                    <option value="{{ $emp->id }}">
                        {{ $emp->name }} ({{ $operatorAvailability[$emp->id] ?? 'Now' }})
                    </option>
                @endforeach
            </select>
        </td>
        <td>
            <div class="d-flex align-items-center">
                <input type="number" name="processes[${idx}][cycle_hours]" class="form-control" placeholder="Hours" min="0" step="1" style="width: 45%;">
                <span>:</span>
                <input type="number" name="processes[${idx}][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>
    `;
        updatePreviousProcessDropdowns();
        updateProcessSlNo();
        updateProcessDropdowns();
        updateSourceFields();
    }

    function deleteProcessRow(btn) {
        let table = document.getElementById('processTable').getElementsByTagName('tbody')[0];
        let row = btn.closest('tr');
        table.removeChild(row);
        updatePreviousProcessDropdowns();
        updateProcessSlNo();
        handleDuplicateProcess();
    }

    // Process "Other" logic
    function handleProcessOther(sel) {
        let $sel = $(sel);
        let $other = $sel.closest('td').find('.process-other');
        if ($sel.val() === "Other") {
            $other.show().prop('required', true);
        } else {
            $other.hide().val('').prop('required', false);
        }
        handleDuplicateProcess();
    }

    // Duplicate process validation (disable already selected in other rows)
    function handleDuplicateProcess() {
        let selected = [];
        $('.process-select').each(function() {
            let val = $(this).val();
            if (val && val !== "Other") selected.push(val);
        });
        $('.process-select').each(function() {
            let sel = $(this);
            let curr = sel.val();
            sel.find('option').prop('disabled', false);
            sel.find('option').each(function() {
                let v = $(this).val();
                if (v && v !== curr && v !== "" && selected.includes(v)) {
                    $(this).prop('disabled', true);
                }
            });
        });
    }
    $(document).on('change', '.process-select', handleDuplicateProcess);

    // Duplicate machine validation
    function handleDuplicateMachine() {
        let selected = [];
        $('.machine-select').each(function() {
            let val = $(this).val();
            if (val) selected.push(val);
        });
        $('.machine-select').each(function() {
            let sel = $(this);
            let curr = sel.val();
            sel.find('option').prop('disabled', false);
            sel.find('option').each(function() {
                let v = $(this).val();
                if (v && v !== curr && v !== "" && selected.includes(v)) {
                    $(this).prop('disabled', true);
                }
            });
        });
    }
    $(document).on('change', '.machine-select', handleDuplicateMachine);

    // --- Show/Hide Machine and Operator fields based on Source ---
    function handleSourceChange(radio) {
        let $row = $(radio).closest('tr');
        let sourceVal = $(radio).val();
        let $machine = $row.find('select.machine-select');
        let $operator = $row.find('select.operator-select');
    
        if (sourceVal === "outsourced") {
            $machine.prop('disabled', true);
            $operator.prop('disabled', true);
            // Optionally clear value:
            $machine.val('');
            $operator.val('');
        } else {
            $machine.prop('disabled', false);
            $operator.prop('disabled', false);
        }
    }


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

    // Set machine/operator field visibility on page load and after row add/remove
    function updateSourceFields() {
    $('#processTable tbody tr').each(function() {
        let $row = $(this);
        let $checked = $row.find('input[type=radio][name$="[source]"]:checked');
        if ($checked.length) handleSourceChange($checked[0]);
    });
}
    // --- Auto-select the immediate previous process in Previous Process column ---
    function updatePreviousProcessDropdowns() {
        let table = document.getElementById('processTable').getElementsByTagName('tbody')[0];
        let rows = table.getElementsByTagName('tr');
        let processNames = [];
        for (let i = 0; i < rows.length; i++) {
            let proc = $(rows[i]).find('select.process-select').val() ||
                $(rows[i]).find('input.process-other').val() ||
                `Process ${i+1}`;
            processNames.push(proc);
        }
        for (let i = 0; i < rows.length; i++) {
            let cell = rows[i].querySelector('.prev-process-cell');
            if (i === 0) {
                cell.innerHTML = ''; // No previous process for first row
            } else {
                let options = processNames.slice(0, i)
                    .map((name, j) => `<option value="${j+1}">${name}</option>`).join('');
                cell.innerHTML = `<select name="processes[${i}][previous_process]" class="form-control prev-process-select">${options}</select>`;
                // Auto-select previous process by default (e.g., 2nd row selects 1, 3rd selects 2)
                let prevProcessSelect = cell.querySelector('select');
                if (prevProcessSelect) prevProcessSelect.selectedIndex = prevProcessSelect.options.length - 1;
            }
        }
    }
    $('#processTable').on('change input', '.process-select, .process-other', function() {
        updatePreviousProcessDropdowns();
    });

    // Update SL No and field names
    function updateProcessSlNo() {
        let table = document.getElementById('processTable').getElementsByTagName('tbody')[0];
        let rows = table.getElementsByTagName('tr');
        for (let i = 0; i < rows.length; i++) {
            rows[i].querySelector('.sl-no').innerText = i + 1;
            $(rows[i]).find('input,select').each(function() {
                if (this.name) this.name = this.name.replace(/processes\[\d+\]/g, `processes[${i}]`);
            });
            $(rows[i]).find('input[type=radio]').each(function() {
                if (this.name) this.name = this.name.replace(/processes\[\d+\]\[source\]/g,
                    `processes[${i}][source]`);
            });
        }
        updatePreviousProcessDropdowns();
        updateSourceFields();
    }

    $(document).ready(function() {
        updateProcessDropdowns();
        updatePreviousProcessDropdowns();
        updateSourceFields();
    });
</script>

@endsection
