@extends('layouts.dashboard.superadminapp')
@section('title', 'Edit Route Card')

@section('styles')
<style>
    #processTable input.form-control, #processTable select.form-control {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Edit Route Card" icon="route" iconColor="warning" />

<!-- Alerts -->
@if (session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if (session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if ($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>
        <ul class="mb-0">
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<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, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-edit mr-2"></i> Edit Route Card - {{ $card->route_no }}
        </h6>
        <a href="{{ route('superadmin.routecard.details') }}" class="btn btn-light btn-sm">
            <i class="fa fa-arrow-left mr-1"></i> Back to List
        </a>
    </div>
    <div class="card-body">
        <form id="routeForm" method="POST" action="{{ route('superadmin.routecard.update', $card->id) }}">
            @csrf
            @method('PUT')

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RC ID <span class="text-danger">*</span></label>
                    <input type="text" id="routeNo" name="route_no" value="{{ $card->route_no }}" readonly class="form-control" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RC Date <span class="text-danger">*</span></label>
                    <input type="date" id="routeDate" name="route_date" value="{{ old('route_date', $card->route_date) }}" class="form-control" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">GRN ID</label>
                    <input type="text" id="grnNo" name="grn_no" class="form-control" value="{{ $card->grn_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">GRN Date</label>
                    <input type="date" id="grnDate" name="grn_date" class="form-control" value="{{ $card->grn_date }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Order ID</label>
                    <input type="text" id="orderNo" name="order_no" class="form-control" value="{{ $card->order_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Order Date</label>
                    <input type="date" id="orderDate" name="order_date" class="form-control" value="{{ $card->order_date }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Order Company Name <span class="text-danger">*</span></label>
                    <select id="companyNameSelect" name="company_name" class="form-control" required onchange="fillCompanyDetails(this)">
                        <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>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Address</label>
                    <input type="text" id="companyAddress" name="company_address" class="form-control" value="{{ $card->company_address }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">GST No</label>
                    <input type="text" id="companyGSTN" name="company_gstn" class="form-control" value="{{ $card->company_gstn }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Order Reference No</label>
                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control" value="{{ $card->order_ref_no }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Email</label>
                    <input type="email" id="companyEmail" name="company_email" class="form-control" value="{{ $card->company_email }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Contact Number</label>
                    <input type="tel" id="companyPhone" name="company_phone" class="form-control" value="{{ $card->company_phone }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Quotation ID</label>
                    <input type="text" id="quotationNo" name="quotation_no" class="form-control" value="{{ $card->quotation_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Quotation Date</label>
                    <input type="date" id="quotationDate" name="quotation_date" class="form-control" value="{{ $card->quotation_date }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RFQ No</label>
                    <input type="text" id="rfqNo" name="rfq_no" class="form-control" value="{{ $card->rfq_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">RFQ Date</label>
                    <input type="date" id="rfqDate" name="rfq_date" class="form-control" value="{{ $card->rfq_date }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Part No</label>
                    <input type="text" id="partNo" name="part_no" class="form-control" value="{{ $card->part_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Project Material No</label>
                    <input type="text" id="project-materialNo" name="project_material_no" class="form-control" value="{{ $card->project_material_no }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Drawing No</label>
                    <input type="text" id="drawingNo" name="drawing_no" class="form-control" value="{{ $card->drawing_no }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Drawing Revision</label>
                    <input type="text" id="drawingRev" name="drawing_rev" class="form-control" value="{{ $card->drawing_rev }}">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Product Type <span class="text-danger">*</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-3 mb-3">
                    <label class="small font-weight-bold">Project Start Date <span class="text-danger">*</span></label>
                    <input type="datetime-local" id="projectStart" name="project_start_date" class="form-control" required
                        value="{{ old('project_start_date', \Carbon\Carbon::parse($card->project_start_date)->format('Y-m-d\TH:i')) }}">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="small font-weight-bold">Description</label>
                    <textarea id="description" name="description" rows="2" class="form-control">{{ $card->description }}</textarea>
                </div>
            </div>

            <hr>

            <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-tasks mr-2"></i>Process Details</h6>

            <div class="table-responsive">
                <table id="processTable" class="table table-bordered table-sm">
                    <thead class="thead-light">
                        <tr>
                            <th width="50">Sl No</th>
                            <th>Process</th>
                            <th width="120">Source</th>
                            <th>Previous Process</th>
                            <th>Machine</th>
                            <th>Operator</th>
                            <th width="150">Cycle Time (h:m)</th>
                            <th width="50"></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>
                                </select>
                                <input type="text" name="processes[{{ $i }}][process_other]" class="form-control mt-1 process-other" style="display:none;" placeholder="Other process" value="{{ $process->process_other ?? '' }}">
                            </td>
                            <td>
                                <div class="form-check form-check-inline">
                                    <input type="radio" name="processes[{{ $i }}][source]" value="inhouse" class="form-check-input" @if ($process->source == 'inhouse') checked @endif>
                                    <label class="form-check-label small">Inhouse</label>
                                </div>
                                <div class="form-check form-check-inline">
                                    <input type="radio" name="processes[{{ $i }}][source]" value="outsourced" class="form-check-input" @if ($process->source == 'outsourced') checked @endif>
                                    <label class="form-check-label small">Outsourced</label>
                                </div>
                            </td>
                            <td class="prev-process-cell"></td>
                            <td>
                                <select name="processes[{{ $i }}][machine]" class="form-control machine-select">
                                    <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">
                                    <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="H" min="0" step="1" style="width: 45%;" value="{{ $process->cycle_hours }}">
                                    <span class="mx-1">:</span>
                                    <input type="number" name="processes[{{ $i }}][cycle_minutes]" class="form-control" placeholder="M" min="0" max="59" step="1" style="width: 45%;" value="{{ $process->cycle_minutes }}">
                                </div>
                            </td>
                            <td>
                                <button class="btn btn-danger btn-sm" type="button" onclick="deleteProcessRow(this)"><i class="fa fa-trash"></i></button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <div class="mb-3">
                <button type="button" class="btn btn-primary btn-sm" id="addProcessRowBtn">
                    <i class="fa fa-plus mr-1"></i> Add Row
                </button>
            </div>

            <hr>

            <div class="d-flex justify-content-end">
                <button type="submit" id="save-RC" class="btn btn-success btn-sm mr-2">
                    <i class="fa fa-save mr-1"></i> Update
                </button>
                <a href="{{ route('superadmin.routecard.details') }}" class="btn btn-outline-secondary btn-sm">
                    <i class="fa fa-arrow-left mr-1"></i> Back
                </a>
            </div>
        </form>
    </div>
</div>

@endsection

@section('scripts')
<script>
window.machines = @json($machines->map(function($m) use ($machineAvailability) {
    return [
        'id' => (string)$m->machine_id,
        'label' => $m->machine_id . ' (' . ($machineAvailability[$m->machine_id] ?? 'Available now') . ')'
    ];
})->values());
window.operators = @json($employees->map(function($e) use ($operatorAvailability) {
    return [
        'id' => (string)$e->id,
        'label' => $e->name . ' (' . ($operatorAvailability[$e->id] ?? 'Available now') . ')'
    ];
})->values());
window.processAssignments = @json($processAssignments);
window.productTypeNameToId = @json($productTypeNameToId);

let rowIdx = {{ count($card->processes) }};
let productTypeProcesses = {};

function fillCompanyDetails(select) {
    const selected = select.options[select.selectedIndex];
    document.getElementById('companyAddress').value = selected.getAttribute('data-address') || '';
    document.getElementById('companyGSTN').value = selected.getAttribute('data-gst') || '';
    document.getElementById('companyEmail').value = selected.getAttribute('data-email') || '';
    document.getElementById('companyPhone').value = selected.getAttribute('data-mobile') || '';
}

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);
        }
    });
    updateMachineAndOperatorDropdowns();
}

function updateProcessDropdowns(productType) {
    if (!productType) {
        fillProcessDropdowns([]);
        return;
    }
    if (productTypeProcesses[productType]) {
        fillProcessDropdowns(productTypeProcesses[productType]);
        return;
    }
    $.get("{{ url('superadmin/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();
    updateMachineAndOperatorDropdowns();
});

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 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-1 process-other" style="display:none;" placeholder="Other process">
            </td>
            <td>
                <div class="form-check form-check-inline">
                    <input type="radio" name="processes[${rowIdx}][source]" value="inhouse" class="form-check-input" checked>
                    <label class="form-check-label small">Inhouse</label>
                </div>
                <div class="form-check form-check-inline">
                    <input type="radio" name="processes[${rowIdx}][source]" value="outsourced" class="form-check-input">
                    <label class="form-check-label small">Outsourced</label>
                </div>
            </td>
            <td class="prev-process-cell"></td>
            <td>
                <select name="processes[${rowIdx}][machine]" class="form-control machine-select">
                    <option value="">Select Machine</option>
                </select>
            </td>
            <td>
                <select name="processes[${rowIdx}][operator]" class="form-control operator-select">
                    <option value="">Select Operator</option>
                </select>
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <input type="number" name="processes[${rowIdx}][cycle_hours]" class="form-control" placeholder="H" min="0" step="1" style="width: 45%;">
                    <span class="mx-1">:</span>
                    <input type="number" name="processes[${rowIdx}][cycle_minutes]" class="form-control" placeholder="M" min="0" max="59" step="1" style="width: 45%;">
                </div>
            </td>
            <td>
                <button class="btn btn-danger btn-sm" 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();
        updateMachineAndOperatorDropdowns();
    } else {
        alert('At least one process row is required!');
    }
}

function updateMachineAndOperatorDropdowns() {
    $('.process-select').each(function() {
        let $row = $(this).closest('tr');
        let processName = $(this).val();
        let productTypeName = $('#productType').val();
        let productTypeId = window.productTypeNameToId[productTypeName];

        let key = productTypeId + '|' + processName;
        let assignments = window.processAssignments[key] || { machines: [], operators: [] };

        let $machineSel = $row.find('.machine-select');
        let $operatorSel = $row.find('.operator-select');

        let currentMachine = $machineSel.val();
        let currentOperator = $operatorSel.val();

        $machineSel.empty().append('<option value="">Select Machine</option>');
        $operatorSel.empty().append('<option value="">Select Operator</option>');

        assignments.machines.forEach(function(id) {
            let machine = window.machines.find(m => m.id == id);
            let label = machine ? machine.label : id;
            $machineSel.append(`<option value="${id}">${label}</option>`);
        });

        if (currentMachine && $machineSel.find(`option[value="${currentMachine}"]`).length) {
            $machineSel.val(currentMachine);
        } else {
            $machineSel.val('');
        }

        assignments.operators.forEach(function(id) {
            let operator = window.operators.find(o => o.id == id);
            let label = operator ? operator.label : id;
            $operatorSel.append(`<option value="${id}">${label}</option>`);
        });

        if (currentOperator && $operatorSel.find(`option[value="${currentOperator}"]`).length) {
            $operatorSel.val(currentOperator);
        } else {
            $operatorSel.val('');
        }
    });
}

$(document).on('change', '#productType, .process-select', function() {
    updateProcessDropdowns($('#productType').val());
});

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