<?php
/**
 * gantt_chart.php  (was: the file-1 admin Gantt include)
 * =====================================================================
 * CHANGES FROM ORIGINAL:
 *   - All duplicated scheduling functions removed; now includes
 *     cnc_scheduler_lib.php instead.
 *   - FIX: the "overdue task" batch loop below queried
 *       cnc_part_count_log WHERE cnc_machine_table_id = <row id>
 *     but cnc_part_count_log.cnc_machine_table_id actually stores
 *     manuf_id (confirmed by extensive comments in the ajax files).
 *     $okQty was therefore almost always wrong (usually 0), so
 *     "remaining qty" for an overdue-but-in-progress job was computed
 *     as if nothing had been produced. Fixed by selecting v.manuf_id
 *     and keying the count-log lookup off it.
 *   - The setup_hours=0 reset for overdue jobs is preserved (it's a
 *     business-rule decision, not something to silently change) but is
 *     now clearly flagged — confirm this is actually desired before
 *     relying on it, since it means an overdue job never gets budgeted
 *     re-setup time.
 *   - handleMachineBreakdowns() now also mirrors into
 *     cnc_machine_breakdown_log so the shop-floor tablet's
 *     isMachineInBreakdown() check (which only reads that table) picks
 *     up breakdowns started from this admin page. See cnc_scheduler_lib.php
 *     header comment for the full rationale.
 *   - Uses cnc_fullRescheduleMachine() instead of manually repeating the
 *     5-call chain everywhere.
 *
 * FIELDS DROPPED FROM QUERIES (unreferenced anywhere in the 4 source
 * files — see CHANGELOG.md before dropping the columns themselves):
 *   dual_table_break_id, linked_task_id, is_shadow_break, shadow_of
 * =====================================================================
 */

$file = __DIR__ . '/cnc_scheduler_lib.php';

if (file_exists($file)) {
    require_once $file;
} else {
    die('cnc_scheduler_lib.php not found.');
}

$now   = date('Y-m-d H:i:s');
$today = date('Y-m-d');

/* ---------------------------------------------------------------------
 * PASS 1: recompute remaining hours for every overdue-but-unfinished task
 * ------------------------------------------------------------------- */
$query = "
    SELECT
        v.id,
        v.manuf_id,
        v.machine_id,
        v.table_id,
        v.total_hours,
        v.start_date,
        v.is_break,
        m.total_hours AS hours,
        m.work_order_id,
        m.part_id,
        m.quantity AS total_quantity
    FROM cnc_machine_table AS v
    LEFT JOIN manufacture_machine_table AS m
        ON v.work_order_id = m.work_order_id
       AND v.part_id       = m.part_id
    WHERE v.finished = 0 AND v.is_break = 0
      AND v.start_date < '$today'
";

$result = mysqli_query($conn, $query);
$machinesToReschedule = [];

while ($row = mysqli_fetch_assoc($result)) {

    $cncId       = intval($row['id']);
    $manufId     = intval($row['manuf_id']);   // FIX: this, not $cncId, is the key used by cnc_part_count_log
    $machineId   = intval($row['machine_id']);
    $totalQty    = floatval($row['total_quantity']);
    $hours       = floatval($row['hours']);
    $isBreak     = intval($row['is_break']);

    $uph = ($hours > 0 && $totalQty > 0) ? ($totalQty / $hours) : 0;
    if ($uph <= 0 || $totalQty <= 0) {
        continue; // safety — nothing sensible to schedule
    }

    // FIX: query by manuf_id, matching every other consumer of this table.
    $okQtyResult = mysqli_query($conn, "
        SELECT SUM(quantity) AS ok_qty
        FROM cnc_part_count_log
        WHERE cnc_machine_table_id = $manufId
          AND type = 'ok'
    ");
    $okQtyRow = mysqli_fetch_assoc($okQtyResult);
    $okQty    = floatval($okQtyRow['ok_qty'] ?? 0);

    $remainingQty   = max(0, $totalQty - $okQty);
    $remainingHours = ($uph > 0) ? ($remainingQty / $uph) : 0;

    // NOTE (business rule, unchanged from original — flagged, not silently
    // altered): overdue jobs have setup_hours zeroed out here. If a machine
    // has sat idle past an overdue job's start date, this assumes no fresh
    // setup will be needed when it resumes. Revisit if that's not actually
    // true for your shop floor.
    mysqli_query($conn, "
        UPDATE cnc_machine_table
        SET
            original_total_hours = $remainingHours,
            total_hours_update   = $remainingHours,
            setup_hours          = 0,
            finished              = " . ($isBreak == 1 ? 1 : 'finished') . "
        WHERE id = $cncId
    ");

    $machinesToReschedule[$machineId] = true;
}

foreach (array_keys($machinesToReschedule) as $machineId) {
    cnc_fullRescheduleMachine($conn, $machineId);
}

/* ---------------------------------------------------------------------
 * PASS 2: machine breakdowns (machine_type = 3 machines)
 * ------------------------------------------------------------------- */
function handleMachineBreakdowns_admin($conn) {
    $currentTime = date('Y-m-d H:i:s');
    $currentTs   = strtotime($currentTime);
    $todayTs     = strtotime(date('Y-m-d 00:00:00'));

    $breakdownResult = mysqli_query($conn, "
        SELECT mb.*, sdt.resource_code
        FROM machine_breakdown mb
        JOIN station_detail_table sdt ON mb.machine_id = sdt.id
        WHERE mb.breakdown_start <= '$currentTime'
          AND mb.is_active = 1
    ");
    if (!$breakdownResult) return;

    while ($breakdown = mysqli_fetch_assoc($breakdownResult)) {
        $machineId        = (int) $breakdown['machine_id'];
        $breakdownId      = (int) $breakdown['id'];
        $breakdownStartTs = strtotime($breakdown['breakdown_start']);

        $breakdownHours = ($breakdownStartTs >= $todayTs)
            ? max(0, ($currentTs - $breakdownStartTs) / 3600)
            : max(0, ($currentTs - $todayTs) / 3600);

        mysqli_query($conn, "
            UPDATE machine_breakdown
            SET breakdown_hours = $breakdownHours, updated_at = '$currentTime'
            WHERE id = $breakdownId
        ");

        $tasksResult = mysqli_query($conn, "
            SELECT id, total_hours, setup_hours, total_hours_update, breakdown_hours
            FROM cnc_machine_table
            WHERE machine_id = $machineId
              AND is_breakdown_affected = 1
              AND is_break = 0
        ");
        if ($tasksResult) {
            while ($task = mysqli_fetch_assoc($tasksResult)) {
                $taskId          = (int) $task['id'];
                $prevSetupHours  = (float) $task['setup_hours'];
                $prevUpdateHours = (float) $task['total_hours_update'];
                $newTotalHours   = $prevSetupHours + $prevUpdateHours + $breakdownHours;

                mysqli_query($conn, "
                    UPDATE cnc_machine_table
                    SET original_total_hours = $newTotalHours, breakdown_hours = $breakdownHours
                    WHERE id = $taskId
                ");
            }
        }
    }
}

$breakdownMachineQuery = mysqli_query($conn, "
    SELECT DISTINCT mb.machine_id, sd.resource_code
    FROM machine_breakdown mb
    JOIN station_detail_table sd ON mb.machine_id = sd.id
    WHERE sd.machine_type = 3
");

if ($breakdownMachineQuery && mysqli_num_rows($breakdownMachineQuery) > 0) {
    handleMachineBreakdowns_admin($conn);
    while ($machineRow = mysqli_fetch_assoc($breakdownMachineQuery)) {
        $machineId = (int) $machineRow['machine_id'];
        cnc_fullRescheduleMachine($conn, $machineId);
    }
}
?>

<div class="container-fluid" style="background-color: #ffe6e6; height: 100vh;">

 <div class="split-container">
        <div class="split-panel" id="left-panel">
            <style>
                .scrollable-section {
                    max-height: 400px;
                    overflow-y: auto;
                    border: 1px solid #dee2e6;
                    border-radius: 5px;
                    background-color: #fff;
                }
                .spinner-border-sm {
                    width: 1rem;
                    height: 1rem;
                    border-width: 0.15em;
                }
                .table td, .table th {
                    vertical-align: middle !important;
                    text-align: center;
                }
                .table .form-check-input {
                    margin: 0 auto;
                    display: block;
                    position: relative;
                    top: 0;
                    transform: translateY(0);
                    width: 24px;
                    height: 24px;
                    cursor: pointer;
                    transition: all 0.2s ease;
                }
                .table .form-check-input:hover {
                    transform: scale(1.1);
                    box-shadow: 0 0 8px rgba(0, 123, 255, 0.5);
                }
                .table .form-check-input:checked {
                    background-color: #0d6efd;
                    border-color: #0d6efd;
                }
                .table .form-check-input:focus {
                    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
                }
                .sortable {
                    cursor: pointer;
                    user-select: none;
                    position: relative;
                    padding-right: 20px !important;
                }
                .sortable:hover {
                    background-color: #e9ecef !important;
                }
                .sortable::after {
                    content: '⇅';
                    position: absolute;
                    right: 8px;
                    opacity: 0.3;
                    font-size: 12px;
                }
                .sortable.asc::after {
                    content: '↑';
                    opacity: 1;
                }
                .sortable.desc::after {
                    content: '↓';
                    opacity: 1;
                }
                .select2-container--open {
                    z-index: 9999 !important;
                }
                .select2-container--default .select2-selection--single .select2-selection__rendered {
                    white-space: normal;
                    overflow: visible;
                    text-overflow: unset;
                }
            </style>

            <div class="container mt-4">
                <h3 class="mb-3" style="background-color: #f8d7da;">Ready Orders</h3>
                <form id="workOrderForm">
                    <div id="ready-orders-container" class="scrollable-section">
                        <div class="text-center p-3">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p>Loading ready orders...</p>
                        </div>
                    </div>
                    <div class="mt-3 text-end">
                        <button type="button" class="btn btn-primary" id="showSelectedBtn" onclick="showSelectedWorkOrders()">
                            <span class="btn-text">Show Selected</span>
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        </button>
                    </div>
                </form>
            </div>

            <div class="container mt-4">
                <h3 class="mb-3" style="background-color: #ffc107;">WIP VAC</h3>
                <form id="wipVacForm">
                    <div id="wip-vac-container" class="scrollable-section">
                        <div class="text-center p-3">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p>Loading WIP VAC orders...</p>
                        </div>
                    </div>
                    <div class="mt-3 text-end">
                        <button type="button" class="btn btn-warning" id="showSelectedWipBtn" onclick="showSelectedWipOrders()">
                            <span class="btn-text">Show Selected</span>
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        </button>
                    </div>
                </form>
            </div>

            <div class="container mt-4">
                <h3 class="mb-3" style="background-color: #e0e0e0;">Pending Orders</h3>
                <form id="pendingOrdersForm">
                    <div id="pending-orders-container" class="scrollable-section">
                        <div class="text-center p-3">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p>Loading pending orders...</p>
                        </div>
                    </div>
                    <div class="mt-3 text-end">
                        <button type="button" class="btn btn-secondary" id="showSelectedPendingBtn" onclick="showSelectedPendingOrders()">
                            <span class="btn-text">Show Selected</span>
                            <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                        </button>
                    </div>
                </form>
            </div>

            <script>
                let machineList = [];

                function loadWorkOrders() {
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_get_workorders&action=get_work_orders",
                        method: 'GET',
                        dataType: 'json',
                        success: function(response) {
                            machineList = response.machines || [];
                            renderReadyOrders(response.ready_orders);
                            renderWipVacOrders(response.wip_vac);
                            renderPendingOrders(response.pending_orders);
                        },
                        error: function(xhr, status, error) {
                            console.error('Error loading work orders:', error);
                        }
                    });
                }

                function renderReadyOrders(orders) {
                    if (orders.length === 0) {
                        $('#ready-orders-container').html('<p class="p-3">No ready orders found.</p>');
                        return;
                    }
                    let html = `
                        <table class="table table-bordered table-sm mb-0" id="readyOrdersTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Select</th>
                                    <th class="sortable" data-column="work_order_name" data-type="string">WO Number</th>
                                    <th class="sortable" data-column="part_number" data-type="string">Part Number</th>
                                    <th class="sortable" data-column="product_description" data-type="string">Part Description</th>
                                    <th class="sortable" data-column="end_date" data-type="date">Due Date</th>
                                    <th class="sortable" data-column="quantity" data-type="number">Qty</th>
                                    <th class="sortable" data-column="total_hours" data-type="number">Std Hours</th>
                                    <th>Machine</th>
                                    <th>Table</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    orders.forEach(order => {
                        html += `
                            <tr data-part-id="${order.part_id}" data-wo-id="${order.work_order_id}">
                                <td class="text-center">
                                    <input class="form-check-input" type="checkbox" name="workOrder[]" value="${order.work_order_id}"
                                        id="workOrder${order.work_order_id}" data-machine-id="${order.machine_id}" data-id="${order.id}">
                                </td>
                                <td>${escapeHtml(order.work_order_name)}</td>
                                <td>${escapeHtml(order.part_number)}</td>
                                <td>${escapeHtml(order.product_description)}</td>
                                <td>${escapeHtml(order.end_date)}</td>
                                <td>${escapeHtml(order.quantity)}</td>
                                <td>${escapeHtml(order.total_hours)}</td>
                                <td>${getMachineSelectHtml(order.id, order.machine_id)}</td>
                                <td>
                                    <select class="form-select form-select-sm" name="table_assignment[${order.work_order_id}]">
                                        <option value="Table 1">Table 1</option>
                                        <option value="Table 2">Table 2</option>
                                    </select>
                                </td>
                            </tr>
                        `;
                    });
                    html += `</tbody></table>`;
                    $('#ready-orders-container').html(html);
                    if (typeof $().select2 !== 'undefined') {
                        $('#ready-orders-container .machine-select').each(function() {
                            if (!$(this).hasClass('select2-hidden-accessible')) {
                                $(this).select2({ dropdownParent: $(document.body), width: '100%' });
                            }
                        });
                    }
                    initTableSort('readyOrdersTable');
                }

                function renderWipVacOrders(orders) {
                    if (orders.length === 0) {
                        $('#wip-vac-container').html('<p class="p-3">No WIP VAC orders found.</p>');
                        return;
                    }
                    let html = `
                        <table class="table table-bordered table-sm mb-0" id="wipVacTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Select</th>
                                    <th class="sortable" data-column="work_order_name" data-type="string">WO Number</th>
                                    <th class="sortable" data-column="part_number" data-type="string">Part Number</th>
                                    <th class="sortable" data-column="route_desc" data-type="string">Part Description</th>
                                    <th class="sortable" data-column="end_date" data-type="date">Due Date</th>
                                    <th class="sortable" data-column="quantity" data-type="number">Qty</th>
                                    <th class="sortable" data-column="total_hours" data-type="number">Std Hours</th>
                                    <th>Machine</th>
                                    <th>Table</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    orders.forEach(order => {
                        const dbId = order.id || order.work_order_id;
                        html += `
                            <tr data-part-id="${order.part_id}" data-wo-id="${order.work_order_id}">
                                <td class="text-center">
                                    <input class="form-check-input" type="checkbox" name="wipWorkOrder[]" value="${order.work_order_id}"
                                        id="wipWorkOrder${order.work_order_id}" data-machine-id="${order.machine_id}" data-id="${dbId}">
                                </td>
                                <td>${escapeHtml(order.work_order_name)}</td>
                                <td>${escapeHtml(order.part_number)}</td>
                                <td>${escapeHtml(order.route_desc)}</td>
                                <td>${escapeHtml(order.end_date)}</td>
                                <td>${escapeHtml(order.quantity)}</td>
                                <td>${escapeHtml(order.total_hours)}</td>
                                <td>${getMachineSelectHtml(order.id, order.machine_id)}</td>
                                <td>
                                    <select class="form-select form-select-sm" name="wip_table_assignment[${order.work_order_id}]">
                                        <option value="Table 1">Table 1</option>
                                        <option value="Table 2">Table 2</option>
                                    </select>
                                </td>
                            </tr>
                        `;
                    });
                    html += `</tbody></table>`;
                    $('#wip-vac-container').html(html);
                    if (typeof $().select2 !== 'undefined') {
                        $('#wip-vac-container .machine-select').each(function() {
                            if (!$(this).hasClass('select2-hidden-accessible')) {
                                $(this).select2({ dropdownParent: $(document.body), width: '100%' });
                            }
                        });
                    }
                    initTableSort('wipVacTable');
                }

                function renderPendingOrders(orders) {
                    if (orders.length === 0) {
                        $('#pending-orders-container').html('<p class="p-3">No pending orders found.</p>');
                        return;
                    }
                    let html = `
                        <table class="table table-bordered table-sm mb-0" id="pendingOrdersTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Select</th>
                                    <th class="sortable" data-column="work_order_name" data-type="string">WO Number</th>
                                    <th class="sortable" data-column="part_number" data-type="string">Part Number</th>
                                    <th class="sortable" data-column="route_desc" data-type="string">Part Description</th>
                                    <th class="sortable" data-column="end_date" data-type="date">Due Date</th>
                                    <th class="sortable" data-column="quantity" data-type="number">Qty</th>
                                    <th class="sortable" data-column="total_hours" data-type="number">Std Hours</th>
                                    <th>Machine</th>
                                    <th>Table</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                    orders.forEach(order => {
                        const dbId = order.id || order.work_order_id;
                        html += `
                            <tr data-part-id="${order.part_id}" data-wo-id="${order.work_order_id}">
                                <td class="text-center">
                                    <input class="form-check-input" type="checkbox" name="pendingWorkOrder[]" value="${order.work_order_id}"
                                        id="pendingWorkOrder${order.work_order_id}" data-machine-id="${order.machine_id}" data-id="${dbId}">
                                </td>
                                <td>${escapeHtml(order.work_order_name)}</td>
                                <td>${escapeHtml(order.part_number)}</td>
                                <td>${escapeHtml(order.route_desc)}</td>
                                <td>${escapeHtml(order.end_date)}</td>
                                <td>${escapeHtml(order.quantity)}</td>
                                <td>${escapeHtml(order.total_hours)}</td>
                                <td>${getMachineSelectHtml(dbId, order.machine_id)}</td>
                                <td>
                                    <select class="form-select form-select-sm" name="pending_table_assignment[${order.work_order_id}]">
                                        <option value="Table 1">Table 1</option>
                                        <option value="Table 2">Table 2</option>
                                    </select>
                                </td>
                            </tr>
                        `;
                    });
                    html += `</tbody></table>`;
                    $('#pending-orders-container').html(html);
                    if (typeof $().select2 !== 'undefined') {
                        $('#pending-orders-container .machine-select').each(function() {
                            if (!$(this).hasClass('select2-hidden-accessible')) {
                                $(this).select2({ dropdownParent: $(document.body), width: '100%' });
                            }
                        });
                    }
                    initTableSort('pendingOrdersTable');
                }

                function escapeHtml(text) {
                    const div = document.createElement('div');
                    div.textContent = text;
                    return div.innerHTML;
                }

                function getMachineSelectHtml(id, selectedMachineId) {
                    let options = '<option value="">Select Machine</option>';
                    machineList.forEach(machine => {
                        const selected = machine.id == selectedMachineId ? 'selected' : '';
                        options += `<option value="${machine.id}" ${selected}>${escapeHtml(machine.name)}</option>`;
                    });
                    return `<select class="form-control form-control-sm machine-select" id="machine_id_${id}" name="machine_id[${id}]" data-row-id="${id}">
                        ${options}
                    </select>`;
                }
                function resizeMachineSelects() {
                    $('.machine-select').each(function() {
                        if ($(this).hasClass('select2-hidden-accessible')) {
                            $(this).select2('destroy');
                        }
                    });
                    $('.machine-select').each(function() {
                        $(this).select2({ dropdownParent: $(document.body), width: '100%' });
                    });
                }

                function initTableSort(tableId) {
                    const table = document.getElementById(tableId);
                    if (!table) return;
                    const headers = table.querySelectorAll('th.sortable');
                    headers.forEach(header => {
                        header.addEventListener('click', function() {
                            const column = this.dataset.column;
                            const type = this.dataset.type;
                            const tbody = table.querySelector('tbody');
                            const rows = Array.from(tbody.querySelectorAll('tr'));
                            let direction = 'asc';
                            if (this.classList.contains('asc')) {
                                direction = 'desc';
                            }
                            headers.forEach(h => h.classList.remove('asc', 'desc'));
                            this.classList.add(direction);
                            const columnIndex = Array.from(this.parentElement.children).indexOf(this);
                            rows.sort((a, b) => {
                                let aVal = a.children[columnIndex].textContent.trim();
                                let bVal = b.children[columnIndex].textContent.trim();
                                if (type === 'number') {
                                    aVal = parseFloat(aVal) || 0;
                                    bVal = parseFloat(bVal) || 0;
                                } else if (type === 'date') {
                                    aVal = new Date(aVal);
                                    bVal = new Date(bVal);
                                }
                                if (aVal < bVal) return direction === 'asc' ? -1 : 1;
                                if (aVal > bVal) return direction === 'asc' ? 1 : -1;
                                return 0;
                            });
                            rows.forEach(row => tbody.appendChild(row));
                        });
                    });
                }

                function showSelectedWorkOrders() {
                    const btn = $("#showSelectedBtn");
                    btn.prop("disabled", true);
                    btn.find(".btn-text").text("Processing...");
                    btn.find(".spinner-border").removeClass("d-none");
                    const workOrders = [];
                    $('input[name="workOrder[]"]:checked').each(function() {
                        const workOrderId = $(this).val();
                        const row = $(this).closest('tr');
                        const partId = row.data('part-id');
                        const dbId = $(this).data('id');
                        const machineId = $("#machine_id_" + dbId).val();
                        const tableValue = row.find('select[name="table_assignment[' + workOrderId + ']"]').val();
                        const tableId = tableValue === 'Table 1' ? 1 : (tableValue === 'Table 2' ? 2 : '');
                        workOrders.push({
                            id: dbId,
                            work_order_id: workOrderId,
                            part_id: partId,
                            machine_id: machineId,
                            table_id: tableId
                        });
                    });
                    if (workOrders.length === 0) {
                        alert("Please select at least one work order.");
                        resetButton(btn, "Show Selected");
                        return;
                    }
                    submitWorkOrders(workOrders, btn, "Show Selected");
                }

                function showSelectedWipOrders() {
                    const btn = $("#showSelectedWipBtn");
                    btn.prop("disabled", true);
                    btn.find(".btn-text").text("Processing...");
                    btn.find(".spinner-border").removeClass("d-none");
                    const workOrders = [];
                    let hasError = false;
                    $('input[name="wipWorkOrder[]"]:checked').each(function() {
                        const workOrderId = $(this).val();
                        const row = $(this).closest('tr');
                        const partId = row.data('part-id');
                        const dbId = $(this).data('id');
                        const machineId = $("#machine_id_" + dbId).val();
                        const tableValue = row.find('select[name="wip_table_assignment[' + workOrderId + ']"]').val();
                        const tableId = tableValue === 'Table 1' ? 1 : (tableValue === 'Table 2' ? 2 : '');
                        if (!machineId || machineId === '') {
                            alert("Please select a machine for all selected work orders.");
                            hasError = true;
                            return false;
                        }
                        workOrders.push({
                            id: dbId,
                            work_order_id: workOrderId,
                            part_id: partId,
                            machine_id: machineId,
                            table_id: tableId
                        });
                    });
                    if (hasError) { resetButton(btn, "Show Selected"); return; }
                    if (workOrders.length === 0) {
                        alert("Please select at least one work order.");
                        resetButton(btn, "Show Selected");
                        return;
                    }
                    submitWorkOrders(workOrders, btn, "Show Selected");
                }

                function showSelectedPendingOrders() {
                    const btn = $("#showSelectedPendingBtn");
                    btn.prop("disabled", true);
                    btn.find(".btn-text").text("Processing...");
                    btn.find(".spinner-border").removeClass("d-none");
                    const workOrders = [];
                    let hasError = false;
                    $('input[name="pendingWorkOrder[]"]:checked').each(function() {
                        const workOrderId = $(this).val();
                        const row = $(this).closest('tr');
                        const partId = row.data('part-id');
                        const dbId = $(this).data('id');
                        const machineId = $("#machine_id_" + dbId).val();
                        const tableValue = row.find('select[name="pending_table_assignment[' + workOrderId + ']"]').val();
                        const tableId = tableValue === 'Table 1' ? 1 : (tableValue === 'Table 2' ? 2 : '');
                        if (!machineId || machineId === '') {
                            alert("Please select a machine for all selected work orders.");
                            hasError = true;
                            return false;
                        }
                        workOrders.push({
                            id: dbId,
                            work_order_id: workOrderId,
                            part_id: partId,
                            machine_id: machineId,
                            table_id: tableId
                        });
                    });
                    if (hasError) { resetButton(btn, "Show Selected"); return; }
                    if (workOrders.length === 0) {
                        alert("Please select at least one work order.");
                        resetButton(btn, "Show Selected");
                        return;
                    }
                    submitWorkOrders(workOrders, btn, "Show Selected");
                }

                function submitWorkOrders(workOrders, btn, buttonText) {
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=select_order_for_cnc",
                        method: "POST",
                        data: { work_orders: JSON.stringify(workOrders) },
                        success: function() {
                            alert("Work orders submitted successfully!");
                            window.location.reload();
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error:", error);
                            window.location.reload();
                            resetButton(btn, buttonText);
                        }
                    });
                }

                function resetButton(btn, text) {
                    btn.prop("disabled", false);
                    btn.find(".btn-text").text(text);
                    btn.find(".spinner-border").addClass("d-none");
                }

                $(document).ready(function() {
                    loadWorkOrders();
                    setInterval(loadWorkOrders, 30000);
                });
            </script>
        </div>

<div class="split-divider" id="divider"></div>

<div class="split-panel" id="right-panel">

<?php

 $month = isset($_GET['month']) ? intval($_GET['month']) : date('m');
 $year  = isset($_GET['year'])  ? intval($_GET['year'])  : date('Y');

$currentDateStr = date('Y-m-d');

$machineColors = [];
$colorPalette = [
    '#e6f5f5','#f5e6f5','#e6ffe6','#fff2e6','#f0e6ff',
    '#e6ffff','#ffe6f2','#f5f5e6','#e6f5f5','#f5e6ff',
    '#e6ffec','#fff0e6','#e6f0ff','#ffe6ff','#e6ffe6',
    '#f5e6e6','#e6e6f5','#f5f5e6','#e6f5f5','#f5e6f5'
];
$colorIndex = 0;

$machineQuery = mysqli_query($conn, "SELECT id, resource_code FROM station_detail_table WHERE machine_type = 3 AND hide = 0");
$taskNames = [];
while ($row = mysqli_fetch_assoc($machineQuery)) {
    $machineId = $row['id'];
    $taskNames[$machineId . '-1'] = $row['resource_code'] . ' - Table 1';
    $taskNames[$machineId . '-2'] = $row['resource_code'] . ' - Table 2';
    if (!isset($machineColors[$machineId])) {
        $machineColors[$machineId] = $colorPalette[$colorIndex % count($colorPalette)];
        $colorIndex++;
    }
}

$shifts = [];
$shiftHours = [];
$shiftDays = [];
$shiftTimes = [];
$dayMap = [0=>"Sunday",1=>"Monday",2=>"Tuesday",3=>"Wednesday",4=>"Thursday",5=>"Friday",6=>"Saturday"];

$sql = "SELECT shift_name, day_shifts, start_time, end_time, hours FROM working_hours";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    $shiftName = $row['shift_name'];
    $shifts[] = $shiftName;
    $shiftHours[$shiftName] = (float)$row['hours'];
    $shiftDays[$shiftName]  = $dayMap[(int)$row['day_shifts']];
    $shiftTimes[$shiftName] = ['start'=>$row['start_time'],'end'=>$row['end_time'],'hours'=>(float)$row['hours']];
}
$shifts = array_unique($shifts);

$monthsToShow = [];
$currentDate  = new DateTime();
for ($i = 0; $i < 3; $i++) {
    $date = clone $currentDate;
    $date->modify("+$i months");
    $monthsToShow[] = ['month'=>(int)$date->format('m'),'year'=>(int)$date->format('Y'),'label'=>$date->format('F Y')];
}

$intervalCache = [];
function generateTimeIntervals($startTime, $endTime) {
    global $intervalCache;
    $cacheKey = $startTime.'-'.$endTime;
    if (isset($intervalCache[$cacheKey])) return $intervalCache[$cacheKey];
    $intervals = [];
    $current = new DateTime($startTime);
    $end = new DateTime($endTime);
    $intervalStart = $current->format('H:i');
    $current->add(new DateInterval('PT30M'));
    while ($current <= $end) {
        $intervalEnd = $current->format('H:i');
        $intervals[] = ['start'=>$intervalStart,'end'=>$intervalEnd,'minutes'=>(strtotime($intervalEnd)-strtotime($intervalStart))/60];
        $intervalStart = $intervalEnd;
        $current->add(new DateInterval('PT30M'));
    }
    if ($intervalStart !== $end->format('H:i')) {
        $intervals[] = ['start'=>$intervalStart,'end'=>$end->format('H:i'),'minutes'=>(strtotime($end->format('H:i'))-strtotime($intervalStart))/60];
    }
    $intervalCache[$cacheKey] = $intervals;
    return $intervals;
}

function generateCalendar($month, $year, $shifts, $shiftDays, $shiftTimes) {
    $calendar = [];
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $validWeekdays = array_unique(array_values($shiftDays));
    $today = new DateTime();
    $currentYear  = (int)$today->format('Y');
    $currentMonth = (int)$today->format('m');
    $currentDay   = (int)$today->format('d');
    $startDay = ($year == $currentYear && $month == $currentMonth) ? $currentDay : 1;

    for ($day = $startDay; $day <= $daysInMonth; $day++) {
        $date = sprintf("%04d-%02d-%02d", $year, $month, $day);
        $timestamp  = strtotime($date);
        $dayOfWeek  = date("l", $timestamp);

        if (in_array($dayOfWeek, $validWeekdays)) {

            // Collect all shifts that fall on this calendar day first...
            $dayShifts = [];
            foreach ($shifts as $shift) {
                if ($shiftDays[$shift] === $dayOfWeek) {
                    $dayShifts[] = $shift;
                }
            }

            usort($dayShifts, function ($a, $b) use ($shiftTimes) {
                return strtotime($shiftTimes[$a]['start']) <=> strtotime($shiftTimes[$b]['start']);
            });

            foreach ($dayShifts as $shift) {
                $intervals = generateTimeIntervals($shiftTimes[$shift]['start'], $shiftTimes[$shift]['end']);
                $calendar[] = [
                    "date"=>$date,"day"=>$day,"dayOfWeek"=>$dayOfWeek,
                    "month"=>$month,"shift"=>$shift,
                    "start_time"=>$shiftTimes[$shift]['start'],
                    "end_time"=>$shiftTimes[$shift]['end'],
                    "hours"=>$shiftTimes[$shift]['hours'],
                    "intervals"=>$intervals,
                    "total_intervals"=>count($intervals),
                    "total_minutes"=>array_sum(array_column($intervals,'minutes'))
                ];
            }
        }
    }
    return $calendar;
}

$calendarDays = [];
foreach ($monthsToShow as $m) {
    $calendarDays = array_merge($calendarDays, generateCalendar($m['month'],$m['year'],$shifts,$shiftDays,$shiftTimes));
}

$totalWidth = 0;
$dayPositions = [];
$dayWidths = [];

foreach ($calendarDays as $day) {
    $dayWidth = count($day['intervals']) * 40;
    $key = $day['date'].'-'.$day['shift'];
    $dayPositions[$key] = $totalWidth;
    $dayWidths[$key]    = $dayWidth;
    $totalWidth += $dayWidth;
}

function getSavedEmployee($conn, $machineId) {
    $today = date('Y-m-d');
    $query = "SELECT employee_id FROM cnc_machine_engineer_daily WHERE machine_id = ? AND assign_date = ? LIMIT 1";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("is", $machineId, $today);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) return $result->fetch_assoc()['employee_id'];
    return null;
}
?>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
            <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
            <style>
                :root {
                    --primary-color: #3498db;
                    --secondary-color: #2c3e50;
                    --accent-color: #e74c3c;
                    --light-bg: #f8f9fa;
                    --dark-bg: #343a40;
                    --success-color: #2ecc71;
                    --warning-color: #f39c12;
                    --danger-color: #e74c3c;
                    --info-color: #3498db;
                    --current-time-color: #e74c3c;
                    --time-marker-color: #fff3cd;
                    --shift-highlight: #d4edda;
                    --time-interval-width: 40px;
                    --task-bar-height: 130px;
                    --grid-line-color: rgba(0, 0, 0, 0.1);
                }
                .gantt-container {
                    position: relative;
                    width: 100%;
                    overflow-x: auto;
                    margin-top: 20px;
                    display: flex;
                    background-color: white;
                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                    border-radius: 8px;
                }
                .gantt-labels {
                    position: sticky;
                    left: 0;
                    top: 0;
                    width: 350px;
                    background: #f9f9f9;
                    padding: 15px;
                    border-right: 1px solid #ddd;
                    z-index: 20;
                    height: fit-content;
                    flex-shrink: 0;
                }
                .gantt-scrollable-content {
                    flex: 1;
                    min-width: 0;
                    overflow-x: auto;
                    position: relative;
                }
                .gantt-grid {
                    display: inline-block;
                    min-width: <?php echo $totalWidth; ?>px;
                    position: relative;
                }
                .gantt-header {
                    display: inline-flex;
                    background: #f5f5f5;
                    border-bottom: 1px solid #ddd;
                    position: sticky;
                    top: 0;
                    z-index: 15;
                }
                .gantt-day {
                    display: inline-flex;
                    flex-direction: column;
                    text-align: center;
                    background-color: #fff;
                    float: none;
                    vertical-align: top;
                    position: relative;
                }
                .gantt-day strong {
                    font-size: 12px;
                    color: #333;
                    background: #f3f3f3;
                    padding: 3px;
                    border-radius: 3px;
                    margin-bottom: 5px;
                }
                .gantt-time-intervals {
                    display: flex;
                    flex-wrap: nowrap;
                    justify-content: flex-start;
                    width: 100%;
                    background-color: #f8f9fa;
                    border-top: 1px solid #dee2e6;
                }
                .gantt-time-interval {
                    flex: 0 0 var(--time-interval-width);
                    text-align: center;
                    font-size: 10px;
                    color: #555;
                    border-right: 1px solid var(--grid-line-color);
                    height: 30px;
                    position: relative;
                }
                .gantt-time-interval-label {
                    position: absolute;
                    font-size: 0.9rem;
                    transform: rotate(-45deg);
                    transform-origin: left center;
                    white-space: nowrap;
                    left: 0%;
                    bottom: -15px;
                    color: #000;
                }
                .gantt-row {
                    display: block;
                    border-bottom: 1px solid #000;
                    min-height: var(--task-bar-height);
                    position: relative;
                    white-space: nowrap;
                    background-image: linear-gradient(to right, var(--grid-line-color) 1px, transparent 1px);
                    background-size: var(--time-interval-width) 1px;
                    background-position: left center;
                }
                .gantt-row.table-1 {
                    background-color: rgba(230, 242, 255, 0.3);
                }
                .gantt-row.table-2 {
                    background-color: rgba(255, 230, 230, 0.3);
                }
                .gantt-task {
                    position: absolute;
                    height: 100%;
                    top: 0;
                    background: #3498db;
                    color: white;
                    text-align: center;
                    border-radius: 5px;
                    padding: 5px;
                    line-height: 1.2;
                    font-size: 12px;
                    cursor: grab;
                    transition: background-color 0.3s ease;
                    box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
                    z-index: 1;
                    overflow: hidden;
                    box-sizing: border-box;
                }
                .gantt-task .task-content {
                    padding: 3px;
                    font-size: 10px;
                    height: calc(100% - 20px);
                    overflow: hidden;
                }
                .gantt-task .task-hours {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background: rgba(0,0,0,0.2);
                    text-align: center;
                    font-size: 9px;
                    padding: 1px 0;
                    border-radius: 0 0 4px 4px;
                }
                .task-color-1 { background-color: #FFA500; }
                .task-color-2 { background-color: #32CD32; }
                .task-color-3 { background-color: #ff6b6b; }
                .task-color-4 { background-color: #3498db; }
                .no-tasks {
                    color: #999;
                    font-style: italic;
                    padding: 10px;
                    text-align: center;
                    width: 100%;
                }
                .dot-indicator {
                    position: absolute;
                    top: 3px;
                    right: 3px;
                    width: 20px;
                    height: 20px;
                    border-radius: 50%;
                    border: 3px solid black;
                }
                .green-dot-indicator { background-color: #00cc66; }
                .red-dot-indicator { background-color: #ff3333; }
                .blue-dot-indicator { background-color: #3399ff; }
                .hour-indicator {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    font-size: 0.65rem;
                    text-align: center;
                    background: rgba(0,0,0,0.15);
                    padding: 1px 0;
                    border-radius: 0 0 4px 4px;
                }
                .machine-list {
                    display: flex;
                    flex-direction: column;
                    gap: 10px;
                }
                .circle-button {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                    width: 20px;
                    height: 20px;
                    border: none;
                    border-radius: 50%;
                    background-color: #4CAF50;
                    cursor: pointer;
                    z-index: 10;
                }
                .controls {
                    background: white;
                    padding: 15px;
                    border-radius: 8px;
                    margin-bottom: 20px;
                    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                }
                .machine-section { margin-bottom: 15px; }
                .card {
                    border-radius: 8px;
                    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
                    transition: transform 0.2s;
                }
                .card:hover { transform: translateY(-2px); }
                .card-header {
                    font-weight: 500;
                    padding: 8px 12px;
                }
                .form-control {
                    font-size: 0.85rem;
                    padding: 0.25rem 0.5rem;
                }
                .gantt-task.dragging {
                    opacity: 0.5;
                    background-color: #f39c12;
                }
                .gantt-row.drop-target {
                    outline: 2px dashed #007bff;
                    background-color: #e6f7ff;
                }
                .gantt-day.today {
                    background-color: #fff3cd;
                    box-shadow: 0 0 0 2px #ffc107;
                }
                .gantt-day.today strong {
                    background-color: #ffc107;
                    color: #000;
                    font-weight: bold;
                }
                .current-time-marker {
                    position: absolute;
                    top: 0;
                    bottom: 0;
                    width: 2px;
                    background-color: var(--current-time-color);
                    z-index: 10;
                }
                .current-time-marker::after {
                    content: '';
                    position: absolute;
                    top: 0;
                    left: -4px;
                    width: 10px;
                    height: 10px;
                    background-color: var(--current-time-color);
                    border-radius: 50%;
                }
                .gantt-task {
                    border-right: 3px solid rgba(255, 255, 255, 0.5);
                    box-sizing: border-box;
                }
                .gantt-task.highlight-border {
                    border-right: 100px solid rgba(255, 255, 0, 0.8) !important;
                    box-shadow: 0 0 10px rgba(255, 255, 0, 0.5);
                    transition: all 0.3s ease;
                }
                .break-task {
                    background-color: #999 !important;
                    border-left: 3px dashed #fff !important;
                    border-right: 3px dashed #fff !important;
                    color: #fff !important;
                }
                .dot-indicator.inventory-loading {
                    background-color: #ccc !important;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .dot-indicator.inventory-loading .spinner-border-sm {
                    width: 12px;
                    height: 12px;
                }
                .gantt-task.breakdown-affected {
                    background: repeating-linear-gradient(45deg, #ff6b6b, #ff6b6b 10px, #ff8e8e 10px, #ff8e8e 20px) !important;
                    border: 2px dashed #cc0000 !important;
                    color: #000 !important;
                    font-weight: bold !important;
                }
                .gantt-task.breakdown-affected .task-content {
                    background: rgba(255, 255, 255, 0.8);
                    border-radius: 3px;
                    padding: 3px;
                }
                .gantt-task.breakdown-affected .hour-indicator {
                    background: rgba(204, 0, 0, 0.8) !important;
                    color: white !important;
                    font-weight: bold;
                }
                .gantt-task.late-task {
                    background-color: #ff6b6b !important;
                    border-left: 3px solid #ff0000 !important;
                    border-right: 3px solid #ff0000 !important;
                }
                .gantt-task.on-time-task {
                    background-color: #78c679 !important;
                    border-left: 3px solid #2ecc71 !important;
                    border-right: 3px solid #2ecc71 !important;
                }
                // employee display styles
                .employee-display {
                    margin-top: 8px;
                    padding: 5px;
                    background: #e8f4f8;
                    border-radius: 4px;
                    font-size: 11px;
                    font-weight: 500;
                    color: #2c3e50;
                    min-height: 25px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .employee-display i {
                    margin-right: 5px;
                    color: #007bff;
                }
                .no-employee {
                    color: #999;
                    font-style: italic;
                }
                .employee-select-wrapper { margin-top: 30px; }
                .machine-employee-select {
                    width: 100%;
                    font-size: 12px;
                }
            </style>

            <div class="container-fluid">
                <div class="controls">
                    <div class="row">
                        <div class="col-md-6">
                            <h3><i class="fas fa-calendar-day me-2"></i>CNC Gantt Chart</h3>
                            <h4><?php echo date('l, F j, Y'); ?></h4>
                        </div>
                        <div class="col-md-6 text-end">
                            <button class="btn btn-primary" onclick="window.location.reload()">
                                <i class="fas fa-sync-alt me-2"></i>Refresh
                            </button>
                            <button class="btn btn-warning ms-2" id="addBreakBtn">
                                <i class="fas fa-clock me-2"></i>Add Break
                            </button>
                            <button class="btn btn-danger ms-2 hide" id="startBreakdownBtn">
                                <i class="fas fa-exclamation-triangle me-2"></i>Start Breakdown
                            </button>
                            <button class="btn btn-success ms-2 hide" id="stopBreakdownBtn">
                                <i class="fas fa-check me-2"></i>Stop Breakdown
                            </button>
                        </div>
                    </div>
                </div>

                <div class="gantt-container">
                    <div class="gantt-labels">
                        <div>
                            <h5>
                                <i class="fas fa-server me-2"></i>Machines
                                <span class="mx-2">and</span>
                                <i class="fas fa-user-tie me-2"></i>Engineers
                            </h5>
                        </div>
                        <div class="machine-list d-flex flex-wrap" style="gap: 16px;">
                            <div style="margin-bottom: 20px;"></div>
                            <?php
                            $renderedMachines = [];
                            foreach ($taskNames as $taskKey => $taskName):
                                $parts = explode('-', $taskKey);
                                $machineId = $parts[0];
                                $tableId = $parts[1];
                                if (!in_array($machineId, $renderedMachines)):
                                    $renderedMachines[] = $machineId;
                                    //$savedEmployeeId = getSavedEmployee($conn, $machineId);
                            ?>
                            <div class="mb-2">
                                <div class="card" style="background-color: #f2edf2; width: 300px; min-height: 220px; display: flex; align-items: center; justify-content: center; position: relative; padding: 15px;">
                                    <button class="circle-button" data-machine-id="<?php echo $machineId; ?>"></button>
                                    <div class="card-body text-center" style="width: 100%;">
                                        <h5 class="card-title"><?php
                                            $machineNameParts = explode(' - ', $taskName);
                                            echo $machineNameParts[0];
                                        ?></h5>
                                        <div class="employee-select-wrapper" data-machine-id="<?php echo $machineId; ?>">
                                            <?php
                                            echo $gsi->getEmployeeList(
                                                "machine_employee[" . $machineId . "]",
                                                $savedEmployeeId ?? "",
                                                "100%",
                                                false,
                                                "form-control select2 machine-employee-select",
                                                ""
                                            );
                                            ?>
                                        </div>
                                        <?php if ($savedEmployeeId):
                                            $empQuery = "SELECT name, employee_code FROM employees WHERE id = ?";
                                            $empStmt = $conn->prepare($empQuery);
                                            $empStmt->bind_param("i", $savedEmployeeId);
                                            $empStmt->execute();
                                            $empResult = $empStmt->get_result();
                                            if ($empRow = $empResult->fetch_assoc()):
                                        ?>
                                        <div class="employee-display">
                                            <i class="fas fa-user-check"></i>
                                            <span><?php echo htmlspecialchars($empRow['name']); ?></span>
                                        </div>
                                        <?php
                                            endif;
                                        else:
                                        ?>
                                        <div class="employee-display no-employee">
                                            <i class="fas fa-user-times"></i>
                                            <span>No engineer assigned</span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            <?php
                                endif;
                            endforeach;
                            ?>
                        </div>
                    </div>

                    <div class="gantt-labels" style="left: 350px; width: 250px;">
                        <h5><i class="fas fa-table me-2"></i>Tables</h5>
                        <div style="margin-bottom: 30px;"></div>
                        <div class="machine-list">
                            <?php
                            $renderedMachines = [];
                            foreach ($taskNames as $taskKey => $taskName):
                                $parts = explode('-', $taskKey);
                                $machineId = $parts[0];
                                $tableId = $parts[1];
                                if (!in_array($machineId, $renderedMachines)):
                                    $renderedMachines[] = $machineId;
                                    $machineName = explode(' - ', $taskName)[0];
                            ?>
                            <div class="machine-section mb-1" style="width: 200px;">
                                <div class="row" style="margin-bottom: 2px; height: 120px;">
                                    <div class="card card-header text-dark" style="background-color: #e6f2ff;">
                                        <div>Table 1</div>
                                    </div>
                                </div>
                                <div class="row" style="margin-top: 8px; height: 120px;">
                                    <div class="card card-header text-dark" style="background-color: #ffe6e6;">
                                        <div>Table 2</div>
                                    </div>
                                </div>
                            </div>
                            <?php
                                endif;
                            endforeach;
                            ?>
                        </div>
                    </div>

                    <div class="gantt-scrollable-content">
                        <div class="gantt-grid">
                            <div class="gantt-header">
                                <?php foreach ($calendarDays as $day):
                                    $dayWidth = count($day['intervals']) * 40;
                                    $isToday = $day['date'] == date('Y-m-d');
                                ?>
                                <div class="gantt-day <?php echo $isToday ? 'today' : ''; ?>"
                                     data-date="<?php echo $day["date"]; ?>"
                                     data-shift="<?php echo $day["shift"]; ?>"
                                     style="min-width: <?php echo $dayWidth; ?>px;">
                                    <div><strong><?php echo $day["date"] . " (" . $day["shift"] . ")"; ?></strong></div>
                                    <div class="gantt-time-intervals">
                                        <?php foreach ($day['intervals'] as $interval): ?>
                                        <div class="gantt-time-interval" data-interval="<?php echo $interval['start'] . '-' . $interval['end']; ?>">
                                            <div class="gantt-time-interval-label"><?php echo $interval['start']; ?></div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>

                            <div id="gantt-task-rows-wrapper">
                                <?php foreach ($taskNames as $taskKey => $taskName):
                                    $parts = explode('-', $taskKey);
                                    $machineId = $parts[0];
                                    $tableId   = $parts[1];
                                    $rowColor  = $machineColors[$machineId];
                                ?>
                                <div class="gantt-row <?php echo $tableId == 1 ? 'table-1' : 'table-2'; ?>"
                                     data-machine-id="<?php echo $machineId; ?>"
                                     data-table-id="<?php echo $tableId; ?>"
                                     style="background-color: <?php echo $rowColor; ?>; min-width: <?php echo $totalWidth; ?>px; position: relative; min-height: 130px;">
                                    <div style="padding:10px; color:#999; font-style:italic;" class="gantt-loading-spinner">
                                        <span class="spinner-border spinner-border-sm" role="status"></span> Loading...
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="workOrderDetailModal" tabindex="-1" aria-labelledby="workOrderDetailModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title" id="workOrderDetailModalLabel">
                                <i class="fas fa-info-circle me-2"></i>Work Order Details
                            </h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div id="detailLoadingSpinner" class="text-center py-5">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2">Loading details...</p>
                            </div>
                            <div id="workOrderDetailContent" style="display: none;">
                                <div class="card mb-3">
                                    <div class="card-header bg-light">
                                        <h6 class="mb-0"><i class="fas fa-clipboard-list me-2"></i>Order Information</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p><strong>Customer Order:</strong> <span id="detail_customer_order"></span></p>
                                                <p><strong>Work Order Name:</strong> <span id="detail_wo_name"></span></p>
                                                <p><strong>Status:</strong> <span id="detail_status" class="badge"></span></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p><strong>Final Part:</strong> <span id="detail_final_part"></span></p>
                                                <p><strong>Customer code:</strong> <span id="detail_customer_code" class=""></span></p>
                                                <p><strong>RefSalescode:</strong> <span id="detail_RefSalesCode" class=""></span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card mb-3">
                                    <div class="card-header bg-light">
                                        <h6 class="mb-0"><i class="fas fa-cog me-2"></i>Part Information</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <p><strong>Part/Set Name:</strong> <span id="detail_part_name"></span></p>
                                                <p><strong>Desc:</strong> <span id="detail_desc"></span></p>
                                                <p><strong>Quantity:</strong> <span id="detail_quantity"></span></p>
                                            </div>
                                            <div class="col-md-6">
                                                <p><strong>Setup Hours:</strong> <span id="detail_setup_hours"></span></p>
                                                <p><strong>Total Hours:</strong> <span id="detail_total_hours"></span></p>
                                                <p><strong>Due Date:</strong> <span id="detail_due_date"></span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="card mb-3">
                                    <div class="card-header bg-light">
                                        <h6 class="mb-0"><i class="fas fa-wrench me-2"></i>Production Details</h6>
                                    </div>
                                    <div class="card-body">
                                        <p><strong>Description:</strong> <span id="detail_route_desc"></span></p>
                                        <div id="breakdown_info" style="display: none;" class="alert alert-danger">
                                            <strong><i class="fas fa-exclamation-triangle me-2"></i>Breakdown Impact:</strong>
                                            <span id="detail_breakdown_hours"></span> hours delay
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div id="detailErrorMessage" class="alert alert-danger d-none" role="alert">
                                Failed to load work order details. Please try again.
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
                            <button type="button" class="btn btn-warning hide" id="editWorkOrderBtn">
                                <i class="fas fa-edit me-2"></i>Edit
                            </button>
                            <button type="button" class="btn btn-info" id="splitWorkOrderBtn" style="display:none;">
                                <i class="fas fa-cut me-2"></i>Split Work Order
                            </button>
                            <button type="button" class="btn btn-danger" id="deleteWorkOrderBtn">
                                <i class="fas fa-trash me-2"></i>Delete
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="editWorkOrderModal" tabindex="-1" aria-labelledby="editWorkOrderModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header bg-warning">
                            <h5 class="modal-title" id="editWorkOrderModalLabel">
                                <i class="fas fa-edit me-2"></i>Edit Work Order
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="editWorkOrderForm">
                                <input type="hidden" id="edit_task_id" name="task_id">
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="edit_machine" class="form-label">Machine</label>
                                        <select class="form-control" id="edit_machine" name="machine_id">
                                            <?php foreach ($taskNames as $machineId => $taskName): ?>
                                            <option value="<?php echo $machineId; ?>"><?php echo $taskName; ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="edit_setup_hours" class="form-label">Setup Hours</label>
                                        <input type="number" class="form-control" id="edit_setup_hours" name="setup_hours" step="0.5" min="0">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="edit_total_hours" class="form-label">Total Hours</label>
                                        <input type="number" class="form-control" id="edit_total_hours" name="total_hours" step="0.5" min="0">
                                    </div>
                                </div>
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="edit_start_date" class="form-label">Start Date</label>
                                        <input type="date" class="form-control" id="edit_start_date" name="start_date">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="edit_quantity" class="form-label">Quantity</label>
                                        <input type="number" class="form-control" id="edit_quantity" name="quantity" min="1">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="saveEditBtn">
                                <i class="fas fa-save me-2"></i>Save Changes
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="splitWorkOrderModal" tabindex="-1" aria-labelledby="splitWorkOrderModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header bg-info text-white">
                            <h5 class="modal-title" id="splitWorkOrderModalLabel">
                                <i class="fas fa-cut me-2"></i>Split Work Order
                            </h5>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                Split this work order into two separate work orders based on quantity.
                            </div>
                            <form id="splitWorkOrderForm">
                                <input type="hidden" id="split_task_id" name="task_id">
                                <div class="mb-3">
                                    <label class="form-label"><strong>Current Quantity:</strong></label>
                                    <p id="split_current_quantity" class="form-control-plaintext">-</p>
                                </div>
                                <div class="mb-3">
                                    <label for="split_quantity" class="form-label">Split Quantity <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="split_quantity" name="split_quantity" min="1" step="1" required>
                                    <small class="form-text text-muted">Enter the quantity for the new work order</small>
                                </div>
                                <div id="split_preview" style="display:none;" class="mt-3">
                                    <h6 class="border-bottom pb-2">Preview:</h6>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="card bg-light">
                                                <div class="card-body">
                                                    <h6 class="card-title text-primary">Original WO</h6>
                                                    <p class="mb-1"><strong>Quantity:</strong> <span id="preview_remaining_qty">-</span></p>
                                                    <p class="mb-0"><strong>Hours:</strong> <span id="preview_remaining_hours">-</span></p>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="card bg-light">
                                                <div class="card-body">
                                                    <h6 class="card-title text-success">New WO</h6>
                                                    <p class="mb-1"><strong>Quantity:</strong> <span id="preview_split_qty">-</span></p>
                                                    <p class="mb-0"><strong>Hours:</strong> <span id="preview_split_hours">-</span></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="split_error" class="alert alert-danger mt-3" style="display:none;"></div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-info" id="confirmSplitBtn">
                                <i class="fas fa-check me-2"></i>Confirm Split
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                $('body').addClass('sidebar-collapse');
                let currentTaskDetails = null;

                function attachTaskClickHandlers() {
                    document.querySelectorAll('.gantt-task').forEach(task => {
                        if (task.classList.contains('break-task')) {
                            return;
                        }
                        task.style.cursor = 'pointer';
                        task.addEventListener('click', function(e) {
                            if (task.classList.contains('dragging')) {
                                return;
                            }
                            const taskId = this.dataset.taskId;
                            const workOrderId = this.dataset.workOrderId;
                            const partId = this.dataset.partId;
                            const machineId = this.dataset.currentMachine;
                            loadWorkOrderDetails(taskId, workOrderId, partId, machineId);
                        });
                    });
                }

                function loadWorkOrderDetails(taskId, workOrderId, partId, machineId) {
                    const modal = new bootstrap.Modal(document.getElementById('workOrderDetailModal'));
                    modal.show();
                    $('#detailLoadingSpinner').show();
                    $('#workOrderDetailContent').hide();
                    $('#detailErrorMessage').addClass('d-none');
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=get_cnc_task_details",
                        method: "POST",
                        data: { task_id: taskId, work_order_id: workOrderId, part_id: partId, machine_id: machineId },
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                currentTaskDetails = response.data;
                                displayWorkOrderDetails(response.data);
                                $('#detailLoadingSpinner').hide();
                                $('#workOrderDetailContent').show();
                            } else {
                                $('#detailLoadingSpinner').hide();
                                $('#detailErrorMessage').text(response.message || 'Failed to load details').removeClass('d-none');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error:", error);
                            $('#detailLoadingSpinner').hide();
                            $('#detailErrorMessage').removeClass('d-none');
                        }
                    });
                }

                function displayWorkOrderDetails(data) {
                    $('#detail_wo_no').text(data.work_order_no || '-');
                    $('#detail_customer_order').text(data.customer_order_nos || '-');
                    $('#detail_wo_name').text(data.work_order_name || '-');
                    $('#detail_final_part').text(data.parent_part_number || '-');
                    $('#detail_customer_code').text(data.customer_code || '-');
                    $('#detail_RefSalesCode').text(data.RefSalesCode || '-');
                    const statusBadge = $('#detail_status');
                    if (data.is_late) {
                        statusBadge.text('Late').removeClass().addClass('badge bg-danger');
                    } else {
                        statusBadge.text('On Time').removeClass().addClass('badge bg-success');
                    }
                    $('#detail_part_name').text(data.product_name || '-');
                    $('#detail_quantity').text(data.quantity || '-');
                    $('#detail_desc').text(data.manufacture_description || '-');
                    $('#detail_setup_hours').text(data.setup_hours || '-');
                    $('#detail_total_hours').text(data.total_hours || '-');
                    $('#detail_due_date').text(data.end_date || '-');
                    $('#detail_route_desc').text(data.route_desc || '-');
                    if (data.is_breakdown_affected && data.breakdown_hours > 0) {
                        $('#breakdown_info').show();
                        $('#detail_breakdown_hours').text(data.breakdown_hours);
                    } else {
                        $('#breakdown_info').hide();
                    }
                    $('#detail_start_date').text(data.start_date || '-');
                    $('#detail_start_time').text(data.start_time || '-');
                    $('#detail_end_date').text(data.end_date || '-');
                    $('#detail_shift').text(data.shift_name || '-');
                    if (data.is_break == 1 || data.quantity <= 1) {
                        $('#splitWorkOrderBtn').hide();
                    } else {
                        $('#splitWorkOrderBtn').show();
                    }
                }

                $('#editWorkOrderBtn').on('click', function() {
                    if (!currentTaskDetails) return;
                    $('#workOrderDetailModal').modal('hide');
                    $('#edit_task_id').val(currentTaskDetails.task_id);
                    $('#edit_priority').val(currentTaskDetails.priority);
                    $('#edit_machine').val(currentTaskDetails.machine_id);
                    $('#edit_setup_hours').val(currentTaskDetails.setup_hours);
                    $('#edit_start_date').val(currentTaskDetails.start_date);
                    $('#edit_quantity').val(currentTaskDetails.quantity);
                    const editModal = new bootstrap.Modal(document.getElementById('editWorkOrderModal'));
                    editModal.show();
                });

                $('#saveEditBtn').on('click', function() {
                    const formData = {
                        task_id: $('#edit_task_id').val(),
                        priority: $('#edit_priority').val(),
                        machine_id: $('#edit_machine').val(),
                        setup_hours: $('#edit_setup_hours').val(),
                        total_hours: $('#edit_total_hours').val(),
                        start_date: $('#edit_start_date').val(),
                        quantity: $('#edit_quantity').val()
                    };
                    const $btn = $(this);
                    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...');
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=update_cnc_task",
                        method: "POST",
                        data: formData,
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                alert('Work order updated successfully!');
                                $('#editWorkOrderModal').modal('hide');
                                location.reload();
                            } else {
                                alert('Error: ' + (response.message || 'Failed to update work order'));
                                $btn.prop('disabled', false).html('<i class="fas fa-save me-2"></i>Save Changes');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error:", error);
                            alert('Error updating work order: ' + error);
                            $btn.prop('disabled', false).html('<i class="fas fa-save me-2"></i>Save Changes');
                        }
                    });
                });

                $('#deleteWorkOrderBtn').on('click', function() {
                    if (!currentTaskDetails) return;
                    if (!confirm('Are you sure you want to delete this work order? This action cannot be undone.')) {
                        return;
                    }
                    const $btn = $(this);
                    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Deleting...');
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=delete_cnc_task",
                        method: "POST",
                        data: { task_id: currentTaskDetails.task_id, work_order_id: currentTaskDetails.work_order_id, part_id: currentTaskDetails.part_id },
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                alert('Work order deleted successfully!');
                                $('#workOrderDetailModal').modal('hide');
                                location.reload();
                            } else {
                                alert('Error: ' + (response.message || 'Failed to delete work order'));
                                $btn.prop('disabled', false).html('<i class="fas fa-trash me-2"></i>Delete');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error:", error);
                            alert('Error deleting work order: ' + error);
                            $btn.prop('disabled', false).html('<i class="fas fa-trash me-2"></i>Delete');
                        }
                    });
                });

                $('#splitWorkOrderBtn').on('click', function() {
                    if (!currentTaskDetails) return;
                    $('#workOrderDetailModal').modal('hide');
                    $('#split_task_id').val(currentTaskDetails.task_id);
                    $('#split_current_quantity').text(currentTaskDetails.quantity);
                    const maxSplitQty = currentTaskDetails.quantity - 1;
                    if (maxSplitQty < 1) {
                        $('#split_quantity').prop('disabled', true);
                        $('#split_error').text('This work order cannot be split (quantity is 1)').show();
                    } else {
                        $('#split_quantity').prop('disabled', false).attr('max', maxSplitQty);
                    }
                    $('#split_quantity').val('');
                    $('#split_preview').hide();
                    $('#split_error').hide();
                    $('#splitWorkOrderModal').modal('show');
                });

                $('#split_quantity').on('input', function() {
                    const splitQty = parseFloat($(this).val());
                    const currentQty = parseFloat(currentTaskDetails.quantity);
                    const setupHours = parseFloat(currentTaskDetails.setup_hours);
                    const totalHours = parseFloat(currentTaskDetails.total_hours);
                    $('#split_error').hide();
                    if (!splitQty || splitQty <= 0) {
                        $('#split_preview').hide();
                        return;
                    }
                    if (splitQty >= currentQty) {
                        $('#split_error').text('Split quantity must be less than current quantity (' + currentQty + ')').show();
                        $('#split_preview').hide();
                        return;
                    }
                    if (splitQty < 1) {
                        $('#split_error').text('Split quantity must be at least 1').show();
                        $('#split_preview').hide();
                        return;
                    }
                    const hoursWithoutSetup = totalHours - setupHours;
                    const hoursPerUnit = hoursWithoutSetup / currentQty;
                    const remainingQty = currentQty - splitQty;
                    const remainingHours = (remainingQty * hoursPerUnit) + setupHours;
                    const splitHours = (splitQty * hoursPerUnit) + setupHours;
                    $('#preview_remaining_qty').text(remainingQty.toFixed(0));
                    $('#preview_remaining_hours').text(remainingHours.toFixed(2) + 'h');
                    $('#preview_split_qty').text(splitQty.toFixed(0));
                    $('#preview_split_hours').text(splitHours.toFixed(2) + 'h');
                    $('#split_preview').show();
                });

                $('#confirmSplitBtn').on('click', function() {
                    const taskId = $('#split_task_id').val();
                    const splitQty = parseFloat($('#split_quantity').val());
                    if (!splitQty || splitQty <= 0) {
                        $('#split_error').text('Please enter a valid split quantity').show();
                        return;
                    }
                    const $btn = $(this);
                    $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Splitting...');
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=split_cnc_work_order",
                        method: "POST",
                        data: { task_id: taskId, split_quantity: splitQty },
                        dataType: "json",
                        success: function(response) {
                            if (response.success) {
                                alert('Work order split successfully!\n\n' +
                                      'Original WO: ' + response.original_quantity + ' units (' + response.original_hours + 'h)\n' +
                                      'New WO: ' + response.split_quantity + ' units (' + response.split_hours + 'h)');
                                $('#splitWorkOrderModal').modal('hide');
                                location.reload();
                            } else {
                                $('#split_error').text(response.message || 'Failed to split work order').show();
                                $btn.prop('disabled', false).html('<i class="fas fa-check me-2"></i>Confirm Split');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX Error:", error);
                            $('#split_error').text('Error splitting work order: ' + error).show();
                            $btn.prop('disabled', false).html('<i class="fas fa-check me-2"></i>Confirm Split');
                        }
                    });
                });
            </script>

            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
            <script>
                $(document).ready(function() {
                    $(document).on('change', '.machine-employee-select', function() {
                        const employeeId = $(this).val();
                        const machineId = $(this).closest('.employee-select-wrapper').data('machine-id');
                        if (!employeeId || !machineId) {
                            return;
                        }
                        const $wrapper = $(this).closest('.card-body');
                        $wrapper.find('.employee-display').html('<i class="fas fa-spinner fa-spin"></i> Saving...');
                        // ajax call for saving assignment currently disabled
                    });
                });
            </script>

           
            <div class="modal fade" id="breakModal" tabindex="-1" aria-labelledby="breakModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="breakModalLabel">Add Machine Break</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="breakForm">
                                <div class="mb-3">
                                    <label for="breakMachine" class="form-label">Machine</label>
                                    <select class="form-select" id="breakMachine" required>
                                        <option value="">Select Machine</option>
                                        <?php foreach ($taskNames as $taskKey => $taskName):
                                            $parts = explode('-', $taskKey);
                                            $machineId = $parts[0];
                                            $tableId = $parts[1];
                                            if ($tableId == 1): ?>
                                        <option value="<?php echo $machineId; ?>">
                                            <?php echo explode(' - ', $taskName)[0]; ?>
                                        </option>
                                        <?php endif; ?>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="breakTable" class="form-label">Table</label>
                                    <select class="form-select" id="breakTable" required>
                                        <option value="1">Table 1</option>
                                        <option value="2">Table 2</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="breakDuration" class="form-label">Duration (hours)</label>
                                    <input type="number" class="form-control" id="breakDuration" min="0.5" max="10" step="0.5" required>
                                    <div class="form-text">Minimum 1 hours, Maximum 10 hours</div>
                                </div>
                                <div class="mb-3">
                                    <label for="breakReason" class="form-label">Reason</label>
                                    <textarea class="form-control" id="breakReason" rows="2"></textarea>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="saveBreakBtn">Save Break</button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="modal fade" id="startBreakdownModal" tabindex="-1" aria-labelledby="startBreakdownModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="startBreakdownModalLabel">Start Machine Breakdown</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="startBreakdownForm">
                                <div class="mb-3">
                                    <label for="startBreakdownMachine" class="form-label">Machine</label>
                                    <select class="form-select" id="breakdownMachine" required>
                                        <option value="">Select Machine</option>
                                        <?php foreach ($taskNames as $taskKey => $taskName):
                                            $parts = explode('-', $taskKey);
                                            $machineId = $parts[0];
                                            if ($parts[1] == 1): ?>
                                        <option value="<?php echo $machineId; ?>"><?php echo explode(' - ', $taskName)[0]; ?></option>
                                        <?php endif; endforeach; ?>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="breakdownReason" class="form-label">Breakdown Reason</label>
                                    <?php
                                    echo Keycode::getKeycodeListValue(
                                        "breakdown_reason",
                                        "",
                                        "100%",
                                        "Please Select",
                                        "id",
                                        "code",
                                        "breakdown_reason",
                                        "",
                                        "form-select",
                                        false,
                                        "required"
                                    );
                                    ?>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-danger" id="confirmStartBreakdownBtn">Start Breakdown</button>
                        </div>
                    </div>
                </div>
            </div>

         
            <div class="modal fade" id="stopBreakdownModal" tabindex="-1" aria-labelledby="stopBreakdownModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="stopBreakdownModalLabel">Stop Machine Breakdown</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="stopBreakdownForm">
                                <div class="mb-3">
                                    <label for="stopBreakdownMachine" class="form-label">Machine</label>
                                    <select class="form-select" id="stopBreakdownMachine" required>
                                        <option value="">Select Machine</option>
                                        <?php
                                        $activeBreakdownMachines = [];
                                        $breakdownQuery = "SELECT DISTINCT mb.machine_id, sd.resource_code
                                                         FROM machine_breakdown mb
                                                         JOIN station_detail_table sd ON mb.machine_id = sd.id
                                                         WHERE mb.is_active = 1";
                                        $breakdownResult = mysqli_query($conn, $breakdownQuery);
                                        while ($row = mysqli_fetch_assoc($breakdownResult)) {
                                            $activeBreakdownMachines[$row['machine_id']] = $row['resource_code'];
                                        }
                                        foreach ($activeBreakdownMachines as $machineId => $machineName): ?>
                                        <option value="<?php echo $machineId; ?>">
                                            <?php echo $machineName; ?> (Active Breakdown)
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="alert alert-warning">
                                    <i class="fas fa-exclamation-triangle"></i>
                                    This will stop the breakdown and recalculate affected work orders.
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-success" id="confirmStopBreakdownBtn">Stop Breakdown</button>
                        </div>
                    </div>
                </div>
            </div>

            <script>
                // breakdown start/stop functionality
                document.getElementById('startBreakdownBtn').addEventListener('click', function() {
                    var startBreakdownModal = new bootstrap.Modal(document.getElementById('startBreakdownModal'));
                    startBreakdownModal.show();
                });

                document.getElementById('stopBreakdownBtn').addEventListener('click', function() {
                    var stopBreakdownModal = new bootstrap.Modal(document.getElementById('stopBreakdownModal'));
                    stopBreakdownModal.show();
                });

                document.getElementById('confirmStartBreakdownBtn').addEventListener('click', function() {
                    const machineId = document.getElementById('startBreakdownMachine').value;
                    const reason = document.getElementById('breakdown_reason').value;
                    alert(reason);
                    if (!machineId || !reason) {
                        alert('Please select a machine and breakdown reason');
                        return;
                    }
                    const breakdownData = { machine_id: machineId, breakdown_reason: reason };
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=start_machine_breakdown",
                        method: 'POST',
                        data: breakdownData,
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                alert('Breakdown started successfully');
                                $('#startBreakdownModal').modal('hide');
                                document.getElementById('startBreakdownForm').reset();
                                window.location.reload();
                            } else {
                                alert('Error starting breakdown: ' + response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            alert('Error starting breakdown: ' + error);
                        }
                    });
                });

                $('#startBreakdownModal').on('show.bs.modal', function() {
                    document.getElementById('startBreakdownForm').reset();
                });

                document.getElementById('confirmStopBreakdownBtn').addEventListener('click', function() {
                    const machineId = document.getElementById('stopBreakdownMachine').value;
                    if (!machineId) {
                        alert('Please select a machine with active breakdown');
                        return;
                    }
                    const breakdownData = { machine_id: machineId };
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=stop_machine_breakdown",
                        method: 'POST',
                        data: breakdownData,
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                alert('Breakdown stopped successfully');
                                $('#stopBreakdownModal').modal('hide');
                                window.location.reload();
                            } else {
                                alert('Error stopping breakdown: ' + response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            alert('Error stopping breakdown: ' + error);
                        }
                    });
                });

                function refreshBreakdownStatus() {
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=get_breakdown_status",
                        method: 'GET',
                        dataType: 'json',
                        success: function(response) {
                            console.log('Breakdown status updated', response);
                        }
                    });
                }
                // auto-refresh breakdown status every 2 minutes
                setInterval(refreshBreakdownStatus, 120000);
            </script>

            <script>
                function loadInventoryStatus() {
                    const tasks = [];
                    document.querySelectorAll('.gantt-task:not(.break-task)').forEach(task => {
                        tasks.push({ task_id: task.dataset.taskId, part_id: task.dataset.partId, work_order_id: task.dataset.workOrderId });
                    });
                    console.log('Sending tasks for inventory check:', tasks);
                    if (tasks.length === 0) return;
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_get_workorders&action=get_inventory_status",
                        method: 'POST',
                        data: { tasks: JSON.stringify(tasks) },
                        dataType: 'json',
                        success: function(response) {
                            console.log('Inventory response:', response);
                            if (response.status === 'success') {
                                updateDotIndicators(response.inventory_status);
                            } else {
                                console.error('Inventory error:', response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('AJAX Error:', error);
                            console.log('Response text:', xhr.responseText);
                        }
                    });
                }

                function updateDotIndicators(inventoryStatus) {
                    Object.keys(inventoryStatus).forEach(taskId => {
                        const dotClass = inventoryStatus[taskId];
                        const taskElement = document.querySelector(`.gantt-task[data-task-id="${taskId}"]`);
                        if (taskElement) {
                            const existingDot = taskElement.querySelector('.dot-indicator');
                            if (existingDot) {
                                existingDot.classList.remove('inventory-loading', 'red-dot-indicator', 'green-dot-indicator', 'blue-dot-indicator');
                                existingDot.innerHTML = '';
                                existingDot.classList.add(dotClass);
                            }
                        }
                    });
                }

                $(document).ready(function() {
                    setTimeout(loadInventoryStatus, 500);
                    document.addEventListener('taskMoved', loadInventoryStatus);
                });
            </script>

            <script>
                $('body').addClass('sidebar-collapse');
                let draggedTask = null;
                let highlightedNeighbor = null;

                document.querySelectorAll('.gantt-task').forEach(task => {
                    task.addEventListener('dragstart', (e) => {
                        draggedTask = task;
                        task.classList.add('dragging');
                        console.log('Dragging task with priority:', task.dataset.priority);
                    });
                    task.addEventListener('dragend', (e) => {
                        task.classList.remove('dragging');
                        if (highlightedNeighbor) {
                            highlightedNeighbor.classList.remove('highlight-border');
                            highlightedNeighbor = null;
                        }
                    });
                });

                document.querySelectorAll('.gantt-row').forEach(row => {
                    row.addEventListener('dragover', (e) => {
                        e.preventDefault();
                        row.classList.add('drop-target');
                        if (!draggedTask) return;
                        const dropX = e.clientX - row.getBoundingClientRect().left;
                        const tasks = [...row.querySelectorAll('.gantt-task')];
                        const otherTasks = tasks.filter(t => t !== draggedTask);
                        otherTasks.sort((a, b) => parseFloat(a.style.left) - parseFloat(b.style.left));
                        if (highlightedNeighbor) {
                            highlightedNeighbor.classList.remove('highlight-border');
                            highlightedNeighbor = null;
                        }
                        for (let i = 0; i < otherTasks.length; i++) {
                            const task = otherTasks[i];
                            const taskLeft = parseFloat(task.style.left);
                            const taskRight = taskLeft + parseFloat(task.style.width);
                            if (taskRight < dropX) {
                                highlightedNeighbor = task;
                            } else {
                                break;
                            }
                        }
                        if (highlightedNeighbor) {
                            highlightedNeighbor.classList.add('highlight-border');
                        }
                    });

                    row.addEventListener('dragleave', (e) => {
                        row.classList.remove('drop-target');
                        if (highlightedNeighbor) {
                            highlightedNeighbor.classList.remove('highlight-border');
                            highlightedNeighbor = null;
                        }
                    });

                    row.addEventListener('drop', (e) => {
                        e.preventDefault();
                        row.classList.remove('drop-target');
                        if (!draggedTask) return;
                        const dropX = e.clientX - row.getBoundingClientRect().left;
                        const tasks = [...row.querySelectorAll('.gantt-task')];
                        const otherTasks = tasks.filter(t => t !== draggedTask);
                        otherTasks.sort((a, b) => parseFloat(a.style.left) - parseFloat(b.style.left));
                        let leftNeighbor = null;
                        for (let i = 0; i < otherTasks.length; i++) {
                            const task = otherTasks[i];
                            const taskLeft = parseFloat(task.style.left);
                            const taskRight = taskLeft + parseFloat(task.style.width);
                            if (taskRight < dropX) {
                                leftNeighbor = task;
                            } else {
                                break;
                            }
                        }
                        if (highlightedNeighbor) {
                            highlightedNeighbor.classList.remove('highlight-border');
                            highlightedNeighbor = null;
                        }
                        const taskId = draggedTask.dataset.taskId;
                        const newMachineId = row.dataset.machineId;
                        const newTableId = row.dataset.tableId;
                        const partId = draggedTask.dataset.partId;
                        const workOrderId = draggedTask.dataset.workOrderId;
                        const leftNeighborPriority = leftNeighbor ? leftNeighbor.dataset.priority : null;
                        const leftNeighborTaskId = leftNeighbor ? leftNeighbor.dataset.taskId : null;
                        const newPosition = dropX;
                        $.ajax({
                            url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=update_cnc_task_priority",
                            method: 'POST',
                            data: {
                                task_id: taskId,
                                new_machine_id: newMachineId,
                                new_table_id: newTableId,
                                part_id: partId,
                                work_order_id: workOrderId,
                                left_neighbor_priority: leftNeighborPriority,
                                left_neighbor_task_id: leftNeighborTaskId,
                                new_position: newPosition
                            },
                            dataType: 'json',
                            success: function(response) {
                                if (response.status === 'success') {
                                    loadGanttTasks();
                                } else {
                                    window.location.reload();
                                    console.log("h77ii");
                                }
                            }
                        });
                    });
                });

                let scrollInterval = null;
                const ganttScrollable = document.querySelector('.gantt-scrollable-content');
                const scrollSpeed = 20;
                const scrollMargin = 50;

                function startAutoScroll(direction) {
                    if (scrollInterval) clearInterval(scrollInterval);
                    scrollInterval = setInterval(() => {
                        if (direction === 'left') {
                            ganttScrollable.scrollLeft -= scrollSpeed;
                        } else {
                            ganttScrollable.scrollLeft += scrollSpeed;
                        }
                    }, 20);
                }

                function stopAutoScroll() {
                    if (scrollInterval) {
                        clearInterval(scrollInterval);
                        scrollInterval = null;
                    }
                }

                document.addEventListener('dragover', (e) => {
                    if (!draggedTask) return;
                    const scrollRect = ganttScrollable.getBoundingClientRect();
                    const xPos = e.clientX - scrollRect.left;
                    if (xPos < scrollMargin) {
                        startAutoScroll('left');
                    } else if (xPos > (scrollRect.width - scrollMargin)) {
                        startAutoScroll('right');
                    } else {
                        stopAutoScroll();
                    }
                });

                document.addEventListener('dragend', () => {
                    stopAutoScroll();
                });

                document.addEventListener('drop', () => {
                    stopAutoScroll();
                });
            </script>

            <script>
                // vertical auto-scroll (right panel)
                let verticalScrollInterval = null;
                const verticalScrollSpeed = 30;
                const verticalScrollMargin = 80;
                const rightPanel = document.getElementById('right-panel');

                function startVerticalScroll(direction) {
                    if (verticalScrollInterval) clearInterval(verticalScrollInterval);
                    verticalScrollInterval = setInterval(() => {
                        if (direction === 'up') {
                            rightPanel.scrollTop -= verticalScrollSpeed;
                        } else {
                            rightPanel.scrollTop += verticalScrollSpeed;
                        }
                    }, 20);
                }

                function stopVerticalScroll() {
                    if (verticalScrollInterval) {
                        clearInterval(verticalScrollInterval);
                        verticalScrollInterval = null;
                    }
                }

                document.addEventListener('dragover', (e) => {
                    if (!draggedTask || !rightPanel) return;
                    const rect = rightPanel.getBoundingClientRect();
                    const mouseY = e.clientY - rect.top;
                    if (mouseY < verticalScrollMargin) {
                        startVerticalScroll('up');
                    } else if (mouseY > (rect.height - verticalScrollMargin)) {
                        startVerticalScroll('down');
                    } else {
                        stopVerticalScroll();
                    }
                });

                document.addEventListener('dragend', stopVerticalScroll);
                document.addEventListener('drop', stopVerticalScroll);
            </script>

            <script>
                // add break functionality
                document.getElementById('addBreakBtn').addEventListener('click', function() {
                    var breakModal = new bootstrap.Modal(document.getElementById('breakModal'));
                    breakModal.show();
                });

                document.getElementById('saveBreakBtn').addEventListener('click', function() {
                    const machineId = document.getElementById('breakMachine').value;
                    const tableId = document.getElementById('breakTable').value;
                    const duration = parseFloat(document.getElementById('breakDuration').value);
                    const reason = document.getElementById('breakReason').value;
                    if (!machineId || !tableId || isNaN(duration) || duration < 0.5 || duration > 10) {
                        alert('Please fill all fields with valid values');
                        return;
                    }
                    const tasks = [...document.querySelectorAll('.gantt-task')];
                    const machineTasks = tasks.filter(task =>
                        task.dataset.currentMachine === machineId &&
                        task.dataset.currentTable === tableId
                    );
                    let highestPriorityTask = null;
                    if (machineTasks.length > 0) {
                        machineTasks.sort((a, b) => a.dataset.priority - b.dataset.priority);
                        highestPriorityTask = machineTasks[0];
                    }
                    const breakData = {
                        machine_id: machineId,
                        table_id: tableId,
                        duration: duration,
                        reason: reason,
                        highest_priority_task_id: highestPriorityTask ? highestPriorityTask.dataset.taskId : null,
                        highest_priority: highestPriorityTask ? highestPriorityTask.dataset.priority : null
                    };
                    $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=add_cnc_break",
                        method: 'POST',
                        data: breakData,
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                alert('Break added successfully');
                                window.location.reload();
                            } else {
                                alert('Error adding break: ' + response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            alert('Error adding break: ' + error);
                        }
                    });
                });
            </script>

            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
            <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <style>
        .split-container {
            display: flex;
            height: calc(100vh - 60px);
            width: 100%;
        }
        .split-panel {
            flex: 1;
            overflow: auto;
            padding: 10px;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
        }
        #left-panel {
            background-color: #e6f7ff;
            flex: 20;
        }
        #right-panel {
            background-color: #fff2e6;
            flex: 70;
        }
        .split-divider {
            width: 10px;
            background-color: #ccc;
            cursor: col-resize;
        }
        #container {
            display: flex;
            width: 100%;
            height: 100vh;
        }
        #divider {
            width: 5px;
            cursor: col-resize;
            background-color: #aaa;
        }
    </style>

    <script>
        // gantt ajax loader
        let ganttTaskData = {};

        function loadGanttTasks() {
            $.ajax({
                url: site_url + "/modules/machines_management/index.php?page=ajax_actions_for_cnc&action=get_gantt_data",
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        ganttTaskData = response.grouped_tasks;
                        renderAllGanttRows(response.grouped_tasks);
                        attachAllTaskHandlers();
                        setTimeout(loadInventoryStatus, 300);
                    } else {
                        console.error('Gantt data error:', response.message);
                        document.querySelectorAll('.gantt-loading-spinner').forEach(function(el) {
                            el.innerHTML = '<span style="color:red;">Failed to load tasks.</span>';
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Gantt load error:', error);
                    document.querySelectorAll('.gantt-loading-spinner').forEach(function(el) {
                        el.innerHTML = '<span style="color:red;">Error loading tasks.</span>';
                    });
                }
            });
        }

        function renderAllGanttRows(groupedTasks) {
            document.querySelectorAll('.gantt-row').forEach(function(row) {
                var machineId = row.dataset.machineId;
                var tableId   = row.dataset.tableId;
                var groupKey  = machineId + '-' + tableId;
                row.innerHTML = '';
                var tasks = groupedTasks[groupKey];
                if (!tasks || tasks.length === 0) {
                    row.innerHTML = '<div class="no-tasks">No tasks scheduled</div>';
                    return;
                }
                var html = '';
                var cumulativePosition = 0;
                tasks.forEach(function(task) {
                    var allocHours   = parseFloat(task.allocated_hours) || 0;
                    var taskWidth    = allocHours * 80;
                    var leftPosition = cumulativePosition;
                    cumulativePosition += taskWidth;
                    if (task.is_break == 1 || task.is_break === true) {
                        // break task
                        html += '<div class="gantt-task break-task"' +
                            ' draggable="true"' +
                            ' data-task-id="'       + escHtml(String(task.task_id || '')) + '"' +
                            ' data-priority="'      + escHtml(String(task.priority || '')) + '"' +
                            ' data-work-order="'    + escHtml(task.work_order_no || '') + '"' +
                            ' data-part-id="'       + escHtml(String(task.part_id || '')) + '"' +
                            ' data-work-order-id="' + escHtml(String(task.work_order_id || '')) + '"' +
                            ' data-hours="'         + allocHours + '"' +
                            ' data-current-machine="' + escHtml(String(machineId)) + '"' +
                            ' data-current-table="'   + escHtml(String(tableId)) + '"' +
                            ' style="left:' + leftPosition + 'px; width:' + taskWidth + 'px; position:absolute; height:100%; top:0; box-sizing:border-box;">' +
                            '<div class="task-content"><strong>BREAK</strong><br/>' +
                            escHtml(task.break_reason || '') + '<br/>Duration: ' + allocHours + 'h</div>' +
                            '<div class="hour-indicator">' + allocHours + 'h</div>' +
                            '</div>';
                    } else {
                        // normal task
                        var isLateClass      = (task.is_late) ? 'late-task' : 'on-time-task';
                        var breakdownClass   = (task.is_breakdown_affected == 1 || task.is_breakdown_affected === true) ? 'breakdown-affected' : '';
                        var topLine = '';
                        if (!task.parent_ids || task.parent_ids == 0) {
                            topLine = escHtml(task.customer_order_nos || '');
                        } else {
                            topLine = escHtml(task.parent_part_number || '');
                        }
                        var dueDateDisplay = 'N/A';
                        if (task.manufacture_end_date) {
                            dueDateDisplay = formatDate(task.manufacture_end_date);
                        }
                        var breakdownLine = '';
                        if (task.is_breakdown_affected == 1 || task.is_breakdown_affected === true) {
                            breakdownLine = '<div style="color:#ff0000;"><strong>Breakdown Delay: +' +
                                            escHtml(String(task.breakdown_hours || 0)) + 'h</strong></div>';
                        }
                        var hourExtra = '';
                        if (task.is_breakdown_affected == 1 || task.is_breakdown_affected === true) {
                            hourExtra = '<br><small>+' + escHtml(String(task.breakdown_hours || 0)) + 'h delay</small>';
                        }
                        html += '<div class="gantt-task ' + isLateClass + ' ' + breakdownClass + '"' +
                            ' draggable="true"' +
                            ' data-task-id="'       + escHtml(String(task.task_id || '')) + '"' +
                            ' data-priority="'      + escHtml(String(task.priority || '')) + '"' +
                            ' data-work-order="'    + escHtml(task.work_order_no || '') + '"' +
                            ' data-part-id="'       + escHtml(String(task.part_id || '')) + '"' +
                            ' data-work-order-id="' + escHtml(String(task.work_order_id || '')) + '"' +
                            ' data-hours="'         + allocHours + '"' +
                            ' data-current-machine="' + escHtml(String(machineId)) + '"' +
                            ' data-current-table="'   + escHtml(String(tableId)) + '"' +
                            ' style="left:' + leftPosition + 'px; width:' + taskWidth + 'px; position:absolute; height:100%; top:0; box-sizing:border-box;">' +
                            '<div class="dot-indicator red-dot-indicator" data-task-id="' + escHtml(String(task.task_id || '')) + '"></div>' +
                            '<div class="task-content" style="font-size:12px; line-height:1.4;">' +
                                '<div style="margin-bottom:0px;">' + topLine + '</div>' +
                                '<div style="margin-bottom:0px;">' + escHtml(task.work_order_name || '') + '</div>' +
                                '<div style="margin-bottom:0px;">' +
                                    '<strong>Item:</strong> ' + escHtml(task.product_name || '') +
                                    ' &nbsp;&nbsp;|&nbsp;&nbsp; ' +
                                    '<strong>Qty:</strong> ' + escHtml(String(task.quantity || '')) +
                                '</div>' +
                                '<div style="margin-bottom:0px;"><strong>Set Hours:</strong> ' + escHtml(String(task.setup_hours || '')) + '</div>' +
                                breakdownLine +
                                '<div style="margin-bottom:0px;"><strong>Desc:</strong> ' + escHtml(task.manufacture_description || '') + '</div>' +
                                '<div style="margin-bottom:0;"><strong>Due Date:</strong> ' + dueDateDisplay + '</div>' +
                            '</div>' +
                            '<div class="hour-indicator">' + allocHours + 'h' + hourExtra + '</div>' +
                            '</div>';
                    }
                });
                row.innerHTML = html;
            });
        }

        function escHtml(str) {
            var d = document.createElement('div');
            d.textContent = String(str);
            return d.innerHTML;
        }

        function formatDate(dateStr) {
            if (!dateStr) return 'N/A';
            try {
                var d = new Date(dateStr);
                if (isNaN(d.getTime())) return dateStr;
                var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                return d.getDate() + '-' + months[d.getMonth()] + '-' + d.getFullYear();
            } catch(e) {
                return dateStr;
            }
        }

        function attachAllTaskHandlers() {
            document.querySelectorAll('.gantt-task').forEach(function(task) {
                task.addEventListener('dragstart', function(e) {
                    draggedTask = task;
                    task.classList.add('dragging');
                });
                task.addEventListener('dragend', function(e) {
                    task.classList.remove('dragging');
                    if (highlightedNeighbor) {
                        highlightedNeighbor.classList.remove('highlight-border');
                        highlightedNeighbor = null;
                    }
                });
                if (!task.classList.contains('break-task')) {
                    task.style.cursor = 'pointer';
                    task.addEventListener('click', function(e) {
                        if (task.classList.contains('dragging')) return;
                        var taskId      = task.dataset.taskId;
                        var workOrderId = task.dataset.workOrderId;
                        var partId      = task.dataset.partId;
                        var machineId   = task.dataset.currentMachine;
                        if (!taskId) {
                            console.warn('No taskId on clicked task', task);
                            return;
                        }
                        loadWorkOrderDetails(taskId, workOrderId, partId, machineId);
                    });
                }
            });
        }

        $(document).ready(function() {
            loadGanttTasks();
            setInterval(loadGanttTasks, 30000);
        });
    </script>

    <script>
        $(document).ready(function() {
            $('.machine-employee-select').each(function() {
                if (!$(this).hasClass('select2-hidden-accessible')) {
                    $(this).select2({ dropdownParent: $(document.body), width: '100%' });
                }
            });
        });
    </script>

    <script>
        // draggable splitter between left and right panel
        (function() {
            const divider = document.getElementById('divider');
            const leftPanel = document.getElementById('left-panel');
            const rightPanel = document.getElementById('right-panel');
            const container = document.querySelector('.split-container');
            let isDragging = false;

            divider.addEventListener('mousedown', function(e) {
                isDragging = true;
                document.body.style.userSelect = 'none';
                document.body.style.cursor = 'col-resize';
            });

            document.addEventListener('mousemove', function(e) {
                if (!isDragging) return;
                const containerRect = container.getBoundingClientRect();
                const offsetX = e.clientX - containerRect.left;
                const minWidth = 150;
                const maxWidth = containerRect.width - minWidth - divider.offsetWidth;
                const newLeftWidth = Math.max(minWidth, Math.min(offsetX, maxWidth));
                const leftPercent = (newLeftWidth / containerRect.width) * 100;
                const rightPercent = 100 - leftPercent;
                leftPanel.style.flex = 'none';
                rightPanel.style.flex = 'none';
                leftPanel.style.width = leftPercent + '%';
                rightPanel.style.width = rightPercent + '%';
            });

            document.addEventListener('mouseup', function() {
				if (isDragging) {
					isDragging = false;
					document.body.style.userSelect = '';
					document.body.style.cursor = '';
					resizeMachineSelects();
				}
			});
        })();
    </script>
</div>
</div>
</div>