@extends('layouts.dashboard.adminapp')

@section('title', 'Manufacturing Plan Board')

@section('content')
    <meta name="csrf-token" content="{{ csrf_token() }}">
{{-- Success Message --}}
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        {{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

{{-- Error Message (Controller or manual error) --}}
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        {{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

{{-- Validation Errors --}}
@if ($errors->any())
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <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="container-fluid py-2">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="h5 mb-0 text-gray-800">Manufacturing Plan Board</h2>
            <a href="{{ url('admin/manufacturing/planning') }}" class="btn btn-secondary btn-sm">&larr; Back</a>
        </div>
        <!-- RC Header -->
        <div id="rcHeader" class="mb-4"></div>
        <!-- The board -->
        <div class="board"></div>
    </div>

    <!-- Edit/Add Modal -->
    <div class="modal fade" id="processModal" tabindex="-1" role="dialog" aria-labelledby="processModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="processForm" class="modal-content">
                
                <div class="modal-header">
                    <h5 class="modal-title" id="processModalLabel">Edit Process</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body row">
                    <div id="processMessage" class="col-12" style="display:none"></div>
                    <input type="hidden" id="process_id">
                    <div class="form-group col-md-12">
                        <label for="process_name">Process</label>
                        <select class="form-control" id="process_name" required>
                            <!-- Options populated by JS based on RC product type -->
                        </select>
                    </div>
                    <div class="form-group col-md-12">
                        <label for="description">Description</label>
                        <input type="text" class="form-control" id="description">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="machine">Machine</label>
                        <select class="form-control" id="machine">
                            <!-- Options populated by JS -->
                        </select>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="operator">Operator</label>
                        <select class="form-control" id="operator" required>
                            <option value="">Select Operator</option>
                            @foreach ($operators as $oid => $oname)
                                <option value="{{ $oid }}">{{ $oname }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="form-group col-md-6">
                        <label for="ct_hours">Cycle Time (Hours)</label>
                        <input type="number" class="form-control" id="ct_hours" min="0" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="ct_minutes">Cycle Time (Minutes)</label>
                        <input type="number" class="form-control" id="ct_minutes" min="0" max="59" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="start_date">Expected Start Date</label>
                        <input type="datetime-local" class="form-control" id="start_date" required>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="end_date">Expected End Date</label>
                        <input type="datetime-local" class="form-control" id="end_date" readonly>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="source">Source</label>
                        <select class="form-control" id="source">
                            <option value="inhouse">Inhouse</option>
                            <option value="outsourced">Outsourced</option>
                        </select>
                    </div>
                    <div class="form-group col-md-6">
                        <label for="previous_process">Previous Process</label>
                        <select class="form-control" id="previous_process" name="previous_process_id">
                            <option value="">None</option>
                            <!-- JS will populate options -->
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="saveProcessBtn">Save changes</button>
                </div>
            </form>
        </div>
    </div>
@endsection

@push('scripts')
    <!-- jQuery and Bootstrap (if not loaded globally) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
    <script>
window.OPERATOR_MAP = @json($operators);
window.MACHINE_AVAILABILITY = @json($machineAvailability);
window.OPERATOR_AVAILABILITY = @json($operatorAvailability);
let productType = null; // Will be set when loading RC
let machineList = @json(\App\Models\Machines::pluck('machine_id')->toArray());
let processes = [];
let currentRC = null;

const RCid = @json($id ?? request()->route('id'));
if (!RCid) window.location.href = "{{ url('admin/manufacturing/planning') }}";

// --- Utility: Format Dates ---
function formatDateLocal(dateStr) {
    if (!dateStr) return '-';
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return '-';
    return d.toLocaleString('en-GB', {
        day: '2-digit', month: '2-digit', year: 'numeric',
        hour: '2-digit', minute: '2-digit'
    });
}

// --- Fetch processes for given product type ---
function fetchAndSetProcesses(selected) {
    if (!productType) {
        console.warn("fetchAndSetProcesses: productType is missing!", productType);
        $("#process_name").html('<option value="">No process (product type missing)</option>');
        return;
    }
    console.log("Fetching processes for productType:", productType);
    $.get("{{url('/admin/routecard/get-process-list')}}", { product_type: productType }, function(data) {
        let html = '<option value="">Select Process</option>';
        if (data && data.length) {
            data.forEach(p => {
                html += `<option value="${p}" ${selected === p ? "selected" : ""}>${p}</option>`;
            });
            html += '<option value="Other" '+(selected==="Other"?"selected":"")+'>Other</option>';
        } else {
            html += '<option value="Other" '+(selected==="Other"?"selected":"")+'>Other</option>';
        }
        $("#process_name").html(html);
        // If the value didn't match, reset
        if (selected && !data.includes(selected) && selected !== "Other") {
            $("#process_name").val("");
        }
    }).fail(function(xhr) {
        console.error("Failed to fetch process list:", xhr);
        $("#process_name").html('<option value="">Failed to load</option>');
    });
}

// --- Populate machines dropdown ---
function populateMachineDropdown(selected) {
    let html = '<option value="">Select Machine</option>';
    machineList.forEach(m => {
        let avail = (window.MACHINE_AVAILABILITY && window.MACHINE_AVAILABILITY[m]) ? (' - ' + window.MACHINE_AVAILABILITY[m]) : '';
        html += `<option value="${m}" ${selected === m ? "selected" : ""}>${m}${avail}</option>`;
    });
    $("#machine").html(html);
}
function populateOperatorDropdown(selected) {
    let html = '<option value="">Select Operator</option>';
    Object.entries(window.OPERATOR_MAP).forEach(([oid, oname]) => {
        let avail = (window.OPERATOR_AVAILABILITY && window.OPERATOR_AVAILABILITY[oid]) ? (' - ' + window.OPERATOR_AVAILABILITY[oid]) : '';
        html += `<option value="${oid}" ${selected == oid ? "selected" : ""}>${oname}${avail}</option>`;
    });
    $("#operator").html(html);
}
// --- Populate previous process options ---
function populatePreviousProcessOptions(currentId) {
    let options = `<option value="">None</option>`;
    processes.forEach(proc => {
        if (!currentId || proc.id != currentId) {
            options += `<option value="${proc.id}">${proc.process || ('Process #' + proc.id)}</option>`;
        }
    });
    $("#previous_process").html(options);
}
let previousMachine = null;
let previousOperator = null;

function setOutsourcedUI(isOutsourced) {
    const $machine = $("#machine");
    const $operator = $("#operator");
    if (isOutsourced) {
        // Store previous values
        previousMachine = $machine.val();
        previousOperator = $operator.val();
        // Disable and clear
        $machine.prop("disabled", true).val("");
        $operator.prop("disabled", true).val("");
    } else {
        $machine.prop("disabled", false);
        $operator.prop("disabled", false);
        // Autofill previous values if available
        if (previousMachine) $machine.val(previousMachine);
        if (previousOperator) $operator.val(previousOperator);
    }
}

$("#source").on("change", function () {
    setOutsourcedUI($(this).val() === "outsourced");
});
// --- Edit process handler ---
// function editProcess(id) {
//     let proc = processes.find(p => p.id === id);
//     if (!proc) return;
//     currentRC = currentRC || {};
//     productType = currentRC.product_type || (typeof routeCard !== 'undefined' ? routeCard.product_type : null);

//     console.log("Edit process: productType =", productType, "Selected process:", proc.process);

//     populatePreviousProcessOptions(proc.id);
//     fetchAndSetProcesses(proc.process);

//     populateMachineDropdown(proc.machine);      // <--- already here
//     populateOperatorDropdown(proc.operator);    // <--- add this line!

//     $("#operator").val(proc.operator || "");
//     $("#source").val(proc.source || "inhouse");
//     $("#processModalLabel").text('Edit Process');
//     $("#process_id").val(proc.id);
//     $("#description").val(proc.description || '');
//     $("#ct_hours").val(proc.ct_hours ?? proc.cycle_hours ?? '');
//     $("#ct_minutes").val(proc.ct_minutes ?? proc.cycle_minutes ?? '');
//     $("#start_date").val(proc.start_date ? proc.start_date.substring(0, 16) : '');
//     $("#end_date").val(proc.end_date ? proc.end_date.substring(0, 16) : '');
//     $("#previous_process").val(proc.previous_process_id || '');
//     // Save previous machine/operator for autofill
//     previousMachine = proc.machine || null;
//     previousOperator = proc.operator || null;
//     setOutsourcedUI((proc.source || "inhouse") === "outsourced");
//     $("#processModal").modal('show');
// }
function editProcess(id) {
    let proc = processes.find(p => p.id === id);
    if (!proc) return;
    currentRC = currentRC || {};
    productType = currentRC.product_type || (typeof routeCard !== 'undefined' ? routeCard.product_type : null);

    populatePreviousProcessOptions(proc.id);
    fetchAndSetProcesses(proc.process);

    populateMachineDropdown(proc.machine);
    populateOperatorDropdown(proc.operator);

    $("#operator").val(proc.operator || "");
    $("#source").val(proc.source || "inhouse");
    $("#processModalLabel").text('Edit Process');
    $("#process_id").val(proc.id);
    $("#description").val(proc.description || '');
    $("#ct_hours").val(proc.ct_hours ?? proc.cycle_hours ?? '');
    $("#ct_minutes").val(proc.ct_minutes ?? proc.cycle_minutes ?? '');
    $("#start_date").val(proc.start_date ? proc.start_date.substring(0, 16) : '');
    $("#end_date").val(proc.end_date ? proc.end_date.substring(0, 16) : '');
    $("#previous_process").val(proc.previous_process_id || '');
    previousMachine = proc.machine || null;
    previousOperator = proc.operator || null;
    setOutsourcedUI((proc.source || "inhouse") === "outsourced");

    // === NEW: Set min date for Expected Start Date ===
    let minDate = '';
if (proc.previous_process_id) {
    let prev = processes.find(p => String(p.id) === String(proc.previous_process_id));
    if (prev && prev.end_date) {
        const d = new Date(prev.end_date);
        if (!isNaN(d.getTime())) {
            let yyyy = d.getFullYear();
            let mm = String(d.getMonth() + 1).padStart(2, '0');
            let dd = String(d.getDate()).padStart(2, '0');
            let hh = String(d.getHours()).padStart(2, '0');
            let min = String(d.getMinutes()).padStart(2, '0');
            minDate = `${yyyy}-${mm}-${dd}T${hh}:${min}`;
        }
    }
} else {
    // First process: min is RC project_start_date
    if (currentRC && currentRC.project_start_date) {
        const d = new Date(currentRC.project_start_date);
        if (!isNaN(d.getTime())) {
            let yyyy = d.getFullYear();
            let mm = String(d.getMonth() + 1).padStart(2, '0');
            let dd = String(d.getDate()).padStart(2, '0');
            let hh = String(d.getHours()).padStart(2, '0');
            let min = String(d.getMinutes()).padStart(2, '0');
            minDate = `${yyyy}-${mm}-${dd}T${hh}:${min}`;
        }
    }
}
if (minDate) {
    $("#start_date").attr("min", minDate);
} else {
    $("#start_date").removeAttr("min");
}
    $("#processModal").modal('show');
}

// --- Fetch all processes for RC ---
function fetchProcesses() {
    fetch(`{{ url('admin/routecard') }}/${RCid}/processes`)
        .then(res => res.json())
        .then(rc => {
            currentRC = rc;
            productType = rc.product_type; // SET IT!
            processes = rc.processes || [];
            window.RC_PROJECT_START_DATE = rc.project_start_date;
            renderRCHeader(rc);
            renderBoard(processes);
        });
}

// --- Recalculate End Date on inputs change ---
// $("#start_date, #ct_hours, #ct_minutes").on("input change", function() {
//     calculateEndDate();
// });

function calculateEndDate() {
    let startVal = $("#start_date").val();
    let hours = parseInt($("#ct_hours").val()) || 0;
    let mins = parseInt($("#ct_minutes").val()) || 0;

    if (!startVal) { $("#end_date").val(""); return; }
    let startDate = new Date(startVal);
    if (isNaN(startDate.getTime())) { $("#end_date").val(""); return; }

    startDate.setHours(startDate.getHours() + hours);
    startDate.setMinutes(startDate.getMinutes() + mins);

    let yyyy = startDate.getFullYear();
    let mm = String(startDate.getMonth() + 1).padStart(2, '0');
    let dd = String(startDate.getDate()).padStart(2, '0');
    let hh = String(startDate.getHours()).padStart(2, '0');
    let min = String(startDate.getMinutes()).padStart(2, '0');
    let val = `${yyyy}-${mm}-${dd}T${hh}:${min}`;

    $("#end_date").val(val);
}

// --- Submit process form (add/edit) ---
$("#processForm").submit(function(e) {
    if ($("#source").val() === "outsourced") {
        $("#machine").val("");
        $("#operator").val("");
    }
    e.preventDefault();

    let data = {
        route_card_id: RCid,
        process: $("#process_name").val(),
        description: $("#description").val(),
        machine: $("#machine").val(),
        operator: $("#operator").val(),
        ct_hours: $("#ct_hours").val(),
        ct_minutes: $("#ct_minutes").val(),
        start_date: $("#start_date").val(),
        end_date: $("#end_date").val(),
        source: $("#source").val(),
        previous_process_id: $("#previous_process").val() || null,
    };
    let process_id = $("#process_id").val();
    let method = process_id ? 'PUT' : 'POST';
    let url = process_id ?
        `{{ url('admin/routecard/process-reschedule') }}/${process_id}` :
        `{{ url('admin/routecard/process') }}`;

    $("#saveProcessBtn").prop('disabled', true);

    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        body: JSON.stringify(data)
    })
    .then(res => res.json())
        .then(resp => {
    $("#saveProcessBtn").prop('disabled', false);
    if (resp.success) {
        alert(resp.message || "Process updated successfully!");
        $("#processModal").modal('hide');
        fetchProcesses();
    } else {
        alert(resp.message || "Failed to save process.");
    }
})
    .catch(() => {
        $("#saveProcessBtn").prop('disabled', false);
        $("#processMessage")
            .addClass('alert alert-danger')
            .text("Failed to save process due to network or server error.")
            .show();
    });

});

function deleteProcess(id) {
    if (!confirm("Delete this process?")) return;
    fetch(`{{ url('admin/routecard/process') }}/${id}`, {
        method: "DELETE",
        headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
    })
    .then(res => res.json())
    .then(resp => {
        if (resp.success) {
            fetchProcesses();
        } else {
            alert(resp.message || "Delete failed.");
        }
    })
    .catch(() => alert("Delete failed."));
}

// --- Render RC Header and Board (unchanged from your code) ---

function statusBadge(status) {
    status = status ? status.toLowerCase() : '';
    if (status === 'approved') return `<span class="badge badge-success">Approved</span>`;
    if (status === 'pending') return `<span class="badge badge-warning">Pending</span>`;
    if (status === 'rejected') return `<span class="badge badge-danger">Rejected</span>`;
    return `<span class="badge badge-secondary">${status}</span>`;
}

function renderRCHeader(rc) {
    let html = `
    <div class="card shadow-sm mb-3 px-3 py-2" style="background:#e3f0fc;border-radius:14px;">
        <div class="d-flex flex-wrap gap-4 align-items-center" style="font-size:1.1rem;">
            <div><strong>RC No:</strong> <a style="color:#1477d5;text-decoration:underline;" href="javascript:void(0)">${rc.route_no}</a></div>
            <div><strong>Company:</strong> ${rc.company_name || '-'}</div>
            <div><strong>RC Date:</strong> ${rc.route_date || '-'}</div>
            <div><strong>Status:</strong> ${statusBadge(rc.status)}</div>
            ${rc.approved_by ? `<div><strong>Approved By:</strong> ${rc.approved_by}</div>` : ''}
            ${rc.approved_at ? `<div><strong>Approved At:</strong> ${formatDateLocal(rc.approved_at)}</div>` : ''}
        </div>
    </div>
    `;
    $("#rcHeader").html(html);
}

function renderBoard(processArr) {
    let board = $(".board");
    board.html('');
    let html = `
    <div class="card mp-task-list" style="background:#f7fbfe;border-radius:16px;box-shadow:0 2px 8px #c7daf6;">
        <div class="header d-flex justify-content-between align-items-center mb-3">
            <h4 style="font-weight:600;font-size:1.1rem;">Processes For RC: <span style="color:#007bff;">${currentRC.route_no}</span></h4>
        </div>
        <ul class="mp-list list-unstyled" id="process-list" style="margin:0;"></ul>
    </div>
    `;
    board.append(html);

    if (!processArr.length) {
        $('#process-list').html(
            '<li class="text-secondary py-4 text-center" style="background:#eaf6fd;border-radius:10px;">No processes found. Click "Add Process".</li>'
        );
        return;
    }
    processArr.forEach(proc => {
        $('#process-list').append(processListItem(proc));
    });
}

function processListItem(proc) {
    let ct_hours = proc.ct_hours ?? proc.cycle_hours ?? 0;
    let ct_minutes = proc.ct_minutes ?? proc.cycle_minutes ?? 0;
    let ctStr = (ct_hours || ct_minutes) ? `${ct_hours}h ${ct_minutes}m` : '-';

    // Operator Name
    let operatorName = '-';
    if (proc.operator) {
        operatorName = (window.OPERATOR_MAP && window.OPERATOR_MAP[proc.operator]) ? window.OPERATOR_MAP[proc.operator] : proc.operator;
    }

    // Start and End Date (format if exists)
    let sd = (proc.start_date && proc.start_date !== '0000-00-00 00:00:00') ? formatDateLocal(proc.start_date) : '-';
    let ed = (proc.end_date && proc.end_date !== '0000-00-00 00:00:00') ? formatDateLocal(proc.end_date) : '-';

    // Previous Process Name
    //<button class="btn btn-sm btn-danger" onclick="deleteProcess(${proc.id})" title="Delete"><i class="fas fa-trash"></i></button>
    let previousName = '-';
    if (proc.previous_process_id) {
        let prev = processes.find(p => String(p.id) === String(proc.previous_process_id));
        previousName = prev ? (prev.process || ('Process #' + prev.id)) : '-';
    }

    return `
<li class="mp-task-item mb-3 shadow-sm p-3" id="proc-${proc.id}" style="background:#eaf6fd;border-radius:10px;position:relative;">
    <div class="d-flex justify-content-between align-items-center mb-2">
        <span style="font-size:1.08rem;font-weight:600;">${proc.process || '-'}</span>
        <div>
            <button class="btn btn-sm btn-warning mr-1" onclick="editProcess(${proc.id})" title="Edit"><i class="fas fa-edit"></i></button>
            
        </div>
    </div>
    <div class="mb-1"><span class="text-muted">Description:</span> ${proc.description || '-'}</div>
    <div class="mb-1"><span class="text-muted">Machine:</span> ${proc.machine || '-'} <span class="ml-3 text-muted">Operator:</span> ${operatorName}</div>
    <div class="mb-1"><span class="text-muted">Cycle Time:</span> ${ctStr}</div>
    <div class="mb-1"><span class="text-muted">Start:</span> ${sd} <span class="ml-3 text-muted">End:</span> ${ed}</div>
    <div class="mb-1"><span class="text-muted">Source:</span> ${proc.source || '-'} <span class="ml-3 text-muted">Previous:</span> ${previousName}</div>
</li>
    `;
}

// --- Init ---
$(document).ready(function() {
    fetchProcesses();
    $('#processModal').on('hidden.bs.modal', function() {
        $('#processForm')[0].reset();
        $("#process_name").html('<option value="">Select Process</option>');
        $("#machine").html('<option value="">Select Machine</option>');
        $("#start_date").removeAttr("min");  // <--- reset min
         $("#processMessage").hide().removeClass('alert alert-success alert-danger').text('');
    });
});

</script>


    <style>
        .board {
            min-height: 250px;
        }

        .mp-task-list {
            box-shadow: 0 2px 8px rgba(80, 102, 144, 0.09);
            padding: 2rem 2rem 1.2rem 2rem;
        }

        .mp-task-item {
            background: #eaf6fd;
        }

        .mp-task-item strong {
            font-size: 1.09rem;
        }
    </style>
@endpush
