<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ERP Micro Line Planning - Month View</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        body { font-family: 'Segoe UI', sans-serif; background: #f8f9fa; }

        /* Consolidated Sidebar Styles */
        .sidebar, .sidebar1-overlay, .sidebar-overlay {
            position: fixed;
            top: 0;
            height: 100vh;
            overflow-y: auto;
            z-index: 1000;
            transition: all 0.3s ease;
        }
        .sidebar {
            width: 180px;
            background: #fff;
            padding: 15px;
            border-right: 1px solid #ddd;
            left: -220px;
        }

        /* Blur effect for sidebar */
        .sidebar.blurred {
            filter: blur(3px);
            pointer-events: none; /* Disable interactions while blurred */
            transition: filter 0.3s ease;
        }

        .sidebar.open { left: 0; }

        /* Overlay Sidebars */
        .sidebar1-overlay, .sidebar-overlay {
            right: 0;
            width: 100%;
            /* background-color: rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(2px); */
            opacity: 0;
            pointer-events: none;
        }
        .sidebar1-overlay.active, .sidebar-overlay.active {
            opacity: 1;
            pointer-events: auto;
        }
        .sidebar1-content, .sidebar-content {
            position: absolute;
            top: 0;
            right: 0;
            height: 100%;
            background: #fff;
            overflow-y: auto;
            border-left: 1px solid #ddd;
            border-radius: 8px 0 0 8px;
        }
        .sidebar1-content { width: 700px; max-width: 100%; }
        .sidebar-content { width: 600px; max-width: 100%; }


        #splitOrderSidebar {
            position: fixed;
            top: 0;
            right: 0;
            width: 400px;
            height: 100%;
            background: #fff;
            box-shadow: -2px 0 10px rgba(0,0,0,0.1);
            z-index: 1050;
            transform: translateX(100%);
            transition: transform 0.3s ease-in-out;
        }
        #splitOrderSidebar.active {
            transform: translateX(0);
        }


        /* Content and Container */
        .content {
            margin-left: 0;
            margin-right: 0px;
            padding: 15px;
            transition: margin-left 0.3s ease;
        }
        .content.shrink { margin-left: 150px; }
        .container, .container-lg, .container-md, .container-sm, .container-xl, .container-xxl {
            width: 100%;
            min-height: 100vh;
            margin-top: 70px;
            display: flex;
            flex-direction: column;
        }

        /* Navigation */
        .nav {
            display: flex;
            align-items: center;
            padding: 8px 10px;
            background-color: rgb(131, 206, 224); /* Light background for navbar */
            width: 100%;
            height: 50px;
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }

        /* Container for sidebar toggle button */
        .sidebar-toggle-container {
            position: absolute;
            left: 190px; /* Default position assuming sidebar width is 250px when open */
            transition: left 0.3s ease; /* Smooth transition when sidebar toggles */
        }

        .home-bar {
            position: absolute;
            left: 230px; /* Default position assuming sidebar width is 250px when open */
            transition: left 0.3s ease; /* Smooth transition when sidebar toggles */
             z-index: 1001;
            
             
        }

        .mac-bar{
            position: absolute;
            left: 280px; /* Default position assuming sidebar width is 250px when open */
            transition: left 0.3s ease; /* Smooth transition when sidebar toggles */
            z-index: 1001;

        }


        /* Adjust toggle button position when sidebar is closed */
        .sidebar:not(.open) + .nav .sidebar-toggle-container {
            left: 0; /* Move to left edge when sidebar is closed */
        }

        #navbarTitle {
            margin-left: 450px; /* Adjust based on sidebar width and toggle position */
            transition: margin-left 0.3s ease; /* Match sidebar toggle transition */
        }

        .sidebar:not(.open) + .nav #navbarTitle {
            margin-left: 60px; /* Adjust based on toggle button width */
        }

        @media (max-width: 1270px) {
            #navbarTitle {
                display: none !important; /* Hide title on smaller screens */
            }
        }

        /* Container for other navbar items, aligned to the right */
        .nav-items {
            display: flex;
            align-items: center;
            margin-left: auto; /* Pushes items to the right */
        }

        .form-control.flatpickr {
            font-size: 14px;
            padding: 6px;
        }

        .btn.btn-light {
            padding: 6px 12px;
            font-size: 14px;
        }

        .btn.dropdown-toggle::after { display: none !important; }

        /* Planning Table */
        .planning-table { border-collapse: collapse; }
        .planning-table th, .planning-table td {
            border: 1px solid #ccc;
            text-align: center;
            height: 40px;
            width: 100px;
            background: #fff;
            min-width: 40px;
            vertical-align: middle;
            padding: 4px;
        }

        .planning-table th, .planning-table td {
            width: 60px;
            min-width: 60px;
            max-width: 60px;
            padding: 0;
            box-sizing: border-box;
        }

        .date-header { position: sticky; top: 0; background: #f1f1f1; z-index: 3; }
        .sticky-left { position: sticky; left: 0; z-index: 2; }
        .planning-header th {
            height: 14px;
            line-height: 14px;
            padding: 2px 4px;
            font-size: 10px;
            position: sticky;
            top: 0;
            background: #f1f1f1;
        }
        .weekend { background: #f0f0f0; }
        .conflict { background: #ffcccc; }

        /* Task Bars */
        .task-bar {
            position: absolute;
            background: linear-gradient(135deg, #4CAF50, #3e8e41);
            border-radius: 8px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.3);
            color: #fff;
            text-align: center;
            font-weight: 500;
            cursor: grab;
            user-select: none;
            transition: box-shadow 0.2s;
            height: 30px;
            line-height: 30px;
        }
        .task-bar-click .task-bar-prefix {
            font-size: 14px !important;
            font-weight: 600;
        }
        .task-bar:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.5); }
        .task-bar-click { display: inline-block; width: 100%; height: 100%; cursor: pointer; }
        .handle {
            position: absolute;
            width: 8px;
            top: 0;
            bottom: 0;
            background: #00000055;
            cursor: ew-resize;
        }
        .handle.left { left: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; }
        .handle.right { right: 0; border-top-right-radius: 8px; border-bottom-right-radius: 8px; }

        .date-header{
            width:150%;
        }

        /* Dots for Task Bars */
        .dot {
            width: 10px;
            height: 10px;
            background-color: #333;
            border-radius: 50%;
            position: absolute;
            cursor: pointer;
            z-index: 2;
        }
        .dot.start { left: -5px; top: 50%; transform: translateY(-50%); }
        .dot.end { right: -5px; top: 50%; transform: translateY(-50%); }
        .dot:hover { background-color: #666; }
        .dot.connecting { background-color: #ff0000; }

        /* Dependency Lines */
        /* .dependency-line {
            position: absolute;
            border: 1px solid #ff0000;
            z-index: 1;
        } */

        /* Tooltip */
        .task-bar:hover::after {
            content: attr(data-tooltip);
            position: absolute;
            top: -30px;
            left: 100%;
            transform: translateX(-50%);
            background: #333;
            color: #fff;
            padding: 5px;
            border-radius: 4px;
            font-size: 12px;
            white-space: nowrap;
            z-index: 10;
            display:none;
            
        }

        .backlog-item:hover {
            background: #0d6efd; /* Bootstrap primary blue or any color you like */
            color: #fff;
            box-shadow: 0 4px 12px rgba(13,110,253,0.3);
            transform: scale(1.03);
            transition: background 0.2s, box-shadow 0.2s, transform 0.2s;
        }

        td[scope="row"] {
            border-right: 2px solid #ddd !important; /* or #ddd / #999 depending on your style */
            background: #fff;
            z-index: 4;
        }

        #task-layer {
            position: relative;
            z-index: 50; /* make sure this is higher than sticky sidebar */
        }

        .task-bar {
            position: relative; /* needed for ::after to behave correctly */
            z-index: 20; /* just in case */
        }

        td[scope="row"] {
            z-index: 1; /* lower than tooltip and task-bar */
        }

        /* Backlog Items */
        .backlog-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px;
            background: rgb(131, 206, 224);
            color: white;
            padding: 8px 10px;
            border-radius: 6px;
            margin-bottom: 10px;
            cursor: pointer;
            text-align: center;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .backlog-item .spinner-border {
            margin-left: 10px;
        }

        .backlog-item.out-of-bounds {
            background: #ff9800 !important;
        }

        /* Card and Miscellaneous */
        .card-title { font-size: 1.2rem; }
        .side-bar { margin: 0.5rem 0 0 1rem; }

        .card.w-105.ms-4.shadow-sm {
            height: 88vh; /* Adjust this value to increase the height */
        }

        #planning-grid tfoot tr {
            position: sticky;
            bottom: 0;
            background: #f8f9fa;
            z-index: 98;
        }

        .footer-cell{
            text-align:left !important;
        }

        #tailor_qty_display, #planned_tailor_qty_display {
            color: #cbf078;
        }

        #floating-chatbot-card {
            position: fixed;
            bottom: 90px;
            right: 30px;
            width: 620px;
            z-index: 2001;
            border-radius: 12px;
            animation: slideInUp 0.3s;
        }
        @keyframes slideInUp {
            from { transform: translateY(100px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        /* Animation */
        @keyframes slideInRight {
            from { transform: translateX(100%); }
            to { transform: translateX(0); }
        }
        .buyer-filter-dropdown { width: 120px; font-size: 14px; }
        
        /* Conflict styling */
        .task-bar.line-conflict {
            animation: conflictPulse 2s infinite;
        }
        
        @keyframes conflictPulse {
            0% { box-shadow: 0 2px 8px rgba(255, 152, 0, 0.6); }
            50% { box-shadow: 0 2px 12px rgba(255, 152, 0, 0.8); }
            100% { box-shadow: 0 2px 8px rgba(255, 152, 0, 0.6); }
        }

        #order-details-dynamic .row span,
        #order-details-dynamic .row div {
            font-size: 10px !important;
        }

        @page { size: A4 landscape; margin: 10mm; }
        thead th {
            position: static !important;
            background: #eee;
        }

        @media print {
            #planning-area {
                transform: scale(0.9);
                transform-origin: top left;
            }
        }

        .task-bar.task-highlight {
            background: linear-gradient(135deg, #ffc107, #ff9800) !important;
            border: 2px solid #222;
            transform: scale(1.05);
            opacity: 1;
            z-index: 1000 !important;
        }

        .task-bar.task-blur {
            opacity: 0.2;
            filter: grayscale(80%) blur(1px);
            z-index: 0 !important;
        }

        #toggle_task_update:hover {
            text-decoration: underline;
            color: #0b5ed7; /* darker shade of blue */
            transition: all 0.2s ease-in-out;
        }

        #custom-tooltip {
            position: fixed;
            top: 72px;
            right: 39px;
            background-color: #fff9c4;
            color: #333;
            padding: 8px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 1000;
            display: none;
            max-width: 550px;
            line-height: 1.3;
        }
        .tooltip-columns {
            display: flex;
            gap: 10px;
        }
        .tooltip-column {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
    </style>
</head>
<body>
    @php
        $empl_no = Session::get('empl_id');
        $empl_name = Session::get('emp_name');
    @endphp
    <div class="nav d-flex align-items-center">
        <div class="sidebar-toggle-container">
            <button class="btn btn-light" type="button" id="sidebarToggle">
                <i class="bi bi-layout-sidebar-inset"></i>
            </button>
        </div>
       <div class="home-bar">
            <a href="/dashboard" class="btn btn-light ms-2" title="Dashboard">
                        <i class="bi bi-house "></i>
            </a>
        </div>
        <div class="mac-bar">
            <a href="/cap_plan" target="_blank" class="btn btn-light ms-2" title="Macroplan">
                        <i class="bi bi-calendar"></i>
            </a>
        </div>
        <div class="d-flex align-items-center" id="navbarTitle">
            <span class="fw-bold text-white">Micro Planning portal - Garments Division</span>
        </div>
        <div class="nav-items d-flex align-items-center ms-auto">
            <div class="d-flex align-items-center gap-2">
                <!-- <button class="btn btn-light p-1" title="Zoom In" id="zoomIn"><i class="bi bi-zoom-in"></i></button>
                <button class="btn btn-light p-1" title="Zoom Out" id="zoomOut"><i class="bi bi-zoom-out"></i></button> -->
                <!-- <button class="d-none btn btn-sm btn-light" title="Inspect / Details" id="showDetailsBtn">
                    <i class="bi bi-search"></i>
                </button> -->
                <div class="dropdown">
                    <button class="btn btn-sm btn-light p-1 dropdown-toggle" type="button" id="searchBtntask" title="Search">
                        <i class="bi bi-search"></i>
                    </button>
                    <button class="btn btn-sm btn-light p-1 dropdown-toggle d-none" type="button" id="searchBtn" title="Search" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-search"></i>
                    </button>
                    <div class="dropdown-menu no-print p-2" aria-labelledby="searchBtn">
                        <div class="d-flex gap-2">
                            <input type="text" id="taskSearch" style="height: 30px; font-size: 10px" class="form-control w-auto" placeholder="🔍 Search OCN / Item / Color..." oninput="filterTaskbars(this.value)" />
                            <button class="btn btn-sm btn-light p-0" style="height: 25px; width: 40px; font-size: 10px" onclick="clearTaskbarFilter()">Clear</button>
                        </div>
                    </div>
                </div>
                <button class="d-none btn btn-sm btn-light" title="Split" id="splitOrderBtn">
                    <i class="bi bi-layout-split"></i>
                </button>
                <button class="d-none btn btn-sm btn-light" title="Reset" id="resetDetailsBtn">
                    <i class="bi bi-arrow-clockwise"></i>
                </button>
                <button class="d-none btn btn-light p-1" title="Cut"><i class="bi bi-scissors"></i></button>
                <button class="d-none btn btn-light p-1" onclick="printGanttWithTasks()" title="Print"><i class="bi bi-printer"></i></button>
                <button class="d-none btn btn-light p-1" title="Filter"><i class="bi bi-funnel"></i></button>
                <button class="d-none btn btn-light p-1" id="deleteBtn" title="Delete"><i class="bi bi-trash"></i></button>
                <button class="btn btn-success p-1" id="saveBtn" title="Save"><i class="bi bi-save"></i></button>
                <button class="btn bg-light btn-sm " title="Previous" id="prevMonth"><</button>
                <button class="btn bg-light btn-sm me-2" title="Next" id="nextMonth">></button>
            </div>
            <div class="d-none me-2">
                <div class="input-group">
                    <span class="input-group-text"><i class="bi bi-calendar"></i></span>
                    <input type="text" class="form-control flatpickr" id="start-date" placeholder="Select start date" />
                </div>
            </div>
            <div class="me-2">
                <div class="input-group">
                    <span class="d-none input-group-text"><i class="bi bi-calendar"></i></span>
                    <input type="text" class="form-control flatpickr text-center rounded" id="end-date" placeholder="Select end date">
                </div>
            </div>
            <div class="dropdown">
                <button class="btn btn-light dropdown-toggle" type="button" id="factoryDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                    <i class="bi bi-building-gear"></i>
                </button>
                <ul class="dropdown-menu" aria-labelledby="factoryDropdown" style="z-index: 1050;">
                    <li><a class="dropdown-item" href="#">G1</a></li>
                    <li><a class="dropdown-item" href="#">G2</a></li>
                    <li><a class="dropdown-item" href="#">G3</a></li>
                    <li><a class="dropdown-item" href="#">G4</a></li>
                    <li><a class="dropdown-item" href="#">G5</a></li>
                    <li><a class="dropdown-item" href="#">G6</a></li>
                </ul>
            </div>
        </div>
    </div>

    <div class="content shrink pt-0">
        <div class="sidebar open text-center">
            <h5 class="fw-semibold">PO Backlog</h5>
            <div class="d-flex flex-row align-items-center justify-content-center my-2 gap-2">
                <div class="dropdown">
                    <button class="btn btn-light btn-sm dropdown-toggle buyer-filter-dropdown" style="width: 70px; font-size: 10px;" type="button" id="buyerFilterDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person"></i> All
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="buyerFilterDropdown" style="z-index: 1050; font-size: 10px; width: 100px !important"></ul>
                </div>
                <div class="input-group input-group-sm m-1">
                    <!-- 
                 -->
                    <input type="text" class="form-control" id="styleSearchInput" placeholder="Style" style="font-size: 10px;">
                </div>

                <!-- <div class="dropdown">
                        <button class="btn btn-light btn-sm dropdown-toggle style-filter-dropdown" style="width: 80px; font-size: 10px;" type="button" id="styleFilterDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="bi bi-filter"></i> All
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="styleFilterDropdown" style="z-index: 1050; font-size: 10px; width: 150px !important">
                            <li>
                                <input type="text" class="form-control form-control-sm m-1" id="styleSearchInput" placeholder="Search Style" style="font-size: 10px;">
                            </li>
                        </ul>
                    </div> -->
                <!-- <button id="showOcnSearchBtn" class="btn btn-light" type="button" title="Search OCN">
                    <i class="bi bi-search"></i>
                </button> -->
            </div>  
            <input type="text" id="ocnSearchInput" class="form-control mb-2" placeholder="Search OCN..." autocomplete="off" style="display:none;">
            
            <div id="backlog" role="list" aria-label="Purchase Order Backlog"></div>
        </div>

        <div class="container">
            <div class="w-100 mb-3 d-flex flex-row align-items-center gap-2 justify-content-end d-none" style="max-width: 100%;">
                <h5 class="mb-0 me-5 fw-bold text-dark fs-2" style="margin-right: 1rem !important;">ERP Micro Line Planning - Premium Month Header</h5>
                <input type="date" class="form-control flatpickr" id="filter-from-date" value="2025-01-01" style="max-width: 170px;">
                <span>–</span>
                <input type="date" class="form-control" id="filter-to-date" value="2025-12-31" style="max-width: 170px;">
                <select class="form-select" id="filter-unit" style="max-width: 90px;"></select>
                <select class="form-select" id="filter-ocn" style="max-width: 140px;">
                    <option value="">Select OCN</option>
                    <option value="OCN4283">OCN4283</option>
                    <option value="OCN4303">OCN4303</option>
                    <option value="OCN4336">OCN4336</option>
                </select>
                <select class="form-select" id="filter-line" style="max-width: 140px;">
                    <option value="">Filter by Line</option>
                    <option value="1">Line 1</option>
                    <option value="2">Line 2</option>
                </select>
            </div>

            <div class="card w-105 ms-4 shadow-sm">
                <div class="card-body d-flex justify-content-between align-items-center pb-2">
                <h5 class="card-title fw-semibold mb-0" style="color:#83cee0;"></h5>
                    <!-- <div class="d-flex align-items-center gap-2">
                        <button class="btn btn-light p-1" title="Zoom In" id="zoomIn"><i class="bi bi-zoom-in"></i></button>
                        <button class="btn btn-light p-1" title="Zoom Out" id="zoomOut"><i class="bi bi-zoom-out"></i></button> 
                        <div class="dropdown">
                            <button class="btn btn-sm btn-light p-1 dropdown-toggle" type="button" id="searchBtn" title="Search" data-bs-toggle="dropdown" aria-expanded="false">
                                <i class="bi bi-search"></i>
                            </button>
                            <div class="dropdown-menu no-print p-2" aria-labelledby="searchBtn">
                                <div class="d-flex gap-2">
                                    <input type="text" id="taskSearch" style="height: 30px; font-size: 10px" class="form-control w-auto" placeholder="🔍 Search OCN / Item / Color..." oninput="filterTaskbars(this.value)" />
                                    <button class="btn btn-sm btn-light p-0" style="height: 25px; width: 40px; font-size: 10px" onclick="clearTaskbarFilter()">Clear</button>
                                </div>
                            </div>
                        </div>
                        <button class="d-none btn btn-sm btn-light" title="Split" id="splitOrderBtn">
                            <i class="bi bi-layout-split"></i>
                        </button>
                        <button class="d-none btn btn-sm btn-light" title="Reset" id="resetDetailsBtn">
                            <i class="bi bi-arrow-clockwise"></i>
                        </button>
                        <button class="d-none btn btn-light p-1" title="Cut"><i class="bi bi-scissors"></i></button>
                        <button class="d-none btn btn-light p-1" onclick="printGanttWithTasks()" title="Print"><i class="bi bi-printer"></i></button>
                        <button class="d-none btn btn-light p-1" title="Filter"><i class="bi bi-funnel"></i></button>
                        <button class="d-none btn btn-light p-1" id="deleteBtn" title="Delete"><i class="bi bi-trash"></i></button>
                        <button class="btn btn-success p-1" title="Save"><i class="bi bi-save"></i></button>
                        <button class="btn btn-outline-secondary btn-sm ms-2" title="Previous" id="prevMonth"><</button>
                        <button class="btn btn-outline-secondary btn-sm" title="Next" id="nextMonth">></button>
                    </div> -->
                </div>
                <div class="card-body p-2">
                    <div class="table-responsive position-relative flex-grow-1 ms-0 pb-2 ps-0" id="planning-area" style="overflow: auto; height: 78vh;">
                        <table class="planning-table" id="planning-grid" role="grid" aria-label="Production Line Planning Grid">
                            <thead id="gantt-header"></thead>
                            <tbody id="gantt-body"></tbody>
                            <tfoot id="gantt-footer"></tfoot>
                        </table>
                        <div id="task-layer" class="position-absolute top-0 start-0" style="z-index: 3;"></div>
                        <div id="dependency-layer" class="position-absolute top-0 start-0" style="z-index: 1;"></div>
                    </div>
                </div>    
            </div>

            <!-- Default Placeholder Card (Visible Initially) -->
            <div id="order-details-default " class="card mb-4 mt-3 ms-4 shadow-sm d-none" style="width: 98%; height: 15vh;">
                <div class="card-body">
                    <div class="row mb-1">
                        <div class="col-4">
                            <h5 class="fw-semibold mb-3" style="color:#83cee0;">Order Details</h5>
                            <p class="text-secondary mb-0">Select an order to view details</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Dynamic Card Container (Hidden Initially) -->
            <div id="order-details-dynamic" class="card mb-4 mt-2 ms-4 shadow-sm d-none" style="width: 98.5%; height: auto; display: none;">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-3">

                        <h6 class="fw-semibold mb-0" id="dynamic-ocn-heading" style="color: #83cee0;">-- OCN - Details</h6>

                        <div class="d-flex gap-2">

                            <input id="planned_tailor_input" type="text" placeholder="Enter tailor no" style="width: 100px; height: 20px; font-size: 12px;">

                            <button class="btn btn-sm btn-success p-0" title="Submit" id="submit_tailor_Btn" style="width: 20px; height: 20px; font-size: 12px;">
                                <i class="bi bi-check"></i>
                            </button>

                        </div>

                    </div>
                    <div class="row ms-5" style="font-size: 14px;">
                        <div class="col-md-2">
                            <div class="ord"><b>Item Name:</b> <span id="item_name">--</span></div>
                            <div class="ord"><b>Buyer:</b> <span id="buyer">--</span></div>
                            <div class="ord"><b>Color:</b> <span id="color">--</span></div>
                            <div class="ord"><b>Per Day Qty:</b> <span id="per_day_qty">--</span></div>
                            <div class="ord"><b>Per Day Qty:</b> <span id="Per_Day_Qty">--</span></div>
                            <div class="ord"><b>ColorId:</b> <span id="color_id">--</span></div>
                            <div class="ord"><b>ItemId:</b> <span id="item_id">--</span></div>
                        </div>
                        <div class="col-md-2">
                            <div class="ord"><b>CK Date:</b> <span id="ck_date">--</span></div>
                            <!-- <div class="ord"><b>Inspection Date:</b> <span id="inspection_date">--</span></div> -->
                            <div class="ord"><b>Bom_qty:</b> <span id="bom_qty">--</span></div>
                            <div class="ord"><b>Prod_order_qty</b> <span id="prod_order_qty">--</span></div>
                            <div class="ord"><b>Shipping Date:</b> <span id="shipping_date">--</span></div>
                        </div>
                        <div class="col-md-2">
                            <div class="ord"><b>Order Quantity:</b> <span id="planned_qty">--</span></div>
                            <div class="ord"><b>Balance to Sew:</b> <span id="balance_to_sew">--</span></div>
                            <div class="ord"><b>Balance (minutes):</b> <span id="balance_minutes">--</span></div>
                            <div class="ord"><b>No. of Operators:</b> <span id="no_operators">--</span></div>
                            <div class="ord"><b>No. of Planner Operators:</b> <span id="planner_opr">--</span></div>
                        </div>
                        <div class="col-md-2">
                            <div class="ord"><b>SAM (minutes):</b> <span id="sam">--</span></div>
                            <div class="ord"><b>Machines/Tailor:</b> <span id="machines">--</span></div>
                            <div class="ord"><b>Target Efficiency:</b> <span id="efficiency">--</span></div>
                        </div>
                        <div class="col-md-2">
                            <div class="ord"><b>Special Processes:</b> <span id="special">--</span></div>
                            <div class="ord"><b>Sizes:</b> <span id="sizes">--</span></div>
                            <div class="ord"><b>status:</b> <span id="taskstatus">--</span></div>
                            <div class="ord"><b>detail_id:</b> <span id="detail_id">--</span></div>
                            <div class="ord"><b>Raw Material Days:</b> <span id="raw_days">--</span></div>
                        </div>
                        <div class="col-md-2">
                            <div class="ord"><b>FI_date:</b> <span id="FI_date">--</span></div>
                            <div class="ord"><b>Planned Qty (line):</b> <span id="plannedlineqty">--</span></div>
                            <div id="tailor_qty_display" class="ord d-none text-success"><b>Planned Opts:</b> <span id="planned_tailor_qty_display"></span></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="d-none card mt-4 ms-4 shadow-sm" style="width: 98.5%;">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="card-title fw-semibold text-primary mb-0">Resources Required</h6>
                        <div>
                            <button class="d-none btn btn-light p-1" title="Cut"><i class="bi bi-scissors"></i></button>
                            <button class="d-none btn btn-success p-1" title="Save"><i class="bi bi-save"></i></button>
                            <button class="btn btn-light"><i class="bi bi-chevron-left"></i></button>
                            <button class="btn btn-light"><i class="bi bi-chevron-right"></i></button>
                        </div>
                    </div>
                    <div class="table-responsive" style="max-height: 200px; overflow-x: auto;">
                        <table class="table table-bordered text-center align-middle mb-0" style="font-size: 12px;">
                            <thead class="table-light">
                                <tr>
                                    <th rowspan="2" class="bg-light sticky-left" style="min-width: 150px;">Metric</th>
                                    <th colspan="7">WEEK 24</th>
                                    <th colspan="7">WEEK 25</th>
                                    <th colspan="7">WEEK 26</th>
                                    <th colspan="7">WEEK 27</th>
                                    <th colspan="7">WEEK 28</th>
                                </tr>
                                <tr>
                                    <th>11</th><th>12</th><th>13</th><th>14</th><th>15</th><th>16</th><th>17</th>
                                    <th>18</th><th>19</th><th>20</th><th>21</th><th>22</th><th>23</th><th>24</th>
                                    <th>25</th><th>26</th><th>27</th><th>28</th><th>29</th><th>30</th><th>01</th>
                                    <th>02</th><th>03</th><th>04</th><th>05</th><th>06</th><th>07</th><th>08</th>
                                    <th>09</th><th>10</th><th>11</th><th>12</th><th>13</th><th>14</th><th>15</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="text-start bg-light sticky-left">Total Machines Used</td>
                                    <td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
                                    <td>0</td><td>0</td><td>0</td><td>0</td><td>12</td><td>12</td><td>0</td>
                                    <td>20</td><td>20</td><td>20</td><td>0</td><td>0</td><td>0</td><td>0</td>
                                    <td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
                                    <td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- <div class="modal fade d-none" id="taskModal" tabindex="-1" aria-labelledby="taskModalLabel" aria-hidden="true">
        <div class="modal-dialog d-none">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="taskModalLabel">Task Details</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="taskInfo"></div>
            </div>
        </div>
    </div> -->

    <div id="rawMaterialSidebar" class="sidebar1-overlay">
        <div class="sidebar1-content shadow">
            <!-- Search Section -->
            <div class="p-3 border-bottom">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-3 fw-bold">Search Details</h6>
                    <button class="btn-close" id="closeSidebarBtn" aria-label="Close"></button>
                </div>    
                <div class="d-flex gap-3 mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="buyerCheck" name="filter" value="Buyer" />
                        <label class="form-check-label" for="buyerCheck">Buyer</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="typeCheck" name="filter" value="Type" />
                        <label class="form-check-label" for="typeCheck">Item_Type</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="ocnCheck" name="filter" value="OCN" />
                        <label class="form-check-label" for="ocnCheck">OCN</label>
                    </div>
                </div>
                <input type="text" class="form-control" id="searchInput" placeholder="Search materials..." />
            </div>
            <!-- Display Section -->
            <div class="p-3" style="position: relative; max-height: 500px; overflow-y: auto;">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0 fw-bold" id="displayTitle">Details</h6>
                </div>
                <table style="width: 100%; border-collapse: collapse; font-size: 12px;">
                    <thead style="position: sticky; top: -17px; background-color: #fff; z-index: 10; border-bottom: 2px solid #000;">
                        <tr>
                            <th class="fw-bold">Buyer</th>
                            <th class="fw-bold">Line No</th>
                            <th class="fw-bold">Ocn_No</th>
                            <th class="fw-bold">Item_Type</th>
                            <th class="fw-bold">Color</th>
                            <th class="fw-bold">Plan_Qty</th>
                            <th class="fw-bold">Start Date</th>
                            <th class="fw-bold">End Date</th>
                        </tr>
                        
                    </thead>
                    <tbody id="taskRows" style="max-height: 550px;"></tbody>
                </table>
            </div>
        </div>
    </div>

    <div id="splitOrderSidebar" class="sidebar-overlay">
        <div class="sidebar-content shadow">
            <div class="d-flex justify-content-between align-items-center p-3 border-bottom">
                <h6 class="mb-0 fw-bold">Split Order: --</h6>
                <button class="btn-close" id="closeSplitSidebarBtn" aria-label="Close"></button>
            </div>
            <div class="p-3">
                <label>Number of Parts</label>
                <div class="input-group mb-3" style="max-width: 150px;">
                    <button class="btn btn-outline-secondary" type="button" id="decreasePartsBtn">−</button>
                    <input id="numPartsInput" type="text" class="form-control text-center" value="1" readonly>
                    <button class="btn btn-outline-secondary" type="button" id="increasePartsBtn">+</button>
                </div>
                <div id="lineSelectorsContainer"></div>
                <small class="text-muted d-block mt-2"></small>
                <div class="mt-4 d-flex justify-content-end">
                    <button class="btn btn-secondary me-2" id="cancelSplitBtn">Cancel</button>
                    <button class="btn btn-primary" id="confirmSplitBtn">Confirm Split & Schedule</button>
                </div>
            </div>
        </div>
    </div>

    <div id="floating-chatbot-card" class="card shadow" style="display: none;">
        <div class="card-header d-flex justify-content-between align-items-center py-2 px-3">
            <h6 class="fw-semibold mb-0" id="dynamic-ocn-headingord" style="color: #83cee0;">-- OCN - Details</h6>
            <button type="button" class="btn-close btn-close-sm" aria-label="Close" onclick="$('#floating-chatbot-card').hide();"></button>
        </div>
        <div class="card-body p-3" style="font-size: 13px; max-height: 250px; overflow-y: auto;">
            <div id="chatbot-content">
                Hi nanba! How can I help you today?
            </div>
        </div>
    </div>

    <button id="chatbot-toggle-btn" class="btn btn-primary rounded-circle" style="position: fixed; bottom: 30px; right: 30px; z-index: 2000; width: 48px; height: 48px; display: none;">
        <i class="bi bi-exclamation-circle"></i> 
    </button>



    <!-- Bootstrap Modal for Task Update -->
    <!-- <div class="modal fade" id="taskUpdateModal" tabindex="-1" aria-labelledby="taskUpdateModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="taskUpdateModalLabel">Update Task</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="taskStartDate" class="form-label">Start Date</label>
                        <input type="text" class="form-control" id="taskStartDate" placeholder="Select start date">
                    </div>
                    <div class="mb-3">
                        <label for="taskLineNo" class="form-label">Line Number</label>
                        <select class="form-select" id="taskLineNo">
                            
                        </select>
                    </div>
                </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="confirmTaskUpdate">Confirm</button>
                </div>
            </div>
        </div>
    </div> -->


    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></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/ui/1.13.2/jquery-ui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/smoothness/jquery-ui.css">

    <script>
        // --- GLOBAL VARIABLES ---
        let selectedUnitCode = '3';
        let selectedUnitName = 'AAG-I';
        let selectedBuyer;
        let selectedStyle;
        let backlogData = [];
        let microplandata = [];
        let tasks = [];
        let selectedOCN = null;
        let selectedLineNo = null;
        let selectedOrderData = null;
        let currentParts = 1;
        let alertedTasks = new Set();
        let outOfBoundsOCNs = new Set();
        let maxDateShiftDays;
        let selectedItemId = null;
        let selectedColorId = null;

        let cellWidth = 60,
            rowHeight = 40;
        let zoomLevel = 1;
        const lines = ['L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8'];
        let lineCapacities = {};
        const planningStartDate = new Date("2025-06-17");
        window.emp_id = "{{ $empl_no }}";

        // Helper function to check if task already exists
        function taskExists(ocn, line, colorid = null) {
            return tasks.some(task => {
                const sameOCN = task.ocn === ocn;
                const sameLine = task.line === line;
                const sameColor = colorid ? task.colorid === colorid : true;
                return sameOCN && sameLine && sameColor;
            });
        }

        // Helper function to add task with deduplication
        function addTaskSafely(newTask) {
            // Check if task already exists (considering OCN, line, and colorid)
            if (taskExists(newTask.ocn, newTask.line, newTask.colorid)) {
                console.warn(`Task ${newTask.ocn} on line ${newTask.line} with colorid ${newTask.colorid} already exists, skipping.`);
                return false;
            }
            
            // Add task with unique ID
            newTask.id = `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            tasks.push(newTask);
            console.log(`✅ Task added: ${newTask.ocn} on line ${newTask.line} with colorid ${newTask.colorid}`);
            return true;
        }

        // Helper function to clear tasks array
        function clearTasks() {
            tasks = [];
            console.log('🗑️ Tasks array cleared');
        }

        // Helper function to monitor task array changes
        function logTaskArrayChange(action, task = null) {
            console.log(`📊 Task Array Change - ${action}`);
            console.log(`Current tasks count: ${tasks.length}`);
            if (task) {
                console.log(`Task details:`, {
                    id: task.id,
                    ocn: task.ocn,
                    line: task.line,
                    start: task.start,
                    end: task.end
                });
            }
            console.log(`Full tasks array:`, tasks);
        }

        // Enhanced addTaskSafely with monitoring
        const originalAddTaskSafely = addTaskSafely;
        addTaskSafely = function(newTask) {
            const result = originalAddTaskSafely.call(this, newTask);
            if (result) {
                logTaskArrayChange('ADDED', newTask);
            } else {
                logTaskArrayChange('DUPLICATE_SKIPPED', newTask);
            }
            return result;
        };

        // Enhanced clearTasks with monitoring
        const originalClearTasks = clearTasks;
        clearTasks = function() {
            const previousCount = tasks.length;
            originalClearTasks.call(this);
            logTaskArrayChange(`CLEARED (was ${previousCount} tasks)`);
        };


        function initializeFlatpickr() {
            const today = new Date();
            const maxDate = new Date();
            maxDate.setFullYear(today.getFullYear() + 2);

            // Function to format date as DD-MM-YYYY
            const formatDate = (dateStr) => {
                const date = new Date(dateStr);
                return `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()}`;
            };

            let calculateDaysBetween = (startDateStr, endDateStr) => {
                let start = new Date(startDateStr);
                let end = new Date(endDateStr);
                let diffTime = end - start;
                return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // Convert milliseconds to days
            };

            // Function to update the production schedule period text
            const updateSchedulePeriod = () => {
                const startDate = $('#start-date').val() || today.toISOString().split('T')[0];
                const endDate = $('#end-date').val() || new Date(today.setDate(today.getDate() + 60)).toISOString().split('T')[0];
                let maxDateShiftDays = calculateDaysBetween(startDate, endDate);
                console.log(`Calculated maxDateShiftDays: ${maxDateShiftDays} days (from ${startDate} to ${endDate})`);
                $('.card-title').text(`Production Schedule For the period-(${formatDate(startDate)})-(${formatDate(endDate)})`);
                populatePOBacklog();
            };

            // Initialize flatpickr for start date (default to today)
            flatpickr("#start-date", {
                dateFormat: "Y-m-d",
                minDate: "today",
                maxDate: maxDate,
                defaultDate: today,
                onChange: updateSchedulePeriod
            });

            // Initialize flatpickr for end date (default to today + 60 days)
            const defaultEndDate = new Date(today);
            defaultEndDate.setDate(today.getDate() + 60);
            
            flatpickr("#end-date", {
                dateFormat: "Y-m-d",            
                altInput: true,
                altFormat: "d-m-y",             
                minDate: "today",
                maxDate: maxDate,
                defaultDate: defaultEndDate,
                onChange: function(selectedDates, dateStr, instance) {
                    if (confirm(`Are you sure you want to change the end date to ${formatDate(dateStr)}? \n\n save all changes before proceeding?`)) {
                        updateSchedulePeriod();
                    } else {
                        instance.setDate(defaultEndDate); // Revert to default if canceled
                    }
                }
            });

            // Initialize the text on page load
            updateSchedulePeriod();
        }

        // --- FLATPICKR INITIALIZATION ---
        // function initializeFlatpickr() {
        //     const today = new Date();
        //     const maxDate = new Date();
        //     maxDate.setFullYear(today.getFullYear() + 2);

        //     // Function to format date as DD-MM-YYYY
        //     const formatDate = (dateStr) => {
        //         const date = new Date(dateStr);
        //         return `${String(date.getDate()).padStart(2, '0')}-${String(date.getMonth() + 1).padStart(2, '0')}-${date.getFullYear()}`;
        //     };

        //     // Function to update the production schedule period text
        //     const updateSchedulePeriod = () => {
        //         const startDate = $('#start-date').val() || today.toISOString().split('T')[0];
        //         const endDate = $('#end-date').val() || new Date(today.setDate(today.getDate() + 60)).toISOString().split('T')[0];
                
        //         $('.card-title').text(`Production Schedule For the period-(${formatDate(startDate)})-(${formatDate(endDate)})`);
        //         populatePOBacklog();
        //     };

        //     // Initialize flatpickr for start date (default to today)
        //     flatpickr("#start-date", {
        //         dateFormat: "Y-m-d",
        //         minDate: "today",
        //         maxDate: maxDate,
        //         defaultDate: today,
        //         onChange: updateSchedulePeriod
        //     });

        //     // Initialize flatpickr for end date (default to today + 60 days)
        //     const defaultEndDate = new Date(today);
        //     defaultEndDate.setDate(today.getDate() + 60);
            
        //     flatpickr("#end-date", {
        //         dateFormat: "Y-m-d",            
        //         altInput: true,
        //         altFormat: "d-m-y",             
        //         minDate: "today",
        //         maxDate: maxDate,
        //         defaultDate: defaultEndDate,
        //         onChange: updateSchedulePeriod
        //     });

        //     // Initialize the text on page load
        //     updateSchedulePeriod();
            
        // }

        // --- DOCUMENT READY ---
        $(document).ready(function() {
            initializeGanttApp();
        });

        function setupEventListeners() {
            // Header Controls
            $('#factoryDropdown').next('.dropdown-menu').on('click', '.dropdown-item', handleFactoryChange);
            //$('#start-date, #end-date').on('change', populatePOBacklog);

            // Backlog Sidebar
            $('#sidebarToggle').on('click', handleSidebarToggle);
            $('#buyerFilterDropdown').next('.dropdown-menu').on('click', '.dropdown-item', handleBuyerChange);
            $('#backlog').on('click', '.backlog-item', handleBacklogItemClick);
            $('#styleFilterDropdown').next('.dropdown-menu').on('click', '.dropdown-item', handleStyleChange);
            $('#showOcnSearchBtn').on('click', function() {$('#ocnSearchInput').toggle().focus();});
            $('#ocnSearchInput').on('input', function() {renderBacklogItems();});

            // Make the Gantt area droppable to receive new tasks from the backlog
            $("#planning-area").droppable({
                accept: ".backlog-item",
                drop: handleBacklogDrop
            });

            // Order Details Card
            $('#showDetailsBtn').on('click', handleShowDetailsClick);
            $('#splitOrderBtn').on('click', openSplitSidebar);
            $('#resetDetailsBtn').on('click', resetOrderDetails);

            // Production Schedule Card
            $('#prevMonth').on('click', handlePrevMonthClick);
            $('#nextMonth').on('click', handleNextMonthClick);
            $('.btn.btn-success[title="Save"]').on('click', handleSaveClick);
            $('#deleteBtn').on('click', handleDeleteClick);
            
            // Raw Material Sidebar
            $('#closeSidebarBtn').on('click', handleCloseRawMaterialSidebar);
            
            // Split Order Sidebar
            $('#closeSplitSidebarBtn, #cancelSplitBtn').on('click', closeSplitSidebar);
            $('#decreasePartsBtn').on('click', decreaseParts);
            $('#increasePartsBtn').on('click', increaseParts);
            $('#confirmSplitBtn').on('click', handleSplitConfirm);
            
            // Gantt Interactions
            $(document).on('mousedown', '.task-bar', handleTaskbarMouseDown);
           // $(document).on('mousedown', '.handle', handleResizeHandleMouseDown);
            $(document).on('click', handleGanttAreaClick);

            $(document).on('click', '.task-bar', function(e) {
                // Get task details
                const $span = $(this).find('.task-bar-click .task-bar-prefix');
                const prefix = $span.length ? $span[0].outerHTML : '';
                const rest = $(this).find('.task-bar-click').html()?.replace(/<span class="task-bar-prefix">.*?<\/span>/, '') || '';
                
                // Ensure chatbot is visible and refresh content
                // Show both elements and refresh content in one smooth operation
                $('#floating-chatbot-card, #chatbot-toggle-btn').stop(true, true).fadeIn(100, function() {
                    refreshChatbotContent(true); // Force content refresh
                });
            });

            $('#chatbot-toggle-btn').on('click', function() {
                $('#floating-chatbot-card').toggle();
                if ($('#floating-chatbot-card').is(':visible')) {
                    refreshChatbotContent();
                }
            });

             // Checkbox radio-like behavior
             $('input[name="filter"]').on('change', function () {
            if (this.checked) {
                $('input[name="filter"]').not(this).prop('checked', false);
                $('#displayTitle').text('Details:'+$(this).val());
            } else {
                $('#displayTitle').text('Details');
            }
            });

            // Sidebar slide in/out
            $('#searchBtntask').on('click', function () {
            $('#rawMaterialSidebar').toggleClass('active');
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
            });

            $('#closeSidebarBtn').on('click', function () {
            $('#rawMaterialSidebar').removeClass('active');
            });

            $(document).ready(function() {
                // Checkbox change event
                $('#ocnCheck').on('change', function() {
                        if ($(this).is(':checked')) {
                            displayTasksInSidebar();
                        } else {
                            $('#taskRows').empty();
                        }
                    });
            });

            $(document).ready(function() {
                $('#typeCheck, #ocnCheck').on('change', function() {
                    filterTasks();
                });

                $('#searchInput').on('input', function() {
                    filterTasks();
                });
            });
        }

        const nationalHolidays = [
            "2025-01-01", // New Year's Day
            "2025-01-26", // Republic Day (India)
            "2025-08-15", // Independence Day (India)
            "2025-10-02", // Gandhi Jayanti
            "2025-12-25"  // Christmas
        ];

        function displayTasksInSidebar() {
            const $taskRows = $('#taskRows').empty();
            
            tasks.forEach(task => {
                const displayedOcn = task.ocn.includes('GIL/') || task.ocn.includes('GIL\\')
                    ? task.ocn.replace('GIL/', '').replace('GIL\\', '').replace(/^OCN/, '')
                    : task.ocn.replace(/^OCN/, '');

                const row = `
                    <div class="task-row" style="display: contents;">
                        <div>L${task.line_no}</div>
                        <div>${displayedOcn}</div>
                        <div>${task.color || ''}</div>
                        <div>${task.item || ''}</div>
                        <div>${task.start}</div>
                        <div>${task.end}</div>
                    </div>
                `;
                $taskRows.append(row);
            });
        }

                function formatDatee(dateStr) {
                    const date = new Date(dateStr);
                    if (isNaN(date.getTime())) return ''; // Invalid date check
                    const day = String(date.getDate()).padStart(2, '0');
                    const month = String(date.getMonth() + 1).padStart(2, '0');
                    const year = String(date.getFullYear()).slice(-2);
                    return `${day}-${month}-${year}`;
                }


                    

                function filterTasks() {
                    const $taskRows = $('#taskRows').empty();
                    const searchTerm = $('#searchInput').val().trim().toLowerCase();
                    const isBuyerChecked = $('#buyerCheck').is(':checked');
                    const isOcnChecked = $('#ocnCheck').is(':checked');
                    const isTypeChecked = $('#typeCheck').is(':checked');
                    
                    let totalQty = 0;
                    let minStartDate = null;
                    let maxEndDate = null;

                    tasks.forEach(task => {
                        const displayedOcn = task.ocn.includes('GIL/') || task.ocn.includes('GIL\\')
                            ? task.ocn.replace('GIL/', '').replace('GIL\\', '').replace(/^OCN/, '')
                            : task.ocn.replace(/^OCN/, '');

                        let matches = true;
                        if (isOcnChecked && searchTerm) {
                            if (!/^\d+$/.test(searchTerm)) return;
                            matches = displayedOcn.includes(searchTerm);
                        } else if (isTypeChecked && searchTerm) {
                            matches = (task.item || '').toLowerCase().includes(searchTerm);
                        }
                        else if (isBuyerChecked && searchTerm) {
                            matches = (task.buyer || '').toLowerCase().includes(searchTerm);
                        }

                        if (matches) {
                            const row = `
                                <tr class="task-row">
                                    <td>${task.buyer || ''}</td>
                                    <td>${task.line_no}</td>
                                    <td>${displayedOcn}</td>
                                    <td>${task.item || ''}</td>
                                    <td>${task.color || ''}</td>
                                    <td>${task.planned_qty || 0}</td>
                                    <td>${formatDatee(task.start)}</td>
                                    <td>${formatDatee(task.end)}</td>
                                </tr>
                            `;
                            $taskRows.append(row);
                            totalQty += Number(task.planned_qty) || 0;
                            const startDate = new Date(task.start);
                            const endDate = new Date(task.end);
                            if (!minStartDate || startDate < minStartDate) minStartDate = startDate;
                            if (!maxEndDate || endDate > maxEndDate) maxEndDate = endDate;
                        }
                    });

                    const footer = `
                        <tr class="footer-row" style="position: sticky; bottom: -20px; background-color: #fff; z-index: 10; font-weight: bold; border-top: 2px solid #000;">
                            <td style="border-top: 2px solid #000;">Total</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${totalQty}</td>
                            <td>${minStartDate ? formatDatee(minStartDate) : ''}</td>
                            <td>${maxEndDate ? formatDatee(maxEndDate) : ''}</td>
                        </tr>
                    `;
                    $taskRows.append(footer);
                }

        function refreshChatbotContent() {
            let $details = $('#order-details-dynamic');
            let ocnHeading = $details.find('#dynamic-ocn-heading').text() || '-- OCN - Details';
            $('#dynamic-ocn-headingord').text(ocnHeading);

            // Return early if no details available
            if ($details.hasClass('d-none')) {
                $('#chatbot-content').html('Hi! How can I help you today?');
                return;
            }

            // Populate line dropdown
            const lineOptions = lines.map((line, index) => `<option value="${index}">${line}</option>`).join('');

            // Build responsive 4-column layout with date picker and line selector
            let html = `
            <div class="row" style="font-size:12px">
                <!-- Column 1: Labels -->
                <div class="col-3">
                    <div><b>Buyer:</b></div>
                    <div><b>Item:</b></div>
                    <div><b>Color:</b></div>
                    <div><b>CK Date:</b></div>
                    <div><b>Bom_qty:</b></div>
                    <div><b>Production Qty:</b></div>
                    <div><b>FI Date:</b></div>
                    <div><b>Ship Date:</b></div>
                    <div><b>Order Qty:</b></div>
                </div>
                
                <!-- Column 2: Values -->
                <div class="col-3">
                    <div title="${$details.find('#buyer').attr('title') || ''}">${$details.find('#buyer').text()}</div>
                    <div>${$details.find('#item_name').text()}</div>
                    <div title="${$details.find('#color').attr('title') || ''}">${$details.find('#color').text()}</div>
                    <div>${$details.find('#ck_date').text()}</div>
                    <div>${$details.find('#bom_qty').text()}</div>
                    <div>${$details.find('#prod_order_qty').text()}</div>
                    <div>${$details.find('#FI_date').text()}</div>
                    <div>${$details.find('#shipping_date').text()}</div>
                    <div>${$details.find('#planned_qty').text()}</div>
                </div>
                
                <!-- Column 3: Labels -->
                <div class="col-3">
                    <div><b>Bal to Sew:</b></div>
                    <div><b>Bal (min):</b></div>
                    <div><b>Planned Qty (line):</b></div>
                    <div><b>SAM:</b></div>
                    <div><b>Mch/opr:</b></div>
                    <div><b>Special:</b></div>
                    <div><b>Per Day Qty:</b></div>
                    <div><b>Planned Opts:</b></div>
                </div>
                
                <!-- Column 4: Values -->
                <div class="col-3">
                    <div>${$details.find('#balance_to_sew').text()}</div>
                    <div>${$details.find('#balance_minutes').text()}</div>
                    <div>${$details.find('#plannedlineqty').text()}</div>
                    <div>${$details.find('#sam').text()}</div>
                    <div>${$details.find('#machines').text()}</div>
                    <div>${$details.find('#special').text()}</div>
                    <div>${$details.find('#per_day_qty').text()}</div>
                    <div>${$details.find('#tailor_qty_display').hasClass('d-none') ? $details.find('#planner_opr').text() : $details.find('#planned_tailor_qty_display').text()}</div>
                </div>
            </div>
            
            <!-- Tailor Input Section -->
            <div class="mt-2 d-flex align-items-center gap-2">
                <input id="chatbot_tailor_input" type="text" 
                       placeholder="Enter tailor no" 
                       class="form-control form-control-sm" 
                       style="width: 100px; font-size: 12px;">
                <div class="form-check form-check-inline d-none">
                    <input class="form-check-input" type="radio" name="tailorFilter" id="ocnRadio" value="ocn">
                    <label class="form-check-label" for="ocnRadio" style="font-size: 12px;">OCN</label>
                </div>
                <div class="form-check form-check-inline d-none">
                    <input class="form-check-input" type="radio" name="tailorFilter" id="itemRadio" value="item">
                    <label class="form-check-label" for="itemRadio" style="font-size: 12px;">Item</label>
                </div>
                <button id="chatbot_submit_tailor_Btn" 
                        class="btn btn-sm btn-success ms-2"
                        style="padding: 0.15rem 0.5rem; font-size: 12px;">
                    <i class="bi bi-check"></i> Save
                </button>
            </div>
            
            
             <!-- Task Update Section -->
            <p class="d-none" id="toggle_task_update" style="cursor: pointer; font-size: 12px; margin-bottom: 0; color:#1E90FF; margin-top: 10px;">Update Task Status</p>
            <div id="task_update_section" class="mt-2 d-flex gap-2 align-items-end d-none">
                <!-- Start Date -->
                <div class="flex-fill">
                    <label for="chatbot_taskStartDate" class="form-label" style="font-size: 12px;">Start Date</label>
                    <input id="chatbot_taskStartDate" type="text" 
                        class="form-control form-control-sm" 
                        placeholder="Select start date" 
                        style="font-size: 12px;">
                </div>

                <!-- Line Number -->
                <div class="flex-fill">
                    <label for="chatbot_taskLineNo" class="form-label" style="font-size: 12px;">Line Number</label>
                    <select id="chatbot_taskLineNo" class="form-select form-select-sm" style="font-size: 12px;">
                        ${lineOptions}
                    </select>
                </div>

                <!-- Button aligned with bottom -->
                <div class="pb-0">
                    <button id="chatbot_update_task_Btn" 
                            class="btn btn-sm btn-primary"
                            style="padding: 0.25rem 0.6rem; font-size: 12px;">
                        <i class="bi bi-check"></i> Update Task
                    </button>
                </div>
            </div>`;

            $('#chatbot-content').html(html);

            // Initialize Flatpickr for start date
            flatpickr("#chatbot_taskStartDate", {
                dateFormat: "Y-m-d",
                minDate: new Date().toISOString().split('T')[0], // Prevent selecting dates before today
                defaultDate: new Date().toISOString().split('T')[0], // Default to today
                disable: [
                    function(date) {
                        // Disable Sundays and national holidays
                        return date.getDay() === 0 || nationalHolidays.includes(date.toISOString().split('T')[0]);
                    }
                ]
            });

            // Set default values for start date and line number
            let task = tasks.find(t => t.ocn === $details.find('#dynamic-ocn-heading').text().split(' - ')[0].trim() && 
                                    t.itemid === $details.find('#item_id').text().trim() && 
                                    t.colorid === $details.find('#color_id').text().trim());
            if (task) {
                $('#chatbot_taskStartDate').val(task.start);
                $('#chatbot_taskLineNo').val(task.line);
            }

            // Toggle Task Update Section visibility
            $('#toggle_task_update').on('click', function() {
                $('#task_update_section').toggleClass('d-none');
            });

            // Input validation for tailor input
            $('#chatbot_tailor_input').on('keypress', function(e) {
                const char = String.fromCharCode(e.which);
                if (!/[0-9.]/.test(char) || (char === '.' && $(this).val().includes('.'))) {
                    e.preventDefault();
                }
            });

            // Submit handler for tailor input
            let isSubmitting = false;
            $('#chatbot_submit_tailor_Btn').on('click', function() {
                if (isSubmitting) return;
                
                const planned_tailor_qty = $('#chatbot_tailor_input').val().trim();
                let detail_id = $details.find('#taskstatus').text().trim() ? $details.find('#detail_id').text().trim() : 0;

                if (!planned_tailor_qty || isNaN(planned_tailor_qty)) {
                    alert('Please enter a valid number');
                    return;
                }

                isSubmitting = true;
                const data = {
                    ocn_no: $details.find('#dynamic-ocn-heading').text().split(' - ')[0].trim(),
                    itemid: $details.find('#item_id').text().trim(),
                    colorid: $details.find('#color_id').text().trim(),
                    lineno: $details.find('#dynamic-ocn-heading').text().split('in ')[1]?.split('-')[0]?.trim() || '',
                    unit_code: selectedUnitCode,
                    planned_tailor_qty: parseFloat(planned_tailor_qty),
                    per_day_qty: $details.find('#per_day_qty').text().trim(),
                    og_per_day_qty: $details.find('#Per_Day_Qty').text().trim(),
                    no_operators: $details.find('#no_operators').text().trim(),
                    detail_id: detail_id,
                    taskisdragg : '2',
                    type: $('input[name="tailorFilter"]:checked').val() || 'ocn',
                };

                updateSingleTask(data.ocn_no, data.itemid, data.colorid, data.lineno, parseFloat(planned_tailor_qty), globalLineDates, data.og_per_day_qty, data.no_operators);
                $details.find('#planned_tailor_qty_display').text(planned_tailor_qty);
                $details.find('#tailor_qty_display').removeClass('d-none');
                
                console.log('Submitting planned tailor quantity:', data);
                refreshChatbotContent();
                // $.ajax({
                //     url: "{{ route('updateTailorQuantity') }}",
                //     method: 'POST',
                //     headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                //     data: data,
                //     success: function(response) {
                //         if (response.status === "success") {
                //             // Show success and refresh
                //             $('#chatbot-content').prepend(
                //                 '<div class="alert alert-success alert-dismissible fade show mt-2 py-1">' +
                //                 'Saved! <button type="button" class="btn-close p-1" data-bs-dismiss="alert"></button></div>'
                //             );
                //         } else {
                //             console.log('Error: ' + (response.message || 'Operation failed'));
                //         }
                //         refreshChatbotContent();
                //     },
                //     error: function() {
                //         alert('Network error - please try again');
                //     },
                //     complete: function() {
                //         isSubmitting = false;
                //     }
                // });
            });

            // Submit handler for task update (start date and line number)
            $('#chatbot_update_task_Btn').on('click', function() {
                const newStartDate = $('#chatbot_taskStartDate').val();
                const newLineIndex = $('#chatbot_taskLineNo').val();

                if (!newStartDate || newLineIndex === undefined) {
                    alert("Please provide both a start date and a line number.");
                    return;
                }

                const rawOcn = $details.find('#dynamic-ocn-heading').text().split(' - ')[0].trim();
                const ocn = rawOcn.replace(/^OCN/i, '').replace(/^GIL[\\\/]/i, '').trim().toLowerCase(); // Normalize OCN
                const itemid = String($details.find('#item_id').text().trim()); // Ensure string
                const colorid = String($details.find('#color_id').text().trim()); // Ensure string

                // Log input values for debugging
                console.log('Task lookup inputs:', { rawOcn, ocn, itemid, colorid });

                // Normalize OCN in tasks array for comparison
                const task = tasks.find(t => {
                    const taskOcn = String(t.ocn).replace(/^OCN/i, '').replace(/^GIL[\\\/]/i, '').trim().toLowerCase();
                    const taskItemId = String(t.itemid).trim();
                    const taskColorId = String(t.colorid).trim();
                    return taskOcn === ocn && taskItemId === itemid && taskColorId === colorid;
                }) || (activeTaskId ? tasks.find(t => t.id === activeTaskId) : null); // Fallback to activeTaskId

                if (!task) {
                    console.error("Task not found for OCN:", ocn, "Item ID:", itemid, "Color ID:", colorid, "Raw OCN:", rawOcn, "Active Task ID:", activeTaskId);
                    console.log("Tasks array:", tasks.map(t => ({
                        ocn: String(t.ocn).replace(/^OCN/i, '').replace(/^GIL[\\\/]/i, '').trim().toLowerCase(),
                        itemid: String(t.itemid).trim(),
                        colorid: String(t.colorid).trim(),
                        id: t.id
                    })));
                    alert(`Error: Task not found for OCN: ${rawOcn}, Item ID: ${itemid}, Color ID: ${colorid}. Please ensure the task exists and try again.`);
                    return;
                }

                // Log found task for verification
                console.log('Found task:', task);

                // Calculate duration to preserve task length
                const oldStart = new Date(task.start);
                const oldEnd = new Date(task.end);
                const durationMs = oldEnd - oldStart;
                const newStart = new Date(newStartDate);
                const newEnd = new Date(newStart.getTime() + durationMs);

                // Update task properties
                task.start = newStartDate;
                task.end = newEnd.toISOString().split('T')[0];
                task.line = parseInt(newLineIndex);

                // Check for conflicts after updating
                const conflictingTasks = tasks.filter(otherTask => {
                    if (otherTask.id === task.id) return false;
                    if (otherTask.line !== task.line) return false;
                    const otherStart = new Date(otherTask.start);
                    const otherEnd = new Date(otherTask.end);
                    const taskStart = new Date(task.start);
                    const taskEnd = new Date(task.end);
                    return (taskStart <= otherEnd && taskEnd >= otherStart);
                });
                task.hasConflict = conflictingTasks.length > 0;

                // Re-render tasks
                renderTasks();

                // Show success message
                $('#chatbot-content').prepend(
                    '<div class="alert alert-success alert-dismissible fade show mt-2 py-1">' +
                    'Task updated! <button type="button" class="btn-close p-1" data-bs-dismiss="alert"></button></div>'
                );
            });
        }

        // --- EVENT HANDLERS ---
        function handleFactoryChange(e) {
            e.preventDefault();
            selectedUnitCode = $(this).data('unit-code');
            selectedUnitName = $(this).text();
            $('#factoryDropdown').html(`<i class="bi bi-building-gear"></i> ${selectedUnitName}`);
            selectedBuyer = null;
            populatePOBacklog();
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function handleBuyerChange(e) {
            e.preventDefault();
            selectedBuyer = $(this).data('buyer') || null;
            $('#buyerFilterDropdown').html(`<i class="bi bi-person"></i> ${selectedBuyer || 'All'}`);
            renderBacklogItems();
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function handleStyleChange(e) {
            e.preventDefault();
            selectedStyle = $(this).data('style') || null;
            $('#styleFilterDropdown').html(`<i class="bi bi-filter"></i> ${selectedStyle || 'All'}`);
            renderBacklogItems();
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function handleSidebarToggle() {
            $('.sidebar').toggleClass('open');
            $('.content').toggleClass('shrink');
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        let activeSpinners = 0;

function handleBacklogItemClick() {
    const ocn = $(this).data('ocn');
    console.log('Selected OCN:', ocn);

    const $clickedElement = $(this);
    // Show spinner and disable pointer events for all backlog items
    const spinner = $(`#spinner-${ocn}`);
    if (spinner.length) {
        spinner.removeClass('d-none');
        activeSpinners++;
        $('.backlog-item').css({
            'pointer-events': 'none',
            'cursor': 'wait'
        });
        console.log(`Disabled pointer events for all backlog items: Spinner activated for OCN ${ocn}, active spinners: ${activeSpinners}`);
    }

    $.ajax({
        url: '/ocnlineplan',
        method: 'GET',
        data: { ocn_no: ocn },
        success: function(response) {
            if (response && response.data && response.data.length > 0) {
                console.log('API Response for OCN:', ocn, response.data);
                const lastGanttDate = globalLineDates.length > 0 
                    ? new Date(globalLineDates[globalLineDates.length - 1].Edate) 
                    : new Date(document.getElementById('end-date').value || '2025-12-31');
                if (isNaN(lastGanttDate.getTime())) {
                    console.error('Invalid lastGanttDate, using fallback date: 2025-12-31');
                    lastGanttDate = new Date('2025-12-31');
                }
                let hasOutOfBoundsTask = false;
                let validTasksAdded = false;
                response.data.forEach((itemDetails, index) => {
                    const prodStartDate = itemDetails.Prod_Start_Date || itemDetails.ProdStartDate;
                    if (!prodStartDate || typeof prodStartDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(prodStartDate)) {
                        console.warn(`Invalid or missing Prod_Start_Date for OCN ${ocn}, color variant ${index + 1}:`, prodStartDate);
                        return;
                    }
                    const gridStartDate = new Date(prodStartDate);
                    if (isNaN(gridStartDate.getTime())) {
                        console.warn(`Invalid date format for Prod_Start_Date: ${prodStartDate} for OCN ${ocn}, color variant ${index + 1}`);
                        return;
                    }
                    const itemid = itemDetails.Itemid || 0;
                    const colorid = itemDetails.Colorid || 0;
                    const factoryexit = itemDetails.Ex_Fact_Dt || '';
                    const orderqty = parseFloat(itemDetails.Bal_To_Sew || 0);
                    const planqty = parseFloat(itemDetails.Day_Cap_Per_Line || 2000);
                    const daysRequired = Math.ceil(orderqty / planqty);
                    const newEndDate = new Date(gridStartDate);
                    let workingDays = 1;

                    while (workingDays < daysRequired) {
                        newEndDate.setDate(newEndDate.getDate() + 1);
                        if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
                            workingDays++;
                        }
                    }
                    newEndDate.setDate(newEndDate.getDate());

                    console.log(`Task Dates for OCN ${ocn}, Color ${itemDetails.Color || 'N/A'}:`, {
                        Prod_Start_Date: prodStartDate,
                        Start_Date: gridStartDate.toISOString().split('T')[0],
                        End_Date: newEndDate.toISOString().split('T')[0],
                        Last_Gantt_Date: lastGanttDate.toISOString().split('T')[0],
                        Days_Required: daysRequired
                    });

                    if (newEndDate > lastGanttDate) {
                        const daysPast = Math.ceil((newEndDate - lastGanttDate) / (1000 * 60 * 60 * 24));
                        const taskId = `temp_task_${ocn}_${colorid}_${Date.now()}`;
                        if (!alertedTasks.has(taskId)) {
                            alert(`Please check the end date for task ${ocn} (${itemDetails.Color || 'N/A'}). It is ${daysPast} day(s) past the available days in the Gantt chart (end date: ${newEndDate.toISOString().split('T')[0]}).`);
                            alertedTasks.add(taskId);
                        }
                        outOfBoundsOCNs.add(ocn);
                        hasOutOfBoundsTask = true;
                        console.warn(`Skipping task for OCN ${ocn}, color ${itemDetails.Color || 'N/A'} due to out-of-bounds end date: ${newEndDate.toISOString().split('T')[0]}`);
                        return;
                    }

                    const newTask = {
                        ocn: ocn,
                        itemid: itemid,
                        colorid: colorid,
                        factoryexit: factoryexit,
                        orderqty: orderqty,
                        planqty: planqty,
                        start: gridStartDate.toISOString().split('T')[0],
                        end: newEndDate.toISOString().split('T')[0],
                        line: 0,
                        duration: daysRequired,
                        units: itemDetails.Bal_To_Sew,
                        color: itemDetails.Color || 'Unknown',
                        item: itemDetails.Item || 'Unknown',
                        bal_to_sew: itemDetails.Bal_To_Sew || orderqty,
                        day_cap_per_line: itemDetails.Day_Cap_Per_Line,
                        per_day_qty: itemDetails.Day_Cap_Per_Line,
                        mch_cap: itemDetails.No_Of_Mch || 0,
                        no_operators: itemDetails.No_Of_Operator || 0,
                        ck_date: itemDetails.Ck_DAte || '',
                        FI_date: itemDetails.FI_Date || '',
                        ship_date: itemDetails.FI_Date || '',
                        buyer: itemDetails.Buyer || 'Unknown',
                        planner_opr: 0,
                        planner_qty: 0,
                        Isdragg: 0 ,
                        taskstatus: 'not saved'
                    };

                    const result = addTaskWithSmartLineAssignment(newTask);
                    if (result.taskAdded) {
                        validTasksAdded = true;
                        console.log(`✅ Color variant ${index + 1} added successfully to line ${lines[result.assignedLine]}`);
                    } else {
                        console.warn(`⚠️ Color variant ${index + 1} was not added: ${result.hasConflict ? 'Conflicts detected' : 'Invalid data or duplication'}`);
                    }
                });

                if (!hasOutOfBoundsTask && validTasksAdded) {
                    $clickedElement.remove();
                    backlogData = backlogData.filter(item => item.Ocn.split('\\').pop().replace(/^OCN/, '') !== ocn);
                    outOfBoundsOCNs.delete(ocn);
                } else if (hasOutOfBoundsTask) {
                    $clickedElement.addClass('out-of-bounds');
                }
                renderTasks(globalLineDates);
                console.log(`Processed ${response.data.length} color variants for OCN ${ocn}`);
            } else {
                console.warn('No item data found for OCN:', ocn);
            }
        },
        error: function(xhr, status, error) {
            console.error('Failed to fetch item details:', status, error);
        },
        complete: function() {
            // Hide spinner and re-enable pointer events if no spinners are active
            if (spinner.length) {
                spinner.addClass('d-none');
                activeSpinners = Math.max(0, activeSpinners - 1);
                if (activeSpinners === 0) {
                    $('.backlog-item').css({
                        'pointer-events': 'auto',
                        'cursor': 'grab'
                    });
                    console.log(`Re-enabled pointer events for all backlog items: All spinners deactivated`);
                } else {
                    console.log(`Spinner deactivated for OCN ${ocn}, but pointer events remain disabled: ${activeSpinners} spinners still active`);
                }
            }
        }
    });
}

        function handleDeleteClick() {
            if (!selectedOCN || !selectedItemId || !selectedColorId || !selectedLineNo) {
                console.warn("No task selected for deletion.", {
                    OCN: selectedOCN,
                    ItemID: selectedItemId,
                    ColorID: selectedColorId,
                    LineNo: selectedLineNo
                });
                alert("Please select a task to delete.");
                return;
            }

            // Normalize OCN
            const ocnNumber = getOcnNumber(selectedOCN);
            if (!ocnNumber) {
                console.error("Failed to extract ocn_no from:", selectedOCN);
                alert("Invalid OCN format.");
                return;
            }

            // Parse line_no (e.g., 'L31' → 31)
            const parsedLineNo = parseInt(selectedLineNo.replace('L', '')) || parseInt(selectedLineNo);
            if (isNaN(parsedLineNo)) {
                console.error("Invalid Line No:", selectedLineNo);
                alert("Invalid Line No selected.");
                return;
            }

            // Show confirmation alert
            const confirmMessage = `Are you sure you want to delete the following task?\n\n` +
                                `OCN: ${ocnNumber}\n` +
                                ///`Line: L${parsedLineNo}\n` +
                                //`Color ID: ${selectedColorId}\n` +
                                //`Item ID: ${selectedItemId}\n\n` +
                                `This action will remove the tasks with OCN: ${ocnNumber} from the Gantt chart and return it to the PO backlog.`;
            if (!confirm(confirmMessage)) {
                console.log("Deletion cancelled by user for OCN:", ocnNumber);
                return;
            }

            console.log("🔍 Deleting task for OCN:", ocnNumber, "Item ID:", selectedItemId, "Color ID:", selectedColorId, "Line No:", parsedLineNo);

            // Find task
            const taskToDelete = tasks.find(task => {
                const taskOcnNumber = getOcnNumber(task.ocn);
                const taskLineNo = task.line_no || parseInt(lines[task.line]?.replace('L', '')) || task.line;
                return taskOcnNumber === ocnNumber &&
                    task.itemid == selectedItemId &&
                    task.colorid == selectedColorId &&
                    taskLineNo == parsedLineNo;
            }) || (activeTaskId ? tasks.find(task => task.id === activeTaskId) : null);

            if (!taskToDelete) {
                console.error("No task found for deletion. Search parameters:", {
                    OCN: ocnNumber,
                    ItemID: selectedItemId,
                    ColorID: selectedColorId,
                    LineNo: parsedLineNo,
                    ActiveTaskId: activeTaskId,
                    Tasks: tasks.map(t => ({
                        id: t.id,
                        ocn: t.ocn,
                        itemid: t.itemid,
                        colorid: t.colorid,
                        line_no: t.line_no,
                        line: lines[t.line]
                    }))
                });
                alert("No task found to delete with the specified OCN, Item ID, Color ID, and Line No.");
                return;
            }

            console.log("🔍 Task to delete:", {
                id: taskToDelete.id,
                ocn: taskToDelete.ocn,
                itemid: taskToDelete.itemid,
                colorid: taskToDelete.colorid,
                line_no: taskToDelete.line_no,
                line: lines[taskToDelete.line]
            });

            // Disable delete button to prevent multiple clicks
            //$('#deleteBtn').prop('disabled', true).text('Deleting...');

            // Prepare data for deletion
            const deleteData = {
                ocn_no: ocnNumber,
                item_id: selectedItemId,
                color_id: selectedColorId,
                line_no: parsedLineNo,
                unit_id: selectedUnitCode || '3'
            };

            $.ajax({
                url: '/deleteMicroPlan',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(deleteData),
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                timeout: 10000,
                success: function(response) {
                    console.log('Successfully deleted from database:', response, {
                        OCN: ocnNumber,
                        ItemID: taskToDelete.itemid,
                        ColorID: taskToDelete.colorid,
                        LineNo: parsedLineNo,
                        Task: taskToDelete
                    });

                    // Remove task from tasks array
                    tasks = tasks.filter(task => task.ocn !== taskToDelete.ocn);
                    //logTaskArrayChange(`DELETED task for OCN ${ocnNumber}, Item ID ${taskToDelete.itemid}, Color ID ${taskToDelete.colorid}, Line No ${parsedLineNo}`);

                    // Remove task bar from DOM
                    const tooltipPattern = `OCN: ${ocnNumber}`;
                    const $taskBar = $('.task-bar').filter(function() {
                        return $(this).data('tooltip')?.includes(tooltipPattern);
                    });
                    if ($taskBar.length) {
                        $taskBar.remove();
                        console.log(`Removed task bar for OCN: ${ocnNumber}`);
                    } else {
                        console.warn(`No task bar found in DOM for OCN: ${ocnNumber}, Tooltip Pattern: ${tooltipPattern}`);
                    }

                    // Restore to backlog
                    const fallbackOrderData = selectedOrderData || taskToDelete;
                    const backlogItem = {
                        Ocn: `GIL\\OCN${ocnNumber}`,
                        Buyer: fallbackOrderData.buyer || taskToDelete.buyer || 'Unknown',
                        Order_Qty: taskToDelete.units || fallbackOrderData.Bal_To_Sew || 0,
                        Itemid: taskToDelete.itemid,
                        Colorid: taskToDelete.colorid,
                        Plan_Qty: taskToDelete.units || fallbackOrderData.Bal_To_Sew || 2000,
                        Ex_Fact_Dt: taskToDelete.factoryexit || fallbackOrderData.factoryexit || '',
                        Item: taskToDelete.item,
                        Color: taskToDelete.color,
                        Line_No: parsedLineNo
                    };

                    let itemExists = backlogData.some(item => getOcnNumber(item.Ocn) === ocnNumber);
                    if (!itemExists) {
                        // Find the correct insertion index to maintain sorted order
                        const insertIndex = backlogData.findIndex(item => {
                            const existingOcnNumber = getOcnNumber(item.Ocn);
                            return parseInt(existingOcnNumber) > parseInt(ocnNumber);
                        });
                        if (insertIndex === -1) {
                            // If no larger OCN found, append to end
                            backlogData.push(backlogItem);
                        } else {
                            // Insert at the correct position
                            backlogData.splice(insertIndex, 0, backlogItem);
                        }
                        console.log("🔍 Restored to backlog at index", insertIndex === -1 ? backlogData.length - 1 : insertIndex, ":", backlogItem);
                        console.log("Updated backlogData:", backlogData);
                    } else {
                        console.warn("Task already exists in backlog, skipping addition:", backlogItem);
                    }

                    // Clear out-of-bounds status
                    outOfBoundsOCNs.delete(ocnNumber);

                    // Reset selection
                    //resetOrderDetails();
                    selectedOCN = null;
                    selectedItemId = null;
                    selectedColorId = null;
                    selectedLineNo = null;
                    selectedOrderData = null;
                    activeTaskId = null;

                    // Re-render backlog and tasks
                    renderBacklogItems();
                    renderTasks(globalLineDates);

                    // Update microplandata
                    microplandata = microplandata.filter(item => 
                        !(getOcnNumber(item.ocn_no) === ocnNumber && 
                        item.item_id == selectedItemId && 
                        item.color_id == selectedColorId && 
                        item.line_no == parsedLineNo)
                    );
                    console.log("🔍 Updated microplandata:", microplandata);

                    alert("Task deleted successfully and restored to backlog.");
                },
                error: function(xhr, status, error) {
                    console.error("Failed to delete task from database:", status, error, xhr.responseText, {
                        OCN: ocnNumber,
                        DeleteData: deleteData
                    });
                    alert("Failed to delete task from database. Please try again.");
                },
                complete: function() {
                    //$('#deleteBtn').prop('disabled', true).text('Delete');
                }
            });
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function getOcnNumber(ocn) {
            if (!ocn || typeof ocn !== 'string') {
                console.error("Invalid OCN:", ocn);
                return null;
            }
            // Remove 'GIL\' or 'GIL/' and 'OCN' prefix
            return ocn.replace('GIL\\', '').replace('GIL/', '').replace(/^OCN/, '');
        }
        
        function handleBacklogDrop(event, ui) {
            const ocn = ui.draggable.data('ocn');
            const $draggedElement = ui.draggable;
            const itemid = ui.draggable.data('item-id');
            const colorid = ui.draggable.data('color-id');
            const factoryexit = ui.draggable.data('factory-exit');
            const orderqty = parseFloat(ui.draggable.data('order-qty'));
            const planqty = parseFloat(ui.draggable.data('plan-qty'));
            const days = Math.ceil(orderqty / planqty);
            
            const elementUnder = document.elementFromPoint(event.clientX, event.clientY);
            const $row = $(elementUnder).closest('tr[data-line]');
            const $cell = $(elementUnder).closest('td[data-day]');

            if (!$row.length || !$cell.length) {
                console.warn('Dropped on invalid area - no row or cell found');
                return;
            }

            const lineNo = $row.data('line-no'); // Get the actual line (e.g., 'L1')
            const newLineIndex = lines.indexOf(lineNo);
            const dayIndex = $cell.data('day');
            
            if (newLineIndex === -1) {
                console.error('Invalid line index for:', lineNo);
                return;
            }
            $('.sidebar').addClass('blurred');
            // Get all color variants for this OCN
            $.ajax({
                url: '/ocnlineplan',
                method: 'GET',
                data: { ocn_no: ocn },
                success: function(response) {
                    if (response && response.data && response.data.length > 0) {
                        console.log('Drop API Response for OCN:', ocn, response.data);
                        
                        const gridStartDate = new Date($('#start-date').val());
                        const newStartDate = new Date(gridStartDate);
                        newStartDate.setDate(gridStartDate.getDate() + dayIndex);
                        
                        // Fallback to end-date input if globalLineDates is empty
                        const lastGanttDate = globalLineDates.length > 0 
                            ? new Date(globalLineDates[globalLineDates.length - 1].Edate) 
                            : new Date(document.getElementById('end-date').value || '2025-12-31');
                        if (isNaN(lastGanttDate.getTime())) {
                            console.error('Invalid lastGanttDate, using fallback date: 2025-12-31');
                            lastGanttDate = new Date('2025-12-31');
                        }
                        
                        let hasOutOfBoundsTask = false;
                        let validTasksAdded = false;

                        // Process all color variants
                        response.data.forEach((itemDetails, index) => {
                            console.log(`Processing drop color variant ${index + 1}:`, itemDetails);
                            
                            const itemid = itemDetails.Itemid || 0;
                            const colorid = itemDetails.Colorid || 0;
                            const factoryexit = itemDetails.Ex_Fact_Dt || '';
                            const orderqty = parseFloat(itemDetails.Bal_To_Sew || 0);
                            const planqty = parseFloat(itemDetails.Day_Cap_Per_Line || 2000);
                            const daysRequired = Math.ceil(orderqty / planqty);
                            
                            const newEndDate = new Date(newStartDate);
                            //newEndDate.setDate(newEndDate.getDate() + daysRequired  );

                            let workingDays = 1;
    
    while (workingDays < daysRequired) {
        newEndDate.setDate(newEndDate.getDate() + 1);
        if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
            workingDays++;
        }
    }

                            
                            newEndDate.setDate(newEndDate.getDate() );


                            // Check if end date exceeds last available date
                            if (newEndDate > lastGanttDate) {
                                const daysPast = Math.ceil((newEndDate - lastGanttDate) / (1000 * 60 * 60 * 24));
                                const taskId = `temp_task_${ocn}_${colorid}_${Date.now()}`;
                                if (!alertedTasks.has(taskId)) {
                                    alert(`Please check the end date for task ${ocn} (${itemDetails.Color || 'N/A'}). It is ${daysPast} day(s) past the available days in the Gantt chart (end date: ${newEndDate.toISOString().split('T')[0]}).`);
                                    alertedTasks.add(taskId);
                                }
                                outOfBoundsOCNs.add(ocn); // Mark OCN as out-of-bounds
                                hasOutOfBoundsTask = true;
                                console.warn(`Skipping task for OCN ${ocn}, color ${itemDetails.Color || 'N/A'} due to out-of-bounds end date: ${newEndDate.toISOString().split('T')[0]}`);
                                return; // Skip adding this task
                            }

                            console.log('=== DROP TASK DEBUG ===');
                            console.log('OCN:', ocn);
                            console.log('Color ID:', colorid);
                            console.log('Preferred Line:', lines[newLineIndex], 'Index:', newLineIndex);
                            console.log('Day Index:', dayIndex);
                            console.log('Start Date:', newStartDate.toISOString().split('T')[0]);
                            console.log('End Date:', newEndDate.toISOString().split('T')[0]);
                            console.log('Duration:', daysRequired);

                            // Create new task object
                            const newTask = {
                                ocn: ocn,
                                itemid: itemid,
                                colorid: colorid,
                                factoryexit: factoryexit,
                                orderqty: orderqty,
                                planqty: planqty,
                                start: newStartDate.toISOString().split('T')[0],
                                end: newEndDate.toISOString().split('T')[0],
                                line: 0, // Will be assigned by smart line assignment
                                duration: daysRequired,
                                units: itemDetails.Bal_To_Sew,
                                color: itemDetails.Color || 'Unknown',
                                item: itemDetails.Item || 'Unknown',
                                bal_to_sew: itemDetails.Bal_To_Sew || orderqty,
                                day_cap_per_line: itemDetails.Day_Cap_Per_Line,
                                mch_cap: itemDetails.No_Of_Mch || 0,
                                no_operators: itemDetails.No_Of_Operator || 0,
                                ck_date: itemDetails.Ck_DAte || '',
                                FI_date: itemDetails.FI_Date || '',
                                ship_date: itemDetails.FI_Date || '',
                                planner_opr: 0,
                            };

                            // Add to tasks array with smart line assignment
                            // For first variant, try to use the preferred line (where user dropped)
                            // For subsequent variants, let the system find available lines
                            const preferredLine = index === 0 ? newLineIndex : null;
                            const result = addTaskWithSmartLineAssignment(newTask, preferredLine);
                            
                            if (result.taskAdded) {
                                validTasksAdded = true;
                                console.log(`✅ Drop color variant ${index + 1} added successfully to line ${lines[result.assignedLine]}`);
                                if (result.hasConflict) {
                                    console.warn(`⚠️ Drop color variant ${index + 1} has conflicts on line ${lines[result.assignedLine]}`);
                                }
                            } else {
                                console.warn(`⚠️ Drop color variant ${index + 1} was not added due to duplication`);
                            }
                        });

                        // Remove backlog item only if no out-of-bounds tasks and at least one valid task was added
                        if (!hasOutOfBoundsTask && validTasksAdded) {
                            $draggedElement.remove();
                            backlogData = backlogData.filter(item => item.Ocn.split('\\').pop() !== ocn);
                            outOfBoundsOCNs.delete(ocn); // Clear out-of-bounds status
                        } else if (hasOutOfBoundsTask) {
                            $draggedElement.addClass('out-of-bounds'); // Apply orange background
                        }
                        // Re-render tasks after processing all variants
                        renderTasks(globalLineDates);
                        
                        // Remove from backlog
                        //ui.draggable.remove();
                        
                        console.log(`Processed ${response.data.length} color variants for dropped OCN ${ocn}`);
                    } else {
                        console.warn('No item data found for dropped OCN:', ocn);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to fetch item details for drop:', status, error);
                },
                complete: function() {
                    $('.sidebar').removeClass('blurred');
                }
            });
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }
        
        function handleShowDetailsClick() {
            if (selectedOCN) {
                $('#rawMaterialSidebar').addClass('active');
            } else {
                alert("Please select a task first to see details.");
            }
        }

        function handleCloseRawMaterialSidebar() {
            $('#rawMaterialSidebar').removeClass('active');
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function handlePrevMonthClick() {
            document.getElementById('planning-area').scrollLeft -= 200;
        }

        function handleNextMonthClick() {
            document.getElementById('planning-area').scrollLeft += 200;
        }

       

        const extractOCNNumber = ocn => {
    const match = ocn.match(/OCN(\d+)/);
    return match ? match[1].padStart(5, '0') : ocn.padStart(5, '0');
};

        function handleSaveClick() {
            let saveBtn = document.getElementById('saveBtn');
            saveBtn.disabled = true;
            saveBtn.classList.add('disabled');

            const initialTasks = microplandata.map(item => ({
                ocn_no: item.ocn_no,
                line_no: item.line_no,
                item_id: item.item_id,
                color_id: item.color_id,
                fromdate: item.planned_date,
                todate: item.shipping_date
            }));
            console.log('Initial Tasks in microplandata:', initialTasks);

            console.log('Tasks:', tasks);
            const newTasks = tasks.filter(task => {
                const numericOCN = getOcnNumber(task.ocn); // Use getOcnNumber for consistency
                const lineNo = parseInt((task.line_no || (task.line && lines[task.line]?.replace('L', '')) || task.line || 0));
                const taskKey = {
                    ocn_no: numericOCN,
                    line_no: lineNo,
                    item_id: task.itemid,
                    color_id: task.colorid,
                    fromdate: task.start,
                    todate: task.end
                };

                console.log(`Task Key:`, taskKey);

                // Check if task is new or updated (not in microplandata or different dates)
                const isNew = !initialTasks.some(existing => 
                    existing.ocn_no === numericOCN &&
                    existing.line_no === lineNo &&
                    existing.item_id == task.itemid &&
                    existing.color_id == task.colorid &&
                    existing.fromdate === task.start &&
                    existing.todate === task.end
                );

                // Check if task is in backlog
                const inBacklog = backlogData.some(item => {
                    const itemOCN = getOcnNumber(item.Ocn);
                    const itemLineNo = parseInt(item.Line_No || 0);
                    return itemOCN === numericOCN &&
                        itemLineNo === lineNo &&
                        item.Itemid == task.itemid &&
                        item.Colorid == task.colorid;
                });

                
                console.log(`Task ${numericOCN} (Line ${lineNo}, Item ${task.itemid}, Color ${task.colorid}): IsNew=${isNew}, InBacklog=${inBacklog} , "task.planner_qty",${task.planner_qty},"tasks_perday",${task.per_day_qty}`);
                return isNew || inBacklog;
            });

            console.log('New Tasks to Save:', newTasks);

            if (newTasks.length === 0) {
                console.warn('No new tasks to save. Check if tasks are already in microplandata or missing from backlogData.');
                alert("No new tasks to save. Please check if the task is already saved or not in the backlog.");
                return;
            }

            // Group tasks by ocn, item_id, and color_id
            const tasksByKey = {};
            newTasks.forEach(task => {
                const key = `${task.ocn}_${task.itemid}_${task.colorid}`;
                if (!tasksByKey[key]) {
                    tasksByKey[key] = [];
                }
                tasksByKey[key].push(task);
            });

            const postDataArray = Object.keys(tasksByKey).map(key => {
                const tasks = tasksByKey[key];
                const [ocn, itemId, colorId] = key.split('_');
                const details = tasks.map(task => {
                    task.taskstatus = 'saved';
                    const lineNo = parseInt(lines[task.line].replace('L', '')) || 1;
                    const selectedDates = getDatesBetween(task.start, task.end);
                    return {
                        unit_code: selectedUnitCode || '3',
                        line_no: lineNo,
                        item_id: task.itemid,
                        color_id: task.colorid,
                        item: task.item,
                        color: task.color,
                        planned_date: task.start,
                        planned_qty: task.bal_to_sew,
                        selected_dates: selectedDates,
                        is_split: task.is_split,
                        is_split_unit: task.splitunits || 0,
                        no_of_machines: task.mch_cap,
                        no_operators: task.no_operators,
                        ck_date: task.ck_date,
                        FI_date: task.FI_date,
                        planner_opr: task.planner_opr,
                        planner_qty: task.planner_qty,
                        per_day_qty: task.per_day_qty,
                        buyer: task.buyer,
                        taskstatus: task.taskstatus ? task.detail_id : '0',
                        taskisdragg : task.Isdragg,
                    };
                });

                const lineNoForPost = parseInt(lines[tasks[0].line].replace('L', '')) || 1;
                const extractOCNNumber = ocn => {
                    const match = ocn.match(/OCN(\d+)/);
                    return match ? match[1].padStart(5, '0') : ocn.padStart(5, '0');
                };

                return {
                    factory_id: (function() {
                        const code = Number(selectedUnitCode);
                        if ([3, 11, 13, 16].includes(code)) return '3';
                        if ([12, 7].includes(code)) return '12';
                        return code ? String(code) : '13';
                    })(),
                    ocn_no: extractOCNNumber(ocn),
                    line_no: lineNoForPost,
                    item_id: itemId,
                    color_id: colorId,
                    item: tasks.item,
                    item_name: 'N/A',
                    color: tasks.color,
                    order_qty: tasks.reduce((sum, task) => sum + (task.units || 2000), 0),
                    ship_date: tasks[0].end || '2025-06-20',
                    unit_id: selectedUnitCode || '3',
                    plan_date: tasks[0].start || '2025-06-18',
                    plan_enddate: tasks[0].end || '2025-06-18',
                    created_by: window.emp_id || 101,
                    ck_date: tasks.ck_date,
                    FI_date: tasks.FI_date,
                    planner_opr: tasks.planner_opr,
                    planner_qty: tasks.planner_qty,
                    per_day_qty: tasks.per_day_qty,
                    details: details
                };
            });

            console.log('Save Data Array:', postDataArray);

            $.ajax({
                url: '/insertOrUpdateMicroPlan',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(postDataArray),
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                success: function(res) {
                    console.log('Saved:', res);
                    const savedOCNs = newTasks.map(task => extractOCNNumber(task.ocn));
                    microplandata.push(...newTasks.map(task => ({
                        ocn_no: extractOCNNumber(task.ocn),
                        planned_qty: task.units || 2000,
                        shipping_date: task.end,
                        item_id: task.itemid,
                        color_id: task.colorid,
                        item: task.item,
                        color: task.color,
                        ck_date: task.ck_date,
                        FI_date: task.FI_date,
                        line_no: parseInt(lines[task.line].replace('L', ''))
                    })));
                    backlogData = backlogData.filter(item => {
                        const itemOCN = item.Ocn.split('\\').pop().replace(/^OCN/, '').trim();
                        return !savedOCNs.includes(itemOCN);
                    });
                    renderBacklogItems();
                    renderTasks();
                    alert('Plan saved successfully!');
                    saveBtn.disabled = false; 
                    saveBtn.classList.remove('disabled');
                },
                error: function(err) {
                    console.error('Failed:', err);
                    alert('Failed to save tasks. Please try again.');
                    saveBtn.disabled = false; 
                    saveBtn.classList.remove('disabled');
                }
            });
        }

        // Helper function to get dates between start and end (inclusive)
        function getDatesBetween(startDate, endDate) {
            const dates = [];
            let currentDate = new Date(startDate);
            const end = new Date(endDate);

            while (currentDate <= end) {
                if (currentDate.getDay() !== 0) { // Skip Sundays (0 = Sunday)
                    dates.push(currentDate.toISOString().split('T')[0]); // Format as YYYY-MM-DD
                }
                currentDate.setDate(currentDate.getDate() + 1);
            }

            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
            console.log(`Dates between ${startDate} and ${endDate}:`, dates);
            return dates;
        }


        function generateTasksPerColumn() {
            // Create an array with proper structure for all columns
            const tasksPerColumn = [];

            // Get the working dates (excluding Sundays and holidays)
            const workingDates = globalLineDates
                .filter(date => new Date(date.Edate).getDay() !== 0) // Exclude Sundays
                .sort((a, b) => new Date(a.Edate) - new Date(b.Edate));

            // Initialize array for all columns
            for (let i = 0; i < workingDates.length; i++) {
                tasksPerColumn.push({
                    column: (i + 1).toString(),
                    total_mch_cap: 0,
                    total_no_of_opr: 0,
                    total_qty: 0, // Initialize total_qty
                    task_details: []
                });
            }

            // Process each task to determine which columns it spans
            tasks.forEach(task => {
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);

                // Find which columns this task spans
                const taskColumns = [];
                workingDates.forEach((date, index) => {
                    const dateObj = new Date(date.Edate);
                    if (dateObj >= taskStart && dateObj <= taskEnd) {
                        taskColumns.push(index);
                    }
                });

                // Add task data to each column it spans
                taskColumns.forEach(columnIndex => {
                    if (tasksPerColumn[columnIndex]) {
                        const mchCap = parseFloat(task.mch_cap || 0) || 0;
                         let Qty = 0;
                         let noOfOpr =0;

                         console.log('task.no_operators',task.no_operators,'task.planner_opr',task.planner_opr,'task.planner_qty',task.planner_qty,'task.per_day_qty',task.per_day_qty)
                             
                        if(task.planner_opr !=='0' && task.planner_qty!=''){
                            noOfOpr = parseInt(task.planner_opr) || 0;
                            // Qty = parseFloat(task.per_day_qty || 668) || 0;
                           // alert(task.units);
                        }else{
                             noOfOpr = parseInt(task.no_operators || 0) || 0;
                        }
                        

                       
                        if(task.planner_qty !='0'){
                           // Qty = parseInt(task.planner_qty || 668) || 0;
                          
                            Qty = (parseInt(task.planner_qty) > task.bal_to_sew)? parseInt(task.bal_to_sew || 0): parseInt(task.planner_qty) || 0;
                            
                        }else{
                             //Qty = parseInt(task.per_day_qty || task.day_cap_per_line || 668) || 0;
                             Qty = (parseInt(task.per_day_qty) > task.bal_to_sew)? parseInt(task.bal_to_sew || 0): parseInt(task.per_day_qty) || 0;
                            // console.log("wel", Qty + '-' + task.ocn);

                        }

                        
                        

                        tasksPerColumn[columnIndex].total_mch_cap += mchCap;
                        tasksPerColumn[columnIndex].total_no_of_opr += noOfOpr;
                        tasksPerColumn[columnIndex].total_qty += Qty;
                        tasksPerColumn[columnIndex].task_details.push({
                            ocn: task.ocn,
                            mch_cap: mchCap,
                            no_operators: noOfOpr
                        });
                    }
                });
                console.log('taskunit RAJ',task.units);
            });
            

            console.log('Tasks per column with totals:', tasksPerColumn);
            return tasksPerColumn;
        }
        
        // Global variable to store lineDates
        let globalLineDates = [];

        function generateGanttChart(lineDates) {
            if (!lineDates || lineDates.length === 0) {
                return;
            }

            // Store lineDates globally
            globalLineDates = lineDates;

            const $header = $("#gantt-header").empty();
            const $body = $("#gantt-body").empty();
            const $footer = $("#gantt-footer").empty();

            // Filter out Sundays and sort by Edate for the grid display
            const dates = lineDates
                .filter(date => new Date(date.Edate).getDay() !== 0) // Exclude Sundays (0 = Sunday)
                .sort((a, b) => new Date(a.Edate) - new Date(b.Edate));

            // Use original lineDates sorted for accurate date mapping
            const allDates = lineDates.sort((a, b) => new Date(a.Edate) - new Date(b.Edate));
            const dateMap = {};
            allDates.forEach((date, index) => {
                dateMap[index] = dates.findIndex(d => d.Edate === date.Edate) || 0;
            });

            // Year Row
            let yearRow = '<tr class="planning-header text-center bg-light"><th rowspan="4" style="width: 50px; position: sticky; left: 0; background: #f1f1f1; z-index: 21; border-right: 2px solid #ddd;">Line</th>';
            yearRow += '<th rowspan="4" style="width: 50px; position: sticky; left: 50px; background: #f1f1f1; z-index: 21; border-right: 2px solid #ddd;">Machines</th>';
            const yearMap = {};
            dates.forEach(date => {
                const year = new Date(date.Edate).getFullYear();
                yearMap[year] = (yearMap[year] || 0) + 1;
            });
            for (const year in yearMap) {
                yearRow += `<th colspan="${yearMap[year]}" class="text-center bg-light">${year}</th>`;
            }
            yearRow += '</tr>';

            // Month Row
            let monthRow = '<tr class="planning-header text-center bg-light">';
            const monthMap = {};
            dates.forEach(date => {
                const month = new Date(date.Edate).toLocaleString('default', { month: 'short' });
                monthMap[month] = (monthMap[month] || 0) + 1;
            });
            for (const month in monthMap) {
                monthRow += `<th colspan="${monthMap[month]}" class="text-center bg-light">${month}</th>`;
            }
            monthRow += '</tr>';

            // Week Row
            let weekRow = '<tr class="planning-header text-center bg-light">';
            const weekMap = {};
            dates.forEach(date => {
                const week = `WEEK ${date.WeekNumber}`;
                weekMap[week] = (weekMap[week] || 0) + 1;
            });
            for (const week in weekMap) {
                weekRow += `<th colspan="${weekMap[week]}" class="text-center bg-light" style="min-width: 40px;">${week}</th>`;
            }
            weekRow += '</tr>';

            // Day Row
            let dayRow = '<tr class="planning-header text-center bg-light" style="position: sticky; top: 0; z-index: 20;">';
            dates.forEach(date => {
                const day = new Date(date.Edate).getDate();
                const isWeekend = new Date(date.Edate).getDay() === 6; // Only Saturday as weekend
                const isHoliday = date.NH !== null; // Check for holiday
                dayRow += `<th class="date-header text-center ${isWeekend ? 'weekend' : ''} ${isHoliday ? 'holiday' : ''}" data-date="${date.Edate}" style="min-width: 55px;">${day}</th>`;
            });
            dayRow += '</tr>';

            $header.append(yearRow + monthRow + weekRow + dayRow);

            // Generate Body
            lines.forEach((line, index) => {
                let row = `<tr data-line="${index}" data-line-no="${line}" role="row">`;

                // Define zone colors for text and background
                const zoneColors = {
                    'A': { text: '#EE82EE', bg: '#EE82EE' },
                    'B': { text: 'orange', bg: '#ffebcd' },
                    'C': { text: 'navy', bg: '#e6e6ff' }
                };

                // Display line details in "Line" column with Zone in specific color
                const zone = lineZones[line] || 'N/A';
                const zoneColor = zoneColors[zone]?.text || 'black';
                row += `<td style="position: sticky; left: 0; background: #fff; z-index: 22; border-right: 1px solid #ccc; font-size: 12px; min-width: 50px;" scope="row">${line} <span style="color: ${zoneColor};"></span></td>`;

                // Display machine capacity in "Machines" column with dynamic background color based on zone
                const zoneBgColor = zoneColors[zone]?.bg || '#fff';
                row += `<td style="position: sticky; left: 50px; background: ${zoneBgColor}; z-index: 22; border-right: 1px solid #ccc; font-size: 12px; min-width: 50px;" scope="row">${lineCapacities[line] || 'N/A'}</td>`;

                let workingDayIndex = 0;
                dates.forEach((date, dayIndex) => {
                    const dateObj = new Date(date.Edate);
                    const isWeekend = dateObj.getDay() === 6;
                    const isHoliday = date.NH !== null;
                    row += `<td data-day="${workingDayIndex}" class="${isWeekend ? 'weekend' : ''} ${isHoliday ? 'holiday' : ''}"></td>`;
                    workingDayIndex++;
                });
                row += '</tr>';

                $body.append(row);
            });

            // --- FOOTER ROWS ---
            const totalLineCapacity = lines.reduce((sum, line) => sum + (Number(lineCapacities[line]) || 0, 0) || 0);
            const tasksPerColumn = generateTasksPerColumn();

            console.log('Tasks per column kratos: ', tasksPerColumn);

            // Main footer rows
            let footerRow = `<tr class="table-footer text-center footer-toggle-row" style="cursor:pointer; position:sticky; bottom:62px; background:#f8f9fa; z-index:98;">`;
            footerRow += `<td colspan="1" style="font-weight: bold; background: #e9ecef; position: sticky; left: -5px; z-index: 99;">Mch</td>`;
            footerRow += `<td style="font-weight: bold; background: #e9ecef; position: sticky; left: 50px; z-index: 99;">${
                lines.reduce((sum, line) => sum + (Number(lineCapacities[line]) || 0), 0) || 'N/A'
            }</td>`;

            let footerRow3 = `<tr class="table-footer text-center footer-toggle-opt-row" style="cursor:pointer; position:sticky; bottom:29px; background:#f8f9fa; z-index:98;">`;
            footerRow3 += `<td class="ps-3" colspan="1" style="font-weight: bold; background: #e9ecef; position: sticky; left: -5px; z-index: 99; text-align: left;">Opr</td>`;
            footerRow3 += `<td style="font-weight: bold; background: #e9ecef; position: sticky; left: 50px; z-index: 99;">${
                lines.reduce((sum, line) => sum + (Number(lineCapacities[line]) || 0), 0) || 'N/A'
            }</td>`;

            let footerRowPerDay = `<tr class="footer-per-day-row table-footer text-center" style="position:sticky; bottom:-10px; background:#f8f9fa; z-index:98;">`;
            footerRowPerDay += `<td colspan="1" style="font-weight: bold; background: #e9ecef; position: sticky; left: -5px; z-index: 99;">Qty</td>`;
            footerRowPerDay += `<td style="font-weight: bold; background: #e9ecef; position: sticky; left: 50px; z-index: 99;">
            </td>`;


            dates.forEach((date, index) => {
                const totalMchCap = tasksPerColumn[index]?.total_mch_cap || 0;
                const colorStyle = totalMchCap > totalLineCapacity ? 'color: red;' : '';
                footerRow += `<td data-footer-day="${index}" data-date="${date.Edate}" class="footer-cell footer-cell-toggle" style="font-size: 12px; cursor:pointer; text-align: center !important; ${colorStyle}">${totalMchCap}</td>`;

                const totalNoOfOpr = tasksPerColumn[index]?.total_no_of_opr || 0;
                footerRow3 += `<td data-footer-day="${index}" data-date="${date.Edate}" class="footer-cell" style="font-size: 12px; text-align: center !important;">${totalNoOfOpr}</td>`;

                // Example: Per Day Qty (replace 0 with your actual value if available)
                const perDayQty = tasksPerColumn[index]?.total_qty || 0;
                footerRowPerDay += `<td data-footer-day="${index}" data-date="${date.Edate}" class="footer-cell" style="font-size: 12px; text-align: center !important;">${perDayQty}</td>`;
            });

            footerRow += `</tr>`;
            footerRow3 += `</tr>`;
            footerRowPerDay += `</tr>`;
            $footer.append(footerRow);

            // Generate machine type rows (append directly to $footer)
            [
            "2T F/L",
            "3T F/L",
            "3T HF/L",
            "3T O/L",
            "4T O/L",
            "5T F/L",
            "5T HF/L",
            "BARTACK",
            "BUTTON",
            "FUSING",
            "IRON BOX",
            "KAJA",
            "KANSAI",
            "MANUAL",
            "OUTER ELASTIC",
            "RIB O/L",
            "SNAP BUTTON",
            "SNLS"
            ]
            .forEach(type => {
                let machineRow = `<tr class="machine-type-row d-none" data-type="${type}">`;
                machineRow += `<td colspan="2" style="font-weight: bold; background: #e9ecef; position: sticky; left: -5px; z-index: 99; text-align: right; padding-right: 10px;">${type}</td>`;
                dates.forEach((date, index) => {
                    const val = window.machineFooterData?.[index]?.[type] || '0';
                    machineRow += `<td data-date="${date.Edate}" class="machine-type-cell" style="font-size: 10px;">${val}</td>`;
                });
                machineRow += `</tr>`;
                $footer.append(machineRow);
            });

            $footer.append(footerRow3);

            // Generate operator type rows (append directly to $footer)
            const typeDisplayMap = {
                'A': 'Skill_A',
                'B': 'Skill_B',
                'C': 'Skill_C',
                'D': 'Skill_D',
                'HELPER': 'HELPER'
            };

            ['A', 'B', 'C', 'D', 'HELPER'].forEach(type => {
                let operatorRow = `<tr class="operator-type-row d-none" data-type="${type}">`;
                operatorRow += `<td colspan="2" style="font-weight: bold; background: #e9ecef; position: sticky; left: -5px; z-index: 99; text-align: right; padding-right: 20px">${typeDisplayMap[type]}</td>`;
                dates.forEach((date, index) => {
                    const val = window.operatorFooterData?.[index]?.[type] || '0';
                    operatorRow += `<td data-date="${date.Edate}" class="operator-type-cell" style="font-size: 10px;">${val}</td>`;
                });
                operatorRow += `</tr>`;
                $footer.append(operatorRow);
            });

            $footer.append(footerRowPerDay);

            // Set up toggle handlers
            $(document).off('click.footer-toggle').on('click.footer-toggle', '.footer-toggle-row .footer-cell-toggle', function() {
                $('.machine-type-row').toggleClass('d-none');
            });

            $(document).off('click.footer-toggle-opt').on('click.footer-toggle-opt', '.footer-toggle-opt-row .footer-cell', function() {
                $('.operator-type-row').toggleClass('d-none');
            });

            // Render tasks
            renderTasks(globalLineDates);
        }

        // Toggle logic for footer rows
        $(document).off('click.footer-toggle').on('click.footer-toggle', '.footer-toggle-row .footer-cell-toggle', function() {
            $('.footer-opt-row').toggleClass('d-none');
        });

        $(document).off('click.footer-toggle-opt').on('click.footer-toggle-opt', '.footer-toggle-opt-row .footer-cell1', function() {
            $('.footer-opt1-row').toggleClass('d-none');
        });


        function updateFooterWithTaskCounts(tasksPerColumn) {
            // Get total line capacity (same logic as in generateGanttChart)
            const totalLineCapacity = lines.reduce((sum, line) => sum + (Number(lineCapacities[line]) || 0), 0) || 0;

            // Update the main footer row (machines used)
            const $footerCells = $('#gantt-footer').find('tr.table-footer td.footer-cell');
            tasksPerColumn.forEach((colData, index) => {
                if ($footerCells.eq(index).length) {
                    const totalMchCap = colData.total_mch_cap || 0;
                    $footerCells.eq(index)
                        .text(totalMchCap)
                        .css('color', totalMchCap > totalLineCapacity ? 'red' : '');
                    // Debug log
                }
            });

            // Update the operator row
            const $footerOptRow = $('#gantt-footer').find('tr.footer-toggle-opt-row');
            const $footerOptCells = $footerOptRow.find('td.footer-cell');
            tasksPerColumn.forEach((colData, index) => {
                if ($footerOptCells.eq(index).length) {
                    $footerOptCells.eq(index).text(colData.total_no_of_opr || 0);
                }
            });

            const $footerPerDayRow = $('#gantt-footer').find('tr.footer-per-day-row');
            const $footerPerDayCells = $footerPerDayRow.find('td.footer-cell');
            tasksPerColumn.forEach((colData, index) => {
                if ($footerPerDayCells.eq(index).length) {
                    $footerPerDayCells.eq(index).text(colData.total_qty || 0);
                }
            });
        }

        function setupFooterToggles() {
            // Machine types footer toggle
            $(document).off('click.footer-toggle').on('click.footer-toggle', '.footer-toggle-row .footer-cell-toggle', function() {
                const $clickedCell = $(this);
                const colIndex = $clickedCell.index();
                
                // Find or create the container for machine type rows
                let $machineRowsContainer = $clickedCell.closest('tr').next('.machine-rows-container');
                
                if ($machineRowsContainer.length === 0) {
                    $machineRowsContainer = $('<div class="machine-rows-container"></div>').insertAfter($clickedCell.closest('tr'));
                    
                    // Create a row for each machine type
                    [
                    "2T F/L",
                    "3T F/L",
                    "3T HF/L",
                    "3T O/L",
                    "4T O/L",
                    "5T F/L",
                    "5T HF/L",
                    "BARTACK",
                    "BUTTON",
                    "FUSING",
                    "IRON BOX",
                    "KAJA",
                    "KANSAI",
                    "MANUAL",
                    "OUTER ELASTIC",
                    "RIB O/L",
                    "SNAP BUTTON",
                    "SNLS"
                    ]
                    .forEach((type, i) => {
                        const $row = $(`<tr class="machine-type-row" data-type="${type}" style="display: none;"></tr>`);
                        
                        
                        // Add cells for each date column
                        $clickedCell.closest('tr').find('.footer-cell-toggle').each(function(index) {
                            const dateStr = $(this).data('date');
                            const val = machineTypes[type]?.[dateStr] || '0';
                            $row.append(`<td class="machine-type-cell" data-date="${dateStr}">${val}</td>`);
                        });
                        
                        $machineRowsContainer.append($row);
                    });
                }
                
                // Toggle visibility of machine type rows
                $machineRowsContainer.find('.machine-type-row').toggle();
            });

            // Operator types footer toggle
            $(document).off('click.footer-toggle-opt').on('click.footer-toggle-opt', '.footer-toggle-opt-row .footer-cell', function() {
                const $clickedCell = $(this);
                const colIndex = $clickedCell.index();
                
                // Find or create the container for operator type rows
                let $operatorRowsContainer = $clickedCell.closest('tr').next('.operator-rows-container');
                
                if ($operatorRowsContainer.length === 0) {
                    $operatorRowsContainer = $('<div class="operator-rows-container"></div>').insertAfter($clickedCell.closest('tr'));
                    
                    // Create a row for each operator type
                    ['A', 'B', 'C', 'D', 'HELPER'].forEach((type, i) => {
                        const $row = $(`<tr class="operator-type-row" data-type="${type}" style="display: none;"></tr>`);
                        
                        // Add cells for each date column
                        $clickedCell.closest('tr').find('.footer-cell').each(function(index) {
                            const dateStr = $(this).data('date');
                            const val = operatorTypes[type]?.[dateStr] || '0';
                            $row.append(`<td class="operator-type-cell" data-date="${dateStr}">${val}</td>`);
                        });
                        
                        $operatorRowsContainer.append($row);
                    });
                }
                
                // Toggle visibility of operator type rows
                $operatorRowsContainer.find('.operator-type-row').toggle();
            });
        }


        function updateFooterDetailsRows(selectedUnitCode, dates) {
            $.ajax({
                url: '/machinedetails',
                method: 'GET',
                data: { unit: selectedUnitCode },
                success: function(response) {
                    if (!response.data) return;

                    const machineData = response.data.data.machine || [];
                    const operatorData = response.data.data.operator || [];
                    
                    // Build machine types lookup
                    machineTypes = {};
                    machineData.forEach(row => {
                        machineTypes[row.Mch_Type] = row;
                    });
                    
                    // Build operator types lookup
                    operatorTypes = {};
                    operatorData.forEach(row => {
                        operatorTypes[row.Mch_Type] = row;
                    });
                    
                    // Update machine type rows if they exist
                    $('.machine-type-row').each(function() {
                        const type = $(this).data('type');
                        $(this).find('.machine-type-cell').each(function() {
                            const dateStr = $(this).data('date');
                            const val = machineTypes[type]?.[dateStr] || '0';
                            $(this).text(val);
                        });
                    });
                    
                    // Update operator type rows if they exist
                    $('.operator-type-row').each(function() {
                        const type = $(this).data('type');
                        $(this).find('.operator-type-cell').each(function() {
                            const dateStr = $(this).data('date');
                            const val = operatorTypes[type]?.[dateStr] || '0';
                            $(this).text(val);
                        });
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Failed to fetch machine/operator footer details:', status, error, xhr.responseText);
                }
            });
        }

        // Call this during initialization
        setupFooterToggles();


        // function updateFooterDetailsRows(selectedUnitCode, dates) {
        //     $.ajax({
        //         url: '/machinedetails',
        //         method: 'GET',
        //         data: { unit: selectedUnitCode },
        //         success: function(response) {
        //             if (!response.data) return;

        //             const machineData = response.data.data.machine || [];
        //             const operatorData = response.data.data.operator || [];
                    
        //             // Build machine types lookup
        //             machineTypes = {};
        //             machineData.forEach(row => {
        //                 machineTypes[row.Mch_Type] = row;
        //             });
                    
        //             // Build operator types lookup
        //             operatorTypes = {};
        //             operatorData.forEach(row => {
        //                 operatorTypes[row.Mch_Type] = row;
        //             });
                    
        //             // Update machine type rows if they exist
        //             $('.machine-type-row').each(function() {
        //                 const type = $(this).data('type');
        //                 $(this).find('.machine-type-cell').each(function() {
        //                     const dateStr = $(this).data('date');
        //                     const val = machineTypes[type]?.[dateStr] || '0';
        //                     $(this).text(val);
        //                 });
        //             });
                    
        //             // Update operator type rows if they exist
        //             $('.operator-type-row').each(function() {
        //                 const type = $(this).data('type');
        //                 $(this).find('.operator-type-cell').each(function() {
        //                     const dateStr = $(this).data('date');
        //                     const val = operatorTypes[type]?.[dateStr] || '0';
        //                     $(this).text(val);
        //                 });
        //             });
        //         },
        //         error: function(xhr, status, error) {
        //             console.error('Failed to fetch machine/operator footer details:', status, error, xhr.responseText);
        //         }
        //     });
        // }

        // // Call this during initialization
        // setupFooterToggles();

        function renderTasks(lineDates) {
            const $taskLayer = $("#task-layer").empty(); // Clear existing bars
            const $tooltipContainer = $("#custom-tooltip").length ? $("#custom-tooltip") : $('<div>', { id: 'custom-tooltip', css: { display: 'none' } }).appendTo('body');
            
            // Check if we have the required data
            if (!document.getElementById('start-date')?.value) {
                console.warn('No start date available for rendering tasks');
                return;
            }

            const conflicts = detectConflicts();
            const gridStartDate = new Date(document.getElementById('start-date').value);
            const gridEndDate = new Date(document.getElementById('end-date').value);
            
            // Use global lineDates if not provided
            const dates = lineDates || globalLineDates || [];
            
           // console.log('=== RENDER TASKS DEBUG ===');
           // console.log('Total tasks to render:', tasks.length);
           // console.log('Tasks array:', tasks);
           // console.log('Grid start date:', gridStartDate);
           // console.log('Grid end date:', gridEndDate);
           // console.log('Available dates:', dates.length);
            
            // Track rendered tasks for debugging
            let renderedCount = 0;
            let skippedCount = 0;
            
            tasks.forEach((task, i) => {
               // console.log(`\n--- Processing Task ${i} ---`);
                console.log('Task data kratos:', task);
                
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                
                // Validate task dates
                if (isNaN(taskStart.getTime()) || isNaN(taskEnd.getTime())) {
                    console.warn(`Task ${i} has invalid dates:`, task);
                    skippedCount++;
                    return;
                }
                
                // Check if task is within grid range
                if (taskEnd < gridStartDate || taskStart > gridEndDate) {
                    console.warn(`Task ${i} outside grid range:`, {
                        taskStart: taskStart.toISOString().split('T')[0],
                        taskEnd: taskEnd.toISOString().split('T')[0],
                        gridStart: gridStartDate.toISOString().split('T')[0],
                        gridEnd: gridEndDate.toISOString().split('T')[0]
                    });
                    skippedCount++;
                    return;
                }

                // Calculate day index based on working days (excluding Sundays and holidays)
                let dayIndex = 0;
                let currentDate = new Date(gridStartDate);
                
                while (currentDate < taskStart) {
                    if (currentDate.getDay() !== 0 && !isHoliday(currentDate, dates)) {
                        dayIndex++;
                    }
                    currentDate.setDate(currentDate.getDate() + 1);
                }

                // Calculate effective duration (working days only)
                let effectiveDuration = 0;
                currentDate = new Date(taskStart);
                while (currentDate <= taskEnd) {
                    if (currentDate.getDay() !== 0 && !isHoliday(currentDate, dates)) {

                        effectiveDuration++;
                    } else {
                        console.log(`Skipping date ${currentDate.toISOString().split('T')[0]}: Holiday or Sunday ${currentDate} ---${taskEnd}`);
                    }
                    currentDate.setDate(currentDate.getDate() + 1);
                }

                // Ensure minimum duration
                effectiveDuration = Math.max(1, effectiveDuration);

                // Calculate position
                let taskLeft = (dayIndex * cellWidth + 120);
                let taskTop = (task.line * rowHeight + 75 + (rowHeight - 35) / 2);
                
                // Display OCN
                let displayedOcn = task.ocn.includes('GIL/') || task.ocn.includes('GIL\\')
                    ? task.ocn.replace('GIL/', '').replace('GIL\\', '').replace(/^OCN/, '')
                    : task.ocn.replace(/^OCN/, '');

                // Add color information to display
                let itemid = task.itemid ? ` ${task.itemid})` : '';
                let machine_cap = task.mch_cap ? ` (${task.mch_cap})` : '';
                let colorInfo = task.color ? ` (${task.color})` : '';

                let displayInfo = `${displayedOcn || ''} - ${task.item || ''} - ${task.color || ''}`;
                let displayText = displayedOcn + colorInfo;
                let displaynewText = displayInfo;

                // Get shipping date for color coding
               // Replace the shipping date check in renderTasks() with this:
                let shippingDate = task.ship_date; // First check the task's own ship_date

                // Only fall back to microplandata/backlogData if not found in task
                if (!shippingDate) {
                    if (typeof microplandata !== 'undefined') {
                        taskData = microplandata.find(item => item.ocn_no === task.ocn);
                    }
                    if (!taskData && typeof backlogData !== 'undefined') {
                        taskData = backlogData.find(item => item.Ocn?.split('\\').pop() === task.ocn);
                    }
                    if (taskData) {
                        shippingDate = taskData.FI_Date;
                    }
                }

                // Color code the bar
                let barcolor = 'linear-gradient(135deg, #4CAF50, #3e8e41)'; // Default green
                let hasConflict = false;

                // Check for conflicts on this line and date range
                const conflictingTasks = tasks.filter(otherTask => {
                    if (otherTask.id === task.id) return false;
                    if (otherTask.line !== task.line) return false;
                    
                    const otherStart = new Date(otherTask.start);
                    const otherEnd = new Date(otherTask.end);
                    const taskStart = new Date(task.start);
                    const taskEnd = new Date(task.end);
                    
                    return (taskStart <= otherEnd && taskEnd >= otherStart);
                });

                hasConflict = conflictingTasks.length > 0;

                // Check if task crosses shipping date
                if (shippingDate) {
                    const shippingDateObj = new Date(shippingDate);
                    const taskEndDate = new Date(task.end);

                    console.log(`Task ${i} shipping date check:`, {
                        taskOCN: task.ocn,
                        taskEndDate: taskEndDate.toISOString().split('T')[0],
                        shippingDate: shippingDateObj.toISOString().split('T')[0],
                        isOverdue: taskEndDate > shippingDateObj,
                        source: task.ship_date ? 'task object' : 'microplan/backlog data'
                    });
                    
                    if (taskEndDate > shippingDateObj) {
                        barcolor = 'linear-gradient(135deg, #ff0000, #cc0000)'; // Red for overdue
                        hasConflict = true;
                    } else if (hasConflict) {
                        barcolor = 'linear-gradient(135deg, #ff9800, #f57c00)'; // Orange for other conflicts
                    }
                } else if (hasConflict) {
                    barcolor = 'linear-gradient(135deg, #ff9800, #f57c00)'; // Orange for conflicts
                }
                // hasConflict = conflictingTasks.length > 0;
                
                // if (hasConflict) {
                //     barcolor = 'linear-gradient(135deg, #ff9800, #f57c00)'; // Orange for conflicts
                // } else if (shippingDate && taskEnd > new Date(shippingDate)) {
                //     barcolor = 'linear-gradient(135deg, #ff0000, #cc0000)'; // Red for overdue
                // }

                // Generate and log dates between start and end, excluding Sundays/holidays
                const datesBetween = getDatesBetween(task.start, task.end).map(dateStr => new Date(dateStr)).filter(date => date.getDay() !== 0 && !isHoliday(date, dates));
               console.log(`Task ${displayText} (ID: ${task.id || i}): Dates between ${task.start} and ${task.end} (excluding Sundays/Holidays):`, datesBetween.map(date => date.toISOString().split('T')[0]));

                console.log(`Task ${i} positioning:`, {
                    dayIndex,
                    effectiveDuration,
                    taskLeft: `${taskLeft}px`,
                    taskTop: `${taskTop}px`,
                    width: `${effectiveDuration * cellWidth}px`,
                    displayedOcn: displayText,
                    line: lines[task.line] || task.line,
                    color: task.color,
                    hasConflict: hasConflict,
                    conflictCount: conflictingTasks.length,
                    planned_date: task.start || null,
                    ship_date: task.end || null,
                    startdate: task.start || null
                });

                                // Build task bar element
                const $bar = $('<div>', {
                    class: `task-bar ${conflicts.some(c => c.includes(i)) ? 'conflict' : ''} ${hasConflict ? 'line-conflict' : ''}`,
                    'data-id': task.id || i,
                    'data-task-index': i,
                    'data-label': displayText,
                    'data-tooltip': `OCN: ${displayedOcn}, Color: ${task.color || 'N/A'}, ItemId: ${task.itemid || 'N/A'}, Line: ${lines[task.line]},`,
                    'data-ocn': displayedOcn,
                    'data-color': task.color || '',
                    'data-itemid': task.itemid || '',
                    'data-line': lines[task.line] || '',
                    'data-start': task.start || '',
                    'data-end': task.end || '',
                    'data-itemname': task.item || '',
                    css: {
                        background: barcolor,
                        left: `${taskLeft}px`,
                        top: `${taskTop}px`,
                        width: `${effectiveDuration * cellWidth}px`,
                        height: '35px',
                        position: 'absolute',
                        zIndex: hasConflict ? 2 : 1,
                        borderRadius: '8px',
                        boxShadow: hasConflict ? '0 2px 8px rgba(255, 152, 0, 0.6)' : '0 2px 6px rgba(0,0,0,0.3)',
                    }
                }).append(
                    $('<span>', { 
                        class: 'task-bar-click', 
                        'data-id': task.id || i, 
                        html: `<span class="task-bar-prefix">${displaynewText.slice(1,5)} ${displaynewText.slice(5)}</span>`,
                        css: {
                            display: 'inline-block',
                            width: '100%',
                            height: '100%',
                            lineHeight: '35px',
                            textAlign: 'center',
                            color: '#fff',
                            fontWeight: hasConflict ? 'bold' : '500',
                            fontSize: '12px',
                            cursor: 'pointer',
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis'
                        }
                    }).hover(
                        function() {
                            $tooltipContainer.html(`
                                <div class="tooltip-columns">
                                    <div class="tooltip-column">
                                        <div><b>OCN:</b> ${displayedOcn}</div>
                                        <div><b>Line:</b> ${lines[task.line]}</div>
                                    </div>
                                    <div class="tooltip-column">
                                        <div><b>Item:</b> ${task.item || 'N/A'}</div>
                                        <div><b>Color:</b> ${task.color || 'N/A'}</div>
                                    </div>
                                    <div class="tooltip-column">
                                        <div><b>Start:</b> ${formatDatee(task.start) || 'N/A'}</div>
                                        <div><b>End:</b> ${formatDatee(task.end) || 'N/A'}</div>
                                    </div>
                                    <div class="tooltip-column">
                                        <div><b>Duration:</b> ${effectiveDuration}</div>
                                        <div><b>Planned Qty:</b> ${task.units}</div>
                                    </div>
                                </div>
                            `).show();
                        },
                        function() {
                            $tooltipContainer.hide();
                        }
                    )
                );

                task.line_no = lines[task.line] || task.line ;
                task.planned_qty = (task.planned_qty && task.planned_qty !== 0) ? task.planned_qty : task.bal_to_sew;


                // Append the bar to the task layer
                $taskLayer.append($bar);
                renderedCount++;
                
                //console.log(`✅ Task ${i} rendered successfully`);
            });
            
           // console.log(`\n=== RENDER SUMMARY ===`);
           // console.log(`Total tasks: ${tasks.length}`);
           // console.log(`Rendered: ${renderedCount}`);
           // console.log(`Skipped: ${skippedCount}`);
           // console.log(`Task layer children: ${$taskLayer.children().length}`);

            const tasksPerColumn = generateTasksPerColumn();
            updateFooterWithTaskCounts(tasksPerColumn);
            
            
            updateFooterDetailsRows(selectedUnitCode, dates.map(d => d.Edate));
        }

        function updateSingleTask(ocn_no, itemid, colorid, lineno, planned_tailor_qty, lineDates, og_per_day_qty, no_operators) {
            let $taskLayer = $("#task-layer");
            let $details = $('#order-details-dynamic');
            let gridStartDate = new Date(document.getElementById('start-date').value);
            let gridEndDate = new Date(document.getElementById('end-date').value);
            let dates = lineDates || globalLineDates || [];
            let ocnNumber = getOcnNumber(ocn_no);
            let line = lineno.replace('L', '');

            // Find the task to update
            let task = tasks.find(t => {
                let taskOcnNumber = getOcnNumber(t.ocn);
                let taskLineNo = lines[t.line].replace('L', '') || (t.line && lines[t.line]?.replace('L', '')) || t.line || 0;
               
                return taskOcnNumber === ocnNumber &&
                    t.itemid == itemid &&
                    t.colorid == colorid &&
                    taskLineNo == line;
            });

            if (!task) {
                console.error("Task not found for update:", { ocnNumber, itemid, colorid, lineno });
                alert("Task not found to update.");
                return;
            }
            console.log('task.no_operators',task.no_operators,'no_operators', no_operators,'planner_opr', task.planner_opr,'og_per_day_qty', og_per_day_qty, 'planned_tailor_qty', planned_tailor_qty,"task.bal_to_sew",task.bal_to_sew);

            let number_of_operators = no_operators || task.no_operators ;

            // Calculate No_of_days
            let No_of_days = 0;
            if (planned_tailor_qty > 0 && number_of_operators > 0 && task.bal_to_sew > 0) {
                let dummyqt = (og_per_day_qty / number_of_operators) * planned_tailor_qty;
                No_of_days = Math.round(task.bal_to_sew / dummyqt);
                console.log(`Calculated No_of_days for task ${ocn_no} dummyqt:`, No_of_days, dummyqt);
                task.planner_qty = Math.round(dummyqt);
                task.planner_opr = planned_tailor_qty;
                $details.find('#per_day_qty').text(task.planner_qty);
            } else {
                console.warn("Invalid data for No_of_days calculation:", {
                    planned_tailor_qty,
                    no_operators: number_of_operators,
                    bal_to_sew: task.bal_to_sew,
                    planner_opr: task.planner_opr
                });
                alert("Invalid data for calculating task duration.");
                return;
            }

            // Update task.end based on No_of_days
            let taskStart = new Date(task.start);
            let newEndDate = new Date(taskStart);
            let workingDaysAdded = 0;
            while (workingDaysAdded < No_of_days) {
                if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, dates)) {
                    workingDaysAdded++;
                }
                newEndDate.setDate(newEndDate.getDate() + 1);
            }
            newEndDate.setDate(newEndDate.getDate() - 1); // Adjust for loop overshoot
            task.end = newEndDate.toISOString().split('T')[0];
            task.duration = No_of_days; // Update duration if your task object uses it
            
            console.log('task planner_qty', task.planner_qty,'', 'task planner opr', task.planner_opr);

            // Calculate day index for positioning
            let dayIndex = 0;
            let currentDate = new Date(gridStartDate);
            while (currentDate < taskStart) {
                if (currentDate.getDay() !== 0 && !isHoliday(currentDate, dates)) {
                    dayIndex++;
                }
                currentDate.setDate(currentDate.getDate() + 1);
            }

            // Calculate effective duration (working days only)
            let effectiveDuration = Math.max(1, No_of_days);

            // Calculate position
            let taskLeft = (dayIndex * cellWidth + 120);
            let taskTop = (task.line * rowHeight + 75 + (rowHeight - 35) / 2);

            // Format OCN
            let displayedOcn = task.ocn.includes('GIL/') || task.ocn.includes('GIL\\')
                ? task.ocn.replace('GIL/', '').replace('GIL\\', '').replace(/^OCN/, '')
                : task.ocn.replace(/^OCN/, '');
            let colorInfo = task.color ? ` (${task.color})` : '';
            let displayInfo = `${displayedOcn || ''} - ${task.item || ''} - ${task.color || ''}`;
            let displayText = displayedOcn + colorInfo;
            let displaynewText = displayInfo;

            // Check shipping date and conflicts
            let shippingDate = task.ship_date;
            let taskData;
            if (!shippingDate) {
                if (typeof microplandata !== 'undefined') {
                    taskData = microplandata.find(item => item.ocn_no === task.ocn);
                }
                if (!taskData && typeof backlogData !== 'undefined') {
                    taskData = backlogData.find(item => item.Ocn?.split('\\').pop() === task.ocn);
                }
                if (taskData) {
                    shippingDate = taskData.FI_Date;
                }
            }

            let barcolor = 'linear-gradient(135deg, #4CAF50, #3e8e41)';
            let hasConflict = false;
            let conflictingTasks = tasks.filter(otherTask => {
                if (otherTask.id === task.id) return false;
                if (otherTask.line !== task.line) return false;
                let otherStart = new Date(otherTask.start);
                let otherEnd = new Date(otherTask.end);
                let taskStart = new Date(task.start);
                let taskEnd = new Date(task.end);
                return (taskStart <= otherEnd && taskEnd >= otherStart);
            });
            hasConflict = conflictingTasks.length > 0;

            if (shippingDate) {
                let shippingDateObj = new Date(shippingDate);
                let taskEndDate = new Date(task.end);
                if (taskEndDate > shippingDateObj) {
                    barcolor = 'linear-gradient(135deg, #ff0000, #cc0000)';
                    hasConflict = true;
                } else if (hasConflict) {
                    barcolor = 'linear-gradient(135deg, #ff9800, #f57c00)';
                }
            } else if (hasConflict) {
                barcolor = 'linear-gradient(135deg, #ff9800, #f57c00)';
            }

            // Remove existing task bar 
            let tooltipPattern = `OCN: ${displayedOcn}, Color: ${task.color}, ItemId: ${task.itemid}, Line: ${lines[task.line]}`;
            console.log(`Removing existing task bar with tooltip pattern: ${tooltipPattern}`);
            let $existingBar = $('.task-bar').filter(function() {
                return $(this).data('tooltip')?.includes(tooltipPattern);
            });
            $existingBar.remove();

            // Create new task bar
            let $bar = $('<div>', {
                class: `task-bar ${hasConflict ? 'line-conflict' : ''}`,
                'data-id': task.id || i,
                'data-task-index': tasks.indexOf(task),
                'data-label': displayText,
                'data-tooltip': `OCN: ${displayedOcn}, Color: ${task.color || 'N/A'}, ItemId: ${task.itemid || 'N/A'}, Line: ${lines[task.line]}, Mch_Cap: ${task.mch_cap}, Start: ${task.start}, End: ${task.end}, Duration: ${effectiveDuration}, Day Cap: ${task.Day_Cap_Per_Line || '--'}, Bal To Sew: ${task.bal_to_sew || '--'}, Days: ${effectiveDuration}`,
                css: {
                    background: barcolor,
                    left: `${taskLeft}px`,
                    top: `${taskTop}px`,
                    width: `${effectiveDuration * cellWidth}px`,
                    height: '35px',
                    position: 'absolute',
                    zIndex: hasConflict ? 2 : 1,
                    borderRadius: '8px',
                    boxShadow: hasConflict ? '0 2px 8px rgba(255, 152, 0, 0.6)' : '0 2px 6px rgba(0,0,0,0.3)',
                    border: hasConflict ? '2px solid #ff5722' : 'none'
                }
            }).append(
                $('<span>', {
                    class: 'task-bar-click',
                    'data-id': task.id || tasks.indexOf(task),
                    html: `<span class="task-bar-prefix">${displaynewText.slice(0,5)}</span>${displaynewText.slice(5)}`,
                    css: {
                        display: 'inline-block',
                        width: '100%',
                        height: '100%',
                        lineHeight: '35px',
                        textAlign: 'center',
                        color: '#fff',
                        fontWeight: hasConflict ? 'bold' : '500',
                        fontSize: '12px',
                        cursor: 'pointer'
                    }
                })
            );

            $taskLayer.append($bar);
            console.log(`Updated task bar for OCN ${ocn_no}:`, { taskLeft, taskTop, width: `${effectiveDuration * cellWidth}px`, end: task.end });

            // Update footer
            let tasksPerColumn = generateTasksPerColumn();
            updateFooterWithTaskCounts(tasksPerColumn);
            updateFooterDetailsRows(selectedUnitCode, dates.map(d => d.Edate));
        }

        // Helper function to check if a date is a holiday
        function isHoliday(date, lineDates) {
        const dateStr = date.toISOString().split('T')[0];
        const hardcodedHolidays = ['2025-08-15', '2025-08-27', '2025-10-01', '2025-10-02', '2025-10-20']; // Add other holidays as needed
        if (hardcodedHolidays.includes(dateStr)) return true;
        const holidays = lineDates ? lineDates.filter(d => d.NH !== null && d.Edate === dateStr).map(d => d.Edate) : [];
        console.log(`Checking holiday for ${dateStr}:`, holidays);
        return holidays.includes(dateStr);
    }

        // Helper function to get dates between two dates
        function getDatesBetween(startDate, endDate) {
            const dates = [];
            let currentDate = new Date(startDate);
            const end = new Date(endDate);
            while (currentDate <= end) {
                dates.push(new Date(currentDate));
                currentDate.setDate(currentDate.getDate() + 1);
            }
            return dates;
        }

        // Helper function to get dates between start and end (inclusive)
        // function getDatesBetween(startDate, endDate) {
        //     const dates = [];
        //     let currentDate = new Date(startDate);
        //     const end = new Date(endDate);

        //     while (currentDate <= end) {
        //         dates.push(currentDate.toISOString().split('T')[0]); // Format as YYYY-MM-DD
        //         currentDate.setDate(currentDate.getDate() + 1);
        //     }

        //     return dates;
        // }
        
        function convertToTasks(detailData) {
            // Clear existing tasks before converting
            clearTasks();
            
            const grouped = {};
            //console.log(detailData);

            let taskstatus = "saved";
          
            detailData.forEach(row => {
                if (!row.ocn_no || !row.line_no || !row.plan_date || !row.ship_date || !row.item_id || !row.color_id) return;
                const lineNo = `L${row.line_no}`; // Match the format of lines (e.g., 'L1')
                const lineIndex = lines.indexOf(lineNo); // Get the index from lines array
                if (lineIndex < 0) return; // Skip if line not found

                // Use ocn_no, line_no, color_id, and item_id in the key
                const key = `${row.ocn_no}_${row.line_no}_${row.color_id}_${row.item_id}`;

                

                if (!grouped[key]) {
                    grouped[key] = {
                        id: key,
                        ocn: row.ocn_no,
                        line: lineIndex,
                        line_no: parseInt(row.line_no),
                        start: row.startdate,
                        end: row.enddate,
                        units: 0,
                        colorid: row.color_id,
                        itemid: row.item_id,
                        color: row.Color,
                        item: row.Item,
                        mch_cap: row.no_mach,
                        no_operators: row.no_opr || 0,
                        bal_to_sew: row.bal_to_sew || row.bal_sew || row.units,
                        planned_qty:row.planned_qty,
                        day_cap_per_line: row.day_cap_per_line || row.Day_Cap_Per_Line || row.planqty,
                        ck_date: row.ck_date,
                        FI_date: row.FI_Date,
                        per_day_qty: row.per_day_qty || row.perdayqty || 0,
                        planner_opr: row.planner_opr || 0,
                        taskstatus: taskstatus,
                        planner_qty: row.planner_qty || 0,
                        buyer:row.Buyer,
                        detail_id: row.detail_id || null,
                        Isdragg : 0,
                    };
                }
                // Update start to earliest date and end to latest date
                grouped[key].start = grouped[key].start < row.startdate ? grouped[key].start : row.startdate;
                grouped[key].end = grouped[key].end > row.enddate ? grouped[key].end : row.enddate;
                grouped[key].units = parseInt(row.planned_qty || 0);
            });

            // Convert grouped object to array of tasks
            const tasks = Object.values(grouped);
            console.log('Grouped Tasks:', tasks);

            const convertedTasks = Object.values(grouped).map(group => {
                const startDate = new Date(group.start);
                const endDate = new Date(group.end);
                if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) return null;

                const duration = Math.max(1, Math.round((endDate - startDate) / (1000 * 3600 * 24)) + 1);
                return {
                    id: group.id,
                    ocn: group.ocn,
                    line: group.line,
                    line_no: group.line_no,
                    start: startDate.toISOString().split('T')[0],
                    end: endDate.toISOString().split('T')[0],
                    duration: duration,
                    units: group.units,
                    colorid: group.colorid,
                    color: group.color,
                    item: group.item,
                    itemid: group.itemid,
                    mch_cap: group.mch_cap,
                    no_operators: group.no_operators,
                    bal_to_sew: group.bal_to_sew,
                    planned_qty: group.planned_qty,
                    day_cap_per_line: group.day_cap_per_line,
                    ck_date: group.ck_date,
                    FI_date: group.FI_date,
                    planner_opr: group.planner_opr,
                    taskstatus: group.taskstatus,
                    planner_qty: group.planner_qty,
                    per_day_qty: group.per_day_qty,
                    buyer: group.buyer,
                    detail_id: group.detail_id,
                    Isdragg : group.Isdragg,
                };
            }).filter(Boolean); // Filter out nulls

            // Add tasks safely with deduplication
            convertedTasks.forEach(task => {
                addTaskSafely(task);
            });

            console.log(`🔄 Converted ${convertedTasks.length} tasks:`, convertedTasks.map(t => ({
                id: t.id,
                ocn: t.ocn,
                itemid: t.itemid,
                colorid: t.colorid,
                line_no: t.line_no,
                line: t.line
            })));
        }


        function initializeGanttApp() {
            initializeFlatpickr();
            setupEventListeners();
            populateFactoryDropdown();
            //populatePOBacklog();
            // Initial render with dummy data if API is slow or fails
            const dummyLineDates = [];
            const defaultStart = new Date('2025-06-23');
            for (let d = 0; d < 31; d++) {
                const date = new Date(defaultStart);
                date.setDate(defaultStart.getDate() + d);
                dummyLineDates.push({
                    Edate: date.toISOString().split('T')[0],
                    WeekNumber: Math.ceil((date.getDate() + date.getDay()) / 7),
                    NH: null
                });
            }
            generateGanttChart(dummyLineDates); // Initial render
        }


        function getDatesBetween(startDate, endDate) {
            const dates = [];
            let currentDate = new Date(startDate);
            const end = new Date(endDate);

            while (currentDate <= end) {
                if (currentDate.getDay() !== 0 && !isHoliday(currentDate, globalLineDates)) {
                    dates.push(currentDate.toISOString().split('T')[0]); // Format as YYYY-MM-DD
                }
                currentDate.setDate(currentDate.getDate() + 1);
            }

            console.log(`Dates between ${startDate} and ${endDate} (excluding Sundays/Holidays):`, dates);
            return dates;
        }

function handleTaskbarMouseDown(e) {
    if ($(e.target).hasClass('handle')) return;
    const $bar = $(this);
    const taskId = $bar.data('id');
    const taskIndex = $bar.data('task-index');

    // Find task by ID or index
    let task = tasks.find(t => t.id === taskId);
    if (!task && taskIndex !== undefined) {
        task = tasks[taskIndex];
    }

    if (!task) {
        console.error('Task not found for ID:', taskId, 'Index:', taskIndex, 'Tasks:', tasks.map(t => ({
            id: t.id,
            ocn: t.ocn,
            itemid: t.itemid,
            colorid: t.colorid,
            line_no: t.line_no,
            line: t.line,
            start: t.start,
            end: t.end
        })));
        alert('Task not found. Please try again.');
        return;
    }

    // Validate task properties
    if (!task.start || !task.end || isNaN(new Date(task.start)) || isNaN(new Date(task.end))) {
        console.error('Invalid task dates:', { taskId, start: task.start, end: task.end });
        alert('Task has invalid start or end dates.');
        return;
    }

    // Calculate duration in working days
    const originalWorkingDays = [];
    let current = new Date(task.start);
    const end = new Date(task.end);
    while (current <= end) {
        if (current.getDay() !== 0 && !isHoliday(current, globalLineDates)) {
            originalWorkingDays.push(current.toISOString().split('T')[0]);
        }
        current.setDate(current.getDate() + 1);
    }
    const durationInWorkingDays = originalWorkingDays.length;

    if (durationInWorkingDays < 0) {
        console.error('Invalid task duration:', { taskId, start: task.start, end: task.end, durationInWorkingDays });
        alert('Task has invalid duration.');
        return;
    }

    // Store original position and properties
    const originalLeft = parseInt($bar.css("left")) || 0;
    const originalTop = parseInt($bar.css("top")) || 0;
    const originalLine = task.line;
    const originalStart = task.start;
    const originalEnd = task.end;

    // Set selection variables
    selectedOCN = task.ocn;
    selectedItemId = String(task.itemid);
    selectedColorId = String(task.colorid);
    selectedLineNo = task.line_no ? `L${task.line_no}` : (lines[task.line] || 'Unknown');
    selectedOrderData = task;

    const startX = e.pageX, startY = e.pageY;
    let dragged = false;

    $(document).on('mousemove.drag', function(ev) {
        dragged = true;
        $bar.css({ left: originalLeft + (ev.pageX - startX), top: originalTop + (ev.pageY - startY) });
    });

    $(document).on('mouseup.drag', function(ev) {
        $(document).off('.drag');
        if (!dragged) {
            console.log('No drag detected, keeping task in place:', { taskId, ocn: task.ocn });
            return;
        }

        // Ensure Gantt chart is initialized
        if ($('#gantt-header').find('th.date-header').length === 0 && globalLineDates.length > 0) {
            console.warn('Gantt chart headers missing, reinitializing.');
            generateGanttChart(globalLineDates);
        }

        // Find drop target
        $bar.hide();
        const elementUnder = document.elementFromPoint(ev.clientX, ev.clientY);
        $bar.show();

        const $row = $(elementUnder).closest('tr[data-line]');
        const $cell = $(elementUnder).closest('td[data-day]');

        let newLine = originalLine;
        let dayIndex = 0;

        if ($row.length > 0) {
            newLine = $row.data('line');
        } else {
            console.warn('Dropped outside valid row, reverting to original position:', { taskId, ocn: task.ocn });
            $bar.css({ left: originalLeft, top: originalTop });
            return;
        }

        if ($cell.length > 0) {
            dayIndex = $cell.data('day');
        } else {
            const left = parseInt($bar.css("left"));
            dayIndex = Math.max(0, Math.round((left - 60) / cellWidth)); // Use round for pixel-perfect snapping
        }

        // Validate dayIndex
        if (!globalLineDates[dayIndex]) {
            console.warn('Invalid day index:', dayIndex, 'Reverting to original position:', { taskId, ocn: task.ocn });
            $bar.css({ left: originalLeft, top: originalTop });
            return;
        }

        // Get new start date from header cell (original logic)
        const $headerCells = $('#gantt-header').find('th.date-header');
        let newStartDate;
        if ($headerCells.length > 0) {
            const $headerCell = $headerCells.eq(dayIndex);
            const cellDateStr = $headerCell.data('date');
            if (cellDateStr) {
                newStartDate = new Date(cellDateStr);
            } else {
                newStartDate = new Date(globalLineDates[dayIndex]?.Edate || originalStart);
            }
        } else {
            newStartDate = new Date(globalLineDates[dayIndex]?.Edate || originalStart);
        }

        if (isNaN(newStartDate)) {
            console.warn('Invalid new start date, reverting to original position:', originalStart);
            $bar.css({ left: originalLeft, top: originalTop });
            return;
        }

        // Adjust start date to skip Sundays and holidays
        while (newStartDate.getDay() === 0 || isHoliday(newStartDate, globalLineDates)) {
            newStartDate.setDate(newStartDate.getDate() + 1);
        }

        // Calculate new end date
        let newEndDate = new Date(newStartDate);
        let workingDaysCount = 1;
        while (workingDaysCount < durationInWorkingDays) {
            newEndDate.setDate(newEndDate.getDate() + 1);
            if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
                workingDaysCount++;
            }
        }

        // Check for conflicts
        const conflictingTasks = tasks.filter(otherTask => {
            if (otherTask.id === task.id) return false;
            if (otherTask.line !== newLine) return false;
            if (!otherTask.start || !otherTask.end) {
                console.warn('Skipping task with invalid dates:', otherTask);
                return false;
            }
            const otherStart = new Date(otherTask.start);
            const otherEnd = new Date(otherTask.end);
            if (isNaN(otherStart) || isNaN(otherEnd)) {
                console.warn('Invalid dates in conflicting task:', otherTask);
                return false;
            }
            return (newStartDate <= otherEnd && newEndDate >= otherStart);
        });

        // Log tasks before change
        console.log('Before drag - tasks:', tasks.map(t => ({
            id: t.id,
            ocn: t.ocn,
            itemId: t.itemid,
            colorId: t.colorid,
            line: t.line,
            start: t.start,
            end: t.end
        })));

        // Revert on conflict
        if (conflictingTasks.length > 0) {
            console.log('Conflicts detected, reverting to original position:', conflictingTasks.map(t => ({
                id: t.id,
                ocn: t.ocn,
                itemId: t.itemid,
                colorId: t.colorid,
                start: t.start,
                end: t.end
            })));
            $bar.css({ left: originalLeft, top: originalTop });
            return;
        }

        // Validate new dates
        if (newStartDate > newEndDate) {
            console.error('Invalid date range:', { newStartDate, newEndDate });
            $bar.css({ left: originalLeft, top: originalTop });
            return;
        }

        // Update task
        task.start = newStartDate.toISOString().split('T')[0];
        task.end = newEndDate.toISOString().split('T')[0];
        task.line = newLine;

        // Log for debugging
        console.log(`Task ${task.ocn} moved to Line: ${lines[newLine]}, Start: ${task.start}, End: ${task.end}, Duration: ${durationInWorkingDays} working days`);
        console.log(`Old Date Range: ${getDatesBetween(originalStart, originalEnd)}`);
        console.log(`New Date Range: ${getDatesBetween(task.start, task.end)}`);
        console.log('After drag - tasks:', tasks.map(t => ({
            id: t.id,
            ocn: t.ocn,
            itemId: t.itemid,
            colorId: t.colorid,
            line: t.line,
            start: t.start,
            end: t.end
        })));

        task.Isdragg = 1; // Mark task as dragged

        console.log('tasks isdragging', task.Isdragg);

        // Re-render tasks
        renderTasks(globalLineDates);

    });
    $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
}

        // function handleResizeHandleMouseDown(e) {
        //     e.stopPropagation();
        //     const $bar = $(this).closest('.task-bar');
        //     const taskId = $bar.data('id');
        //     const taskIndex = $bar.data('task-index');
            
        //     // Find task by ID or index
        //     let task = tasks.find(t => t.id === taskId);
        //     if (!task && taskIndex !== undefined) {
        //         task = tasks[taskIndex];
        //     }
            
        //     if (!task) {
        //         console.error('Task not found for resize, ID:', taskId, 'Index:', taskIndex);
        //         return;
        //     }
            
        //     const isLeft = $(this).hasClass('left');
        //     const startX = e.pageX;
        //     const startWidth = parseInt($bar.css("width")), startLeft = parseInt($bar.css("left"));
        //     const originalStart = task.start;
        //     const originalEnd = task.end;
        //     const originalDuration = task.duration;

        //     $(document).on('mousemove.resize', function(ev) {
        //         const dx = ev.pageX - startX;
        //         const newWidth = Math.max(cellWidth, isLeft ? startWidth - dx : startWidth + dx);
        //         const newLeft = isLeft ? startLeft + dx : startLeft;
        //         $bar.css({ width: newWidth + 'px', left: newLeft + 'px' });
        //     });

        //     $(document).on('mouseup.resize', function() {
        //         $(document).off('.resize');
        //         const finalWidth = parseInt($bar.css("width"));
        //         const finalLeft = parseInt($bar.css("left"));
                
        //         // Calculate effective dayIndex based on header cells
        //         const $headerCells = $('#gantt-header').find('th.date-header');
        //         let effectiveDayIndex = 0; // Default to first cell
        //         let cumulativeWidth = 60; // Starting offset for the sticky column

        //         if ($headerCells.length === 0) {
        //             console.error('No header cells found. Gantt chart may not be initialized.');
        //             alert('Error: Gantt chart is not properly initialized. Please refresh the page.');
        //             return;
        //         }

        //         if (finalLeft < cumulativeWidth) {
        //             effectiveDayIndex = 0;
        //         } else {
        //             let found = false;
        //             $headerCells.each(function(index) {
        //                 const $cell = $(this);
        //                 const cellWidthActual = $cell.outerWidth() || cellWidth;
        //                 cumulativeWidth += cellWidthActual;
        //                 if (cumulativeWidth > finalLeft) {
        //                     effectiveDayIndex = index;
        //                     found = true;
        //                     return false;
        //                 }
        //             });
        //             if (!found && $headerCells.length > 0) {
        //                 effectiveDayIndex = $headerCells.length - 1;
        //             }
        //             effectiveDayIndex = Math.max(0, Math.min(effectiveDayIndex, $headerCells.length - 1));
        //         }

        //         const $headerCell = $headerCells.eq(effectiveDayIndex);
        //         const cellDateStr = $headerCell.data('date');
        //         if (!cellDateStr) {
        //             console.error('No date found in header cell for effectiveDayIndex:', effectiveDayIndex);
        //             return;
        //         }

        //         const newDuration = Math.max(1, Math.floor(finalWidth / cellWidth));
        //         let newStartDate = isLeft ? new Date(cellDateStr) : new Date(task.start);

        //         // Adjust start date to skip Sundays and holidays
        //         while (newStartDate.getDay() === 0 || isHoliday(newStartDate, globalLineDates)) {
        //             newStartDate.setDate(newStartDate.getDate() + 1);
        //         }

        //         let newEndDate = new Date(newStartDate);
        //         let remainingDays = newDuration - 1;
        //         while (remainingDays > 0) {
        //             newEndDate.setDate(newEndDate.getDate() + 1);
        //             if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
        //                 remainingDays--;
        //             }
        //         }

        //         // Log date ranges as arrays, excluding Sundays and holidays
        //         const oldDateRange = getDatesBetween(originalStart, originalEnd);
        //         const newDateRange = getDatesBetween(newStartDate.toISOString().split('T')[0], newEndDate.toISOString().split('T')[0]);
        //         console.log(`Resize Task ${task.ocn}: Old Dates=${JSON.stringify(oldDateRange)}, New Dates=${JSON.stringify(newDateRange)}`);

        //         // Update task
        //         task.start = newStartDate.toISOString().split('T')[0];
        //         task.end = newEndDate.toISOString().split('T')[0];
        //         task.duration = newDuration;

        //         renderTasks(globalLineDates); // Use globalLineDates
        //     });
        // }

        function detectConflicts() {
            const conflicts = [];
            for (let i = 0; i < tasks.length; i++) {
                for (let j = i + 1; j < tasks.length; j++) {
                    const tA = tasks[i], tB = tasks[j];
                    if (tA.line !== tB.line) continue;
                    const startA = new Date(tA.start), endA = new Date(tA.end);
                    const startB = new Date(tB.start), endB = new Date(tB.end);
                    if (startA <= endB && startB <= endA) {
                        conflicts.push([i, j]);
                    }
                }
            }
            return conflicts;
        }

         // --- SPLIT ORDER SIDEBAR ---
         function openSplitSidebar() {
            if (!activeTaskId) {
                alert("Please select a task to split.");
                return;
            }

            const taskToSplit = tasks.find(t => t.id === activeTaskId);

            if (!taskToSplit) {
                console.error("No task found in tasks array for ID:", activeTaskId);
                alert("Cannot split: Selected task not found.");
                return;
            }

            console.log("🔍 Opening split sidebar for Task ID:", activeTaskId, "Task Data:", taskToSplit);

            const unitCount = parseInt(taskToSplit.units || 0);
            if (unitCount <= 0) {
                console.error("Invalid unit count for splitting:", unitCount);
                alert("Cannot split: No units available to split.");
                return;
            }
            
            const approx = Math.floor(unitCount / (currentParts > 1 ? currentParts : 2));
            currentParts = 1; // Reset currentParts to 1
            const sidebar = $("#splitOrderSidebar");
            sidebar.find("h6").text(`Split Order: ${taskToSplit.ocn}`);
            sidebar.find("small").html(`Total Units: ${unitCount}`);
            
            // Store the task ID and unit count on the sidebar element
            sidebar.data('task-id-to-split', activeTaskId);
            sidebar.data('total-units', unitCount);
            sidebar.addClass("active");
            $('#numPartsInput').val(currentParts); // Reset numPartsInput

            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
            renderLineSelectors();
        }

        function closeSplitSidebar() {
          $('#splitOrderSidebar').removeClass('active');
          $('#lineSelectorsContainer').empty();
          $('#numPartsInput').val(1); // Reset numPartsInput on close
         currentParts = 1; // Reset currentParts
        }

        function increaseParts() {
            if (currentParts < lines.length) {
                currentParts++;
                $('#numPartsInput').val(currentParts);
                updateSplitSidebarText();
                renderLineSelectors();
            }
        }

        function decreaseParts() {
            if (currentParts > 1) {
                currentParts--;
                $('#numPartsInput').val(currentParts);
                updateSplitSidebarText();
                renderLineSelectors();
            }
        }

        function updateSplitSidebarText() {
            const sidebar = $("#splitOrderSidebar");
            const totalUnits = sidebar.data('total-units') || 0;
            const ocn = sidebar.find("h6").text().replace('Split Order: ', '');
            
            if (totalUnits > 0 && currentParts > 0) {
                const approx = Math.floor(totalUnits / currentParts);
                sidebar.find("small").html(`Total Units: ${totalUnits}`);
            }
        }

        function renderLineSelectors() {
            const sidebar = $("#splitOrderSidebar");
            const totalUnits = Number(sidebar.data('total-units')) || 0;
            const container = $('#lineSelectorsContainer').empty();
            let approx = Math.floor(totalUnits / currentParts);
            let values = [];

            // Distribute approx values, last gets the remainder
            for (let i = 1; i <= currentParts; i++) {
                if (i < currentParts) {
                    values.push(approx);
                } else {
                    values.push(totalUnits - approx * (currentParts - 1));
                }
            }

            for (let i = 1; i <= currentParts; i++) {
                container.append(`
                    <div class="mb-2 d-flex align-items-center" style="gap:8px;">
                        <label class="me-1 mb-0 ">Part ${i} Line</label>
                        <select class="form-select mb-1 part-line-${i}" style="max-width:100px;display:inline-block;" onchange="let selected = $(this).val(); $('.form-select').not(this).find('option').each(function(){ if($(this).val() === selected) $(this).prop('disabled', true); else $(this).prop('disabled', false); });">
                            <option>Select line for Part ${i}</option>
                            ${lines.map(line => `<option value="${line}">${line}</option>`).join('')}
                        </select>
                        <label class="me-1 mb-0">QTY:</label>
                        <input type="number" min="1" class="form-control split-bal-input" id="split-bal-${i}" value="${values[i-1]}" data-index="${i-1}" style="max-width:120px;display:inline-block; margin-bottom: 4px;" oninput="if(this.value<1)this.value=0;">
                    </div>
                `);
            }

            $('.split-bal-input').on('input', function() {
                let idx = Number($(this).data('index'));
                let vals = $('.split-bal-input').map(function(){ return Number($(this).val()) || 0; }).get();
                let sum = vals.reduce((a,b) => a+b, 0);
                let diff = sum - totalUnits;

                if (diff !== 0) {
                    let nextIdx = idx === currentParts - 1 ? 0 : idx + 1; // If last input, adjust first; otherwise, adjust next
                    let nextInput = $(`#split-bal-${nextIdx + 1}`);
                    let nextVal = Number(nextInput.val()) || 0;
                    let newNextVal = nextVal - diff; // Adjust the next (or first) input to balance the total
                    if (newNextVal < 1) newNextVal = 1;
                    nextInput.val(newNextVal);

                    // Recalculate to ensure total matches
                    let vals2 = $('.split-bal-input').map(function(){ return Number($(this).val()) || 0; }).get();
                    let sum2 = vals2.reduce((a,b) => a+b, 0);
                    let finalDiff = sum2 - totalUnits;
                    if (finalDiff !== 0) {
                        // Adjust the next input again if needed to make total exact
                        let finalAdjustVal = Number(nextInput.val()) - finalDiff;
                        if (finalAdjustVal < 1) finalAdjustVal = 1;
                        nextInput.val(finalAdjustVal);
                    }
                }
            });
        }

        // Initialize Flatpickr for the start date input
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr("#taskStartDate", {
                dateFormat: "Y-m-d",
                minDate: new Date().toISOString().split('T')[0], // Prevent selecting dates before today
                defaultDate: new Date().toISOString().split('T')[0], // Default to today
                disable: [
                    function(date) {
                        // Disable Sundays (where getDay() === 0)
                        // Disable national holidays
                        return date.getDay() === 0 || nationalHolidays.includes(date.toISOString().split('T')[0]);
                    }
                ]
            });
        });

        // Function to populate line number dropdown
        function populateLineDropdown() {
            const $lineSelect = $('#taskLineNo').empty();
            lines.forEach((line, index) => {
                $lineSelect.append(`<option value="${index}">${line}</option>`);
            });
        }

        // Function to open the task update modal
        function openTaskUpdateModal(task, taskId) {
            // Populate line dropdown
            populateLineDropdown();
            
            // Set default values
            $('#taskStartDate').val(task.start);
            $('#taskLineNo').val(task.line);
            
            // Store taskId for reference
            $('#taskUpdateModal').data('taskId', taskId);
            
            // Show modal
            $('#taskUpdateModal').modal('show');
        }

        // Function to update task and re-render
        function updateTaskAndRender(taskId, newStartDate, newLineIndex) {
            const task = tasks.find(t => t.id === taskId);
            if (!task) {
                console.error("Task not found for ID:", taskId);
                alert("Error: Task not found.");
                return;
            }

            // Calculate duration to preserve task length
            const oldStart = new Date(task.start);
            const oldEnd = new Date(task.end);
            const durationMs = oldEnd - oldStart;
            const newStart = new Date(newStartDate);
            const newEnd = new Date(newStart.getTime() + durationMs);

            // Update task properties
            task.start = newStartDate;
            task.end = newEnd.toISOString().split('T')[0];
            task.line = parseInt(newLineIndex);

            // Check for conflicts after updating
            const conflictingTasks = tasks.filter(otherTask => {
                if (otherTask.id === task.id) return false;
                if (otherTask.line !== task.line) return false;
                const otherStart = new Date(otherTask.start);
                const otherEnd = new Date(otherTask.end);
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                return (taskStart <= otherEnd && taskEnd >= otherStart);
            });
            task.hasConflict = conflictingTasks.length > 0;

            // Re-render tasks
            renderTasks();
        }

        function handleGanttAreaClick(e) {
            const bar = e.target.closest('.task-bar');
            if (bar && bar.dataset) {
                const label = bar.dataset.label.trim();
                const taskId = bar.dataset.id;
                activeTaskId = taskId; // Use the unique ID of the task
                const taskIndex = parseInt(bar.dataset.taskIndex);
                
                // Find task by ID or index
                let task = tasks.find(t => t.id === taskId);
                if (!task && taskIndex !== undefined && !isNaN(taskIndex)) {
                    task = tasks[taskIndex];
                }
                
                if (!task || task.line == null || task.line < 0 || task.line >= lines.length) {
                    console.error("Invalid task or line index:", task, "Task ID:", taskId, "Task Index:", taskIndex, "Lines:", lines);
                    alert("Cannot select task: Invalid line or task data.");
                    return;
                }

                // Check for conflicts
                const conflictingTasks = tasks.filter(otherTask => {
                    if (otherTask.id === task.id) return false;
                    if (otherTask.line !== task.line) return false;
                    
                    const otherStart = new Date(otherTask.start);
                    const otherEnd = new Date(otherTask.end);
                    const taskStart = new Date(task.start);
                    const taskEnd = new Date(task.end);
                    
                    return (taskStart <= otherEnd && taskEnd >= otherStart);
                });
                
                task.hasConflict = conflictingTasks.length > 0;

                // Handle task click with conflict detection
                handleTaskClick(task);

                // Extract OCN from label (remove color info)
                let selectedText = label;
                selectedOCN = selectedText.match(/\d+/)[0];
                selectedItemId = task.itemid;
                selectedColorId = task.colorid;

                selectedLineNo = lines[task.line];
                if (!selectedLineNo) {
                    console.error("Failed to set selectedLineNo. Lines:", lines, "Task Line:", task.line);
                    alert("Cannot select task: Line not found.");
                    return;
                }

                const backlogItem = backlogData.find(item => item.Ocn.split('\\').pop() === selectedOCN);
                // Try to find order data in microplandata, backlogData, or use task as fallback
                selectedOrderData = microplandata.find(item => item.ocn_no === selectedOCN && item.item_id === selectedItemId && item.color_id === selectedColorId) || 
                                    backlogData.find(item => {
                                        const ocnMatch = item.Ocn.split('\\').pop() === selectedOCN;
                                        const itemMatch = item.Itemid === selectedItemId;
                                        const colorMatch = item.Colorid === selectedColorId;
                                        return ocnMatch && itemMatch && colorMatch;
                                    }) || 
                                    task; // Fallback to task data

                if (!selectedOrderData) {
                    console.error("No order data found for OCN:", selectedOCN, "Item ID:", selectedItemId, "Color ID:", selectedColorId, "Task:", task);
                    alert("Cannot select task: Order data not found.");
                    return;
                }

                console.log("✅ Taskbar clicked:", {
                    OCN: selectedOCN,
                    ItemID: selectedItemId,
                    ColorID: selectedColorId,
                    Line: selectedLineNo,
                    Task: task,
                    OrderData: selectedOrderData,
                    Conflict: task.hasConflict
                });

                // Open the task update modal
                openTaskUpdateModal(task, taskId);

                $.ajax({
                    url: '/ordersummary',
                    method: 'GET',
                    data: { orderno: selectedOCN ,itemid : task.itemid, colorid: task.colorid},
                    success: function(response) {
                        console.log("Order Summary Response:", response);
                        if (response && response.data && response.data.data && Array.isArray(response.data.data) && response.data.data.length > 0) {
                            showOrderDetails(selectedOCN, response.data.data[0], task.mch_cap, lines[task.line],task.units, task.planner_opr, task.planner_qty, task.taskstatus, task.detail_id);
                        } else {
                            console.warn("No valid details in response, using fallback data:", response);
                            showOrderDetails(selectedOCN, selectedOrderData, task.mch_cap, lines[task.line],task.units, task.planner_opr, task.planner_qty, task.taskstatus, task.detail_id);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("Failed to fetch order summary:", status, error, xhr.responseText);
                        alert("Error loading order summary. Using fallback data.");
                        showOrderDetails(selectedOCN, selectedOrderData, task.mch_cap, lines[task.line],task.units, task.planner_opr, task.planner_qty, task.taskstatus, task.detail_id);
                    }
                });
            }
        }

        // Handle confirm button click in the modal
        $('#confirmTaskUpdate').on('click', function() {
            const taskId = $('#taskUpdateModal').data('taskId');
            const newStartDate = $('#taskStartDate').val();
            const newLineIndex = $('#taskLineNo').val();

            if (!newStartDate || newLineIndex === undefined) {
                alert("Please provide both a start date and a line number.");
                return;
            }

            updateTaskAndRender(taskId, newStartDate, newLineIndex);
            $('#taskUpdateModal').modal('hide');
        });

        function findNextAvailableDate(lineIndex, originalStartDate, duration, globalLineDates) {
            const start = new Date(originalStartDate);
            let newStartDate = new Date(start);
            let newEndDate = new Date(start);
            
            // Calculate end date for the original start date
            let workingDays = 1;
            while (workingDays < duration) {
                newEndDate.setDate(newEndDate.getDate() + 1);
                if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
                    workingDays++;
                }
            }

            // Check if original start date is available (no conflicts)
            const hasConflict = tasks.some(task => {
                if (task.line !== lineIndex) return false;
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                return (newStartDate <= taskEnd && newEndDate >= taskStart);
            });

            if (!hasConflict) {
                return newStartDate; // Use original start date if no conflict
            }

            // If conflict exists, find the latest end date for tasks on the specified line
            const tasksOnLine = tasks.filter(t => t.line === lineIndex);
            if (tasksOnLine.length === 0) {
                return newStartDate; // No tasks on the line, use original start date
            }

            const latestEndDate = new Date(Math.max(...tasksOnLine.map(t => new Date(t.end))));
            newStartDate = new Date(latestEndDate);
            newStartDate.setDate(newStartDate.getDate() + 1); // Start the next day after the latest end date

            // Ensure the new start date is not a Sunday or holiday
            while (newStartDate.getDay() === 0 || isHoliday(newStartDate, globalLineDates)) {
                newStartDate.setDate(newStartDate.getDate() + 1);
            }

            return newStartDate;
        }


        function handleSplitConfirm() {
            const taskIdToSplit = $('#splitOrderSidebar').data('task-id-to-split');
            if (!taskIdToSplit) {
                alert("Could not identify the task to split. Please re-select and try again.");
                return;
            }

            const numParts = currentParts;
            const partLines = [];
            for (let i = 1; i <= numParts; i++) {
                const selectedLine = $(`.part-line-${i}`).val();
                if (!selectedLine || !selectedLine.startsWith('L')) {
                    alert(`Please select a valid line for Part ${i}`);
                    return;
                }
                partLines.push(selectedLine);
            }

            // Collect split quantities
            const balToSewParts = [];
            for (let i = 1; i <= numParts; i++) {
                const balVal = parseInt($(`#split-bal-${i}`).val(), 10) || 0;
                balToSewParts.push(balVal);
            }

            // Find task by its ID
            const taskIndex = tasks.findIndex(t => t.id === taskIdToSplit);
            if (taskIndex === -1) {
                console.error("No task found for ID:", taskIdToSplit);
                alert("An error occurred. The task to be split could not be found.");
                return;
            }

            const originalTask = { ...tasks[taskIndex] }; // Make a copy

            console.log('orginal task raj' , originalTask);
            tasks.splice(taskIndex, 1); // Remove the original task

            for (let i = 0; i < numParts; i++) {
                const line = partLines[i];
                const newLineIndex = lines.indexOf(line);
                if (newLineIndex === -1) continue;

                const splitUnits = balToSewParts[i];
                let planqty  = 0;
                if(originalTask.planner_qty != 0){
                     planqty = (originalTask.planner_qty && originalTask.planner_qty > 1) ? originalTask.planner_qty :  originalTask.planner_qty;


                }else{
                     planqty = (originalTask.planqty && originalTask.planqty > 1) ? originalTask.planqty :  originalTask.per_day_qty;
                }
                console.log(originalTask.planner_qty);
                console.log(planqty);
               // const planqty = (originalTask.planqty && originalTask.planqty > 1) ? originalTask.planqty :  originalTask.per_day_qty;
                const daysRequired = Math.max(1, Math.ceil(splitUnits / planqty));

                // Find the next available start date for the selected line
                const newStartDate = findNextAvailableDate(newLineIndex, originalTask.start, daysRequired, globalLineDates);

                // Calculate end date for this split (skipping Sundays/holidays)
                let newEndDate = new Date(newStartDate);
                let workingDays = 1;
                while (workingDays < daysRequired) {
                    newEndDate.setDate(newEndDate.getDate() + 1);
                    if (newEndDate.getDay() !== 0 && !isHoliday(newEndDate, globalLineDates)) {
                        workingDays++;
                    }
                }

                const splitTask = {
                    ...originalTask,
                    id: `task_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    parent_ocn: originalTask.ocn,
                    split_part: i + 1,
                    is_split: true,
                    line: newLineIndex,
                    start: newStartDate.toISOString().split('T')[0],
                    end: newEndDate.toISOString().split('T')[0],
                    units: splitUnits,
                    duration: daysRequired,
                    mch_cap: originalTask.mch_cap || 0,
                    no_operators: originalTask.no_operators || 0,
                    splitunits: splitUnits,
                };

                addTaskSafely(splitTask);
            }

            closeSplitSidebar();
            renderTasks(globalLineDates);
        }


        // --- UI & DETAIL DISPLAY ---
        function showOrderDetails(ocn_no, detailsData, machine_capacity, lineno, plannedlineqty, planner_opr, planner_qty, taskstatus, detail_id) {
            if (!detailsData) {
                console.error("No details data provided for OCN:", ocn_no);
                alert("Order details not found!");
                return;
            }
            
            console.log("taskssss", tasks);

            let taskk = tasks.find(t => 
                String(t.ocn.match(/\d+/)[0]) === String(ocn_no) && 
                String(t.itemid) === String(detailsData.Itemid) && 
                String(t.colorid) === String(detailsData.Colorid)
            );
            if (!taskk) {
                console.error("No task found for OCN:", ocn_no, "Item ID:", detailsData.Itemid, "Color ID:", detailsData.Colorid, "detailsData:", detailsData);
                alert("Order details not found for the selected task.");
                return;
            }
            // Log taskk details for debugging
            console.log("taskk", { id: taskk.id, taskstatus: taskk.taskstatus });
            
                  
            // const bar = e.target.closest('.task-bar');

            // if (bar && bar.dataset) {
            //     const label = bar.dataset.label.trim();
            //     const taskId = bar.dataset.id;
            //     activeTaskId = taskId; // Use the unique ID of the task
            //     const taskIndex = parseInt(bar.dataset.taskIndex);
            
            //     // Find task by ID or index
            //     let task = tasks.find(t => t.id === taskId);
            //     console.log ("selected task status", task.taskstatus);
            // }
            if (taskk.taskstatus === 'saved') {
                    $('#resetDetailsBtn').addClass('d-none'); // Hide reset button if taskstatus is 'saved'
                    $('#deleteBtn').removeClass('d-none'); // Show delete button
                } else {
                    $('#resetDetailsBtn').removeClass('d-none'); // Show reset button if taskstatus is not 'saved'
                    $('#deleteBtn').addClass('d-none'); // Hide delete button
                }

                $('#tailor_qty_display').addClass('d-none');
                $('#order-details-default').addClass('d-none');
                const detailsDiv = $('#order-details-dynamic').removeClass('d-none');
                
                $('#splitOrderBtn').removeClass('d-none');
                $('#showDetailsBtn').removeClass('d-none');
                let mac_cap = detailsData.No_Of_Mch + " / " + detailsData.No_Of_Opr;

            // Map data strictly from /ordersummary API response
            const mappedData = {
                ocn_no: detailsData.Order_No ? detailsData.Order_No.split('\\').pop() : ocn_no,
                item_name: detailsData.Item || '--',
                buyer: detailsData.Buyer || '--',
                color: detailsData.Color || '--',
                itemid: detailsData.Itemid || '--',
                colorid: detailsData.Colorid || '--',
                ck_date: formatDate(detailsData.Ck_Date),
                inspection_date: formatDate(detailsData.FI_Date),
                shipping_date: formatDate(detailsData.Ship_Date),
                bom_qty: detailsData.Bom_Qty || '--',
                prod_qty: detailsData.Sew_Qty || '--',
                FI_date: formatDate(detailsData.FI_Date),
                planned_qty: detailsData.Order_Qty || '--',
                balance_to_sew: detailsData.Bal_TO_Sew || '--',
                balance_minutes: detailsData.Bal_To_Sew_Mins || '--',
                sam: detailsData.Sam || '--',
                machines: mac_cap || '--',
                efficiency: detailsData.efficiency || '--',
                special: detailsData.Spl_Process || '--',
                sizes: detailsData.sizes || '--',
                raw_days: detailsData.raw_days || '--',
                planned_lineqty: (plannedlineqty > detailsData.Bal_TO_Sew) ? detailsData.Bal_TO_Sew : plannedlineqty || '--',
                per_day_qty: (planner_qty != 0)  ?  planner_qty  : detailsData.Per_Day_Qty,
                Per_Day_Qty: detailsData.Per_Day_Qty || '--',
                no_operators: detailsData.No_Of_Opr || '--',
                planner_opr: planner_opr,
                taskstatus: taskstatus,
                detail_id: "detail_id",
            };

            // Explicitly update each field to ensure all are set with truncation and tooltip
            detailsDiv.find('#planned_tailor_qty_display').text('');
            detailsDiv.find('#dynamic-ocn-heading').text(`${mappedData.ocn_no} - in ${lineno}- Details`);
            detailsDiv.find('#item_name').text(mappedData.item_name.length > 13 ? mappedData.item_name.slice(0, 13) + "..." : mappedData.item_name).attr('title', mappedData.item_name);
            detailsDiv.find('#buyer').text(mappedData.buyer.length > 13 ? mappedData.buyer.slice(0, 13) + "..." : mappedData.buyer).attr('title', mappedData.buyer);
            detailsDiv.find('#color').text(mappedData.color.length > 13 ? mappedData.color.slice(0, 13) + "..." : mappedData.color).attr('title', mappedData.color);
            detailsDiv.find('#ck_date').text(mappedData.ck_date.length > 13 ? mappedData.ck_date.slice(0, 13) + "..." : mappedData.ck_date).attr('title', mappedData.ck_date);
            // detailsDiv.find('#inspection_date').text(mappedData.inspection_date.length > 13 ? mappedData.inspection_date.slice(0, 13) + "..." : mappedData.inspection_date).attr('title', mappedData.inspection_date);
            detailsDiv.find('#bom_qty').text(mappedData.bom_qty.length > 13 ? mappedData.bom_qty.slice(0, 13) + "..." : mappedData.bom_qty).attr('title', mappedData.bom_qty);
            detailsDiv.find('#prod_order_qty').text(mappedData.prod_qty.length > 13 ? mappedData.prod_qty.slice(0, 13) + "..." : mappedData.prod_qty).attr('title', mappedData.prod_qty);
            detailsDiv.find('#shipping_date').text(mappedData.shipping_date.length > 13 ? mappedData.shipping_date.slice(0, 13) + "..." : mappedData.shipping_date).attr('title', mappedData.shipping_date);
            detailsDiv.find('#FI_date').text(mappedData.FI_date.length > 13 ? mappedData.FI_date.slice(0, 13) + "..." : mappedData.FI_date).attr('title', mappedData.FI_date);
            detailsDiv.find('#planned_qty').text(mappedData.planned_qty.length > 13 ? mappedData.planned_qty.slice(0, 13) + "..." : mappedData.planned_qty).attr('title', mappedData.planned_qty);
            detailsDiv.find('#balance_to_sew').text(mappedData.balance_to_sew.length > 13 ? mappedData.balance_to_sew.slice(0, 13) + "..." : mappedData.balance_to_sew).attr('title', mappedData.balance_to_sew);
            detailsDiv.find('#balance_minutes').text(mappedData.balance_minutes.length > 13 ? mappedData.balance_minutes.slice(0, 13) + "..." : mappedData.balance_minutes).attr('title', mappedData.balance_minutes);
            detailsDiv.find('#sam').text(mappedData.sam.length > 13 ? mappedData.sam.slice(0, 13) + "..." : mappedData.sam).attr('title', mappedData.sam);
            detailsDiv.find('#machines').text(mappedData.machines.length > 13 ? mappedData.machines.slice(0, 13) + "..." : mappedData.machines).attr('title', mappedData.machines);
            detailsDiv.find('#efficiency').text(mappedData.efficiency.length > 13 ? mappedData.efficiency.slice(0, 13) + "..." : mappedData.efficiency).attr('title', mappedData.efficiency);
            detailsDiv.find('#special').text(mappedData.special.length > 13 ? mappedData.special.slice(0, 13) + "..." : mappedData.special).attr('title', mappedData.special);
            detailsDiv.find('#sizes').text(mappedData.sizes.length > 13 ? mappedData.sizes.slice(0, 13) + "..." : mappedData.sizes).attr('title', mappedData.sizes);
            detailsDiv.find('#raw_days').text(mappedData.raw_days.length > 13 ? mappedData.raw_days.slice(0, 13) + "..." : mappedData.raw_days).attr('title', mappedData.raw_days);
            detailsDiv.find('#plannedlineqty').text(mappedData.planned_lineqty.length > 13 ? mappedData.planned_lineqty.slice(0, 13) + "..." : mappedData.planned_lineqty).attr('title', mappedData.planned_lineqty);
            detailsDiv.find('#per_day_qty').text(mappedData.per_day_qty.length > 13 ? mappedData.per_day_qty.slice(0, 13) + "..." : mappedData.per_day_qty).attr('title', mappedData.per_day_qty);
            detailsDiv.find('#Per_Day_Qty').text(mappedData.Per_Day_Qty.length > 13 ? mappedData.Per_Day_Qty.slice(0, 13) + "..." : mappedData.Per_Day_Qty).attr('title', mappedData.Per_Day_Qty);
            detailsDiv.find('#color_id').text(mappedData.colorid.length > 13 ? mappedData.colorid.slice(0, 13) + "..." : mappedData.colorid).attr('title', mappedData.colorid);
            detailsDiv.find('#item_id').text(mappedData.itemid.length > 13 ? mappedData.itemid.slice(0, 13) + "..." : mappedData.itemid).attr('title', mappedData.itemid);
            detailsDiv.find('#no_operators').text(mappedData.no_operators.length > 13 ? mappedData.no_operators.slice(0, 13) + "..." : mappedData.no_operators).attr('title', mappedData.no_operators);
            detailsDiv.find('#planner_opr').text(mappedData.planner_opr.length > 13 ? mappedData.planner_opr.slice(0, 13) + "..." : mappedData.planner_opr).attr('title', mappedData.planner_opr);
            detailsDiv.find('#taskstatus').text(mappedData.taskstatus.length > 13 ? mappedData.taskstatus.slice(0, 13) + "..." : mappedData.taskstatus).attr('title', mappedData.taskstatus);
            detailsDiv.find('#detail_id').text(mappedData.detail_id.length > 13 ? mappedData.detail_id.slice(0, 13) + "..." : mappedData.detail_id).attr('title', mappedData.detail_id);
            // ...existing code...
            detailsDiv
                .attr('data-itemid', mappedData.itemid)
                .attr('data-colorid', mappedData.colorid);

                console.log("per_day_qty",mappedData.Per_Day_Qty);

            console.log("Showing order details for OCN:", mappedData.ocn_no, "Item ID:", mappedData.itemid, "Color ID:", mappedData.colorid, "Line No:", lineno);
            refreshChatbotContent();

            // $('#planned_tailor_input').off('keypress').on('keypress', function (e) {
            //     let char = String.fromCharCode(e.which);
            //     let currentValue = $(this).val();
            //     let isDot = char === '.';
            //     let hasDot = currentValue.includes('.');

            //     // Allow digits, a single dot, and control keys (e.g., Backspace, Enter)
            //     if (!/[0-9.]/.test(char) || (isDot && hasDot)) {
            //         e.preventDefault();
            //     }
            // });

            // let isSubmitting = false;
            // $('#submit_tailor_Btn').off('click').on('click', function () {
            //     if (isSubmitting) return;
            //     isSubmitting = true;

            //     let planned_tailor_qty = detailsDiv.find('#planned_tailor_input').val().trim();

            //     // Validate input
            //     if (!planned_tailor_qty || isNaN(planned_tailor_qty) || parseFloat(planned_tailor_qty) <= 0) {
            //         alert('Please enter a valid positive number for the planned tailor quantity.');
            //         isSubmitting = false;
            //         return;
            //     }

            //     // Validate required fields
            //     if (mappedData.itemid === '--' || mappedData.colorid === '--') {
            //         alert('Item ID or Color ID is missing. Cannot save planned tailor quantity.');
            //         isSubmitting = false;
            //         return;
            //     }
            //     if (!lineno) {
            //         alert('Line number is missing. Cannot save planned tailor quantity.');
            //         isSubmitting = false;
            //         return;
            //     }
            //     if (!selectedUnitCode) {
            //         alert('Unit code is missing. Cannot save planned tailor quantity.');
            //         isSubmitting = false;
            //         return;
            //     }

            //     // Prepare data for API
            //     let data = {
            //         ocn_no: mappedData.ocn_no,
            //         itemid: mappedData.itemid,
            //         colorid: mappedData.colorid,
            //         lineno: lineno,
            //         unit_code: selectedUnitCode,
            //         planned_tailor_qty: parseFloat(planned_tailor_qty)
            //     };

            //     console.log('Submitting data:', data);

            //     // Make AJAX request to store planned tailor quantity
            //     // $.ajax({
            //     //     url: "{{ route('updateTailorQuantity') }}",
            //     //     method: 'POST',
            //     //     headers: {
            //     //         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            //     //     },
            //     //     data: data,
            //     //     success: function (response) {
            //     //         if (response.status === "success") {
            //     //             detailsDiv.find('#dynamic-ocn-heading').after('<div class="alert alert-success mt-2">Planned tailor quantity saved!</div>');
            //     //             setTimeout(() => detailsDiv.find('.alert').remove(), 3000);
            //     //             detailsDiv.find('#planned_tailor_input').val(''); // Clear the input field
            //     //             $('#tailor_qty_display').removeClass('d-none');
            //     //             detailsDiv.find('#planned_tailor_qty_display').text(planned_tailor_qty);
            //     //         } else {
            //     //             alert('Failed to save: ' + (response.message || 'Unknown error'));
            //     //         }
            //     //     },
            //     //     error: function (xhr, status, error) {
            //     //         console.error('Error saving planned tailor quantity:', error);
            //     //         alert('An error occurred while saving the planned tailor quantity. Please try again.');
            //     //     },
            //     //     complete: function () {
            //     //         isSubmitting = false;
            //     //         $('#submit_tailor_Btn').prop('disabled', false); // Re-enable button
            //     //     }
            //     // });
                
            // });
        }

        function resetOrderDetails() {
            if (!selectedOCN || !selectedItemId || !selectedColorId || !selectedLineNo) {
                console.warn("No task selected for erasing from gantt chart.", {
                    OCN: selectedOCN,
                    ItemID: selectedItemId,
                    ColorID: selectedColorId,
                    LineNo: selectedLineNo
                });
                alert("Please select a task to erase.");
                return;
            }

            const ocnNumber = getOcnNumber(selectedOCN);
            if (!ocnNumber) {
                console.error("Failed to extract ocn_no from:", selectedOCN);
                alert("Invalid OCN format.");
                return;
            }

            const parsedLineNo = parseInt(selectedLineNo.replace('L', '')) || parseInt(selectedLineNo);
            if (isNaN(parsedLineNo)) {
                console.error("Invalid Line No:", selectedLineNo);
                alert("Invalid Line No selected.");
                return;
            }

            const confirmMessage = `Are you sure you want to erase the following task?\n\n` +
                                    `OCN: ${ocnNumber}\n` +
                                    //`Line: L${parsedLineNo}\n` +
                                    //`Color ID: ${selectedColorId}\n` +
                                    //`Item ID: ${selectedItemId}\n\n` +
                                    `This action will remove the task from the Gantt chart and return it to the PO backlog.`;
            if (!confirm(confirmMessage)) {
                console.log("Erasure cancelled by user for OCN:", ocnNumber);
                return;
            }

            console.log("🔍 Erase task for OCN:", ocnNumber, "Item ID:", selectedItemId, "Color ID:", selectedColorId, "Line No:", parsedLineNo);

            let taskToErase = tasks.find(task => {
                let taskOcnNumber = getOcnNumber(task.ocn);
                let taskLineNo = task.line_no || (task.line && lines[task.line]?.replace('L', '')) || task.line || 0;
                return taskOcnNumber === ocnNumber ///&&
                    //task.itemid == selectedItemId &&
                    //task.colorid == selectedColorId &&
                    //taskLineNo == parsedLineNo;
            }); //|| (activeTaskId ? tasks.find(task => task.id === activeTaskId) : null);

            if (!taskToErase) {
                console.error("No task found for deletion. Search parameters:", {
                    OCN: ocnNumber,
                    //ItemID: selectedItemId,
                    //ColorID: selectedColorId,
                    ///LineNo: parsedLineNo,
                    //ActiveTaskId: activeTaskId
                });
                alert("No task found to erase with the specified OCN/.");
                return;
            }


            let eraseData = {
                ocn_no: ocnNumber,
                //item_id: selectedItemId,
                //color_id: selectedColorId,
                //line_no: parsedLineNo,
                //unit_id: selectedUnitCode || '3'
            };
            // Remove task from tasks array
            tasks = tasks.filter(task => task.ocn !== taskToErase.ocn);

            // Remove task bar from DOM
            //const tooltipPattern = `OCN: ${ocnNumber}, Color: ${taskToErase.color || 'Unknown'}, ItemId: ${taskToErase.itemid}, Line: L${parsedLineNo}`;
            const tooltipPattern = `OCN: ${ocnNumber}`;
            const $taskBar = $('.task-bar').filter(function() {
                return $(this).data('tooltip')?.includes(tooltipPattern);
            });
            if ($taskBar.length) {
                $taskBar.remove();
                console.log(`Removed task bar for OCN: ${ocnNumber}`);
            } else {
                console.warn(`No task bar found in DOM for OCN: ${ocnNumber}`);
            }

            // Restore to backlog
            const fallbackOrderData = selectedOrderData || taskToErase;
            const backlogItem = {
                Ocn: `GIL\\OCN${ocnNumber}`,
                Buyer: fallbackOrderData.buyer || taskToErase.buyer || 'Unknown',
                Order_Qty: taskToErase.units || fallbackOrderData.Bal_To_Sew || 0,
                Itemid: taskToErase.itemid,
                Colorid: taskToErase.colorid,
                Plan_Qty: taskToErase.units || fallbackOrderData.Bal_To_Sew || 2000,
                Ex_Fact_Dt: taskToErase.factoryexit || fallbackOrderData.factoryexit || '',
                Item: taskToErase.item,
                Color: taskToErase.color,
                Line_No: parsedLineNo
            };

            let itemExists = backlogData.some(item => getOcnNumber(item.Ocn) === ocnNumber);
            if (!itemExists) {
                // Find the correct insertion index to maintain sorted order
                const insertIndex = backlogData.findIndex(item => {
                    const existingOcnNumber = getOcnNumber(item.Ocn);
                    return parseInt(existingOcnNumber) > parseInt(ocnNumber);
                });
                if (insertIndex === -1) {
                    // If no larger OCN found, append to end
                    backlogData.push(backlogItem);
                } else {
                    // Insert at the correct position
                    backlogData.splice(insertIndex, 0, backlogItem);
                }
                console.log("🔍 Restored to backlog at index", insertIndex === -1 ? backlogData.length - 1 : insertIndex, ":", backlogItem);
                console.log("Updated backlogData:", backlogData);
            } else {
                console.warn("Task already exists in backlog, skipping addition:", backlogItem);
            }

            // Clear out-of-bounds status
            outOfBoundsOCNs.delete(ocnNumber);

            // Reset selection
            selectedOCN = null;
            selectedItemId = null;
            selectedColorId = null;
            selectedLineNo = null;
            selectedOrderData = null;
            activeTaskId = null;
            selectedBuyer = null; // Reset buyer filter to show all items

            // Re-render backlog and tasks
            renderBacklogItems();
            renderTasks(globalLineDates);

            // Update microplandata
            microplandata = microplandata.filter(item => 
                !(getOcnNumber(item.ocn_no) === ocnNumber && 
                item.item_id == selectedItemId && 
                item.color_id == selectedColorId && 
                item.line_no == parsedLineNo)
            );
            console.log("🔍 Updated microplandata:", microplandata);

            alert("Task erased successfully and restored to backlog.");

            $('#resetDetailsBtn').addClass('d-none');
            $('#splitOrderBtn').addClass('d-none');
            $('#showDetailsBtn').addClass('d-none');
            $('#deleteBtn').addClass('d-none');
            $('#order-details-dynamic').addClass('d-none');
            $('#order-details-default').removeClass('d-none');
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
            
        }


        // --- UTILITY FUNCTIONS ---
        function getDayOffset(plannedDateStr) {
            if (!plannedDateStr) return null;
            const plannedDate = new Date(plannedDateStr);
            if (isNaN(plannedDate.getTime())) return null;
            plannedDate.setHours(0, 0, 0, 0);
            const normalizedPlanningStartDate = new Date(planningStartDate);
            normalizedPlanningStartDate.setHours(0, 0, 0, 0);
            return Math.floor((plannedDate - normalizedPlanningStartDate) / (1000 * 3600 * 24));
        }

        function formatDate(dateStr) {
            if (!dateStr) return '--';
            const date = new Date(dateStr);
            if (isNaN(date.getTime())) return '--';
            return `${String(date.getDate()).padStart(2, '0')}-${date.toLocaleString('default', { month: 'short' })}-${date.getFullYear()}`;
        }

        let lineZones = {}; // Declare lineZones globally

        function formatToYYMMDD(dateStr) {
            if (!dateStr) return '';
            let parts = dateStr.split('-');

            let year, month, day;

            if (parts[0].length === 4) {
                // Format: yyyy-mm-dd
                year = parts[0];
                month = parts[1];
                day = parts[2];
            } else if (parts[2].length === 4) {
                // Format: dd-mm-yyyy
                year = parts[2];
                month = parts[1];
                day = parts[0];
            } else {
                return '';
            }

            return `${year}-${month}-${day}`;
        }

        function populatePOBacklog() {
            let fromDate = $('#start-date').val();
            let toDate = $('#end-date').val();
            $('#backlog').empty();
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();

            $.ajax({
                url: '/microplaningfilter',
                method: 'GET',
                data: {
                    from_date: fromDate,
                    to_date: toDate,
                    unit_code: selectedUnitCode,
                },
                success: function(response) {
                    const data = response.result.data;
                    console.log('API Response:', response);
                    
                        OriginalbacklogData = data.ocndetails;
                        backlogData = data.ocndetails;
                        microplandata = data.plandata || [];
                        let linedetails = data.linedetails || [];
                        let lineSet = new Set();
                        lineCapacities = {}; 
                        lineZones = {};
                        linedetails.forEach(line => {
                            let lineNo = `L${line.Line_No}`;
                            lineSet.add(lineNo);
                            lineCapacities[lineNo] = line.Mch_Cap; 
                            lineZones[lineNo] = line.Zone;
                        });
                        lines.length = 0;
                        lines.push(...Array.from(lineSet));

                        const lineDates = data.linedate || [];
                        console.log('lineDates received:', lineDates);
                        if (lineDates.length > 0) {
                            planningStartDate.setTime(new Date(lineDates[0].Edate).getTime());
                        } else {
                            console.warn('lineDates is empty, using default date range');
                            const defaultStart = new Date('2025-06-23');
                            for (let d = 0; d < 31; d++) {
                                const date = new Date(defaultStart);
                                date.setDate(defaultStart.getDate() + d);
                                lineDates.push({
                                    Edate: date.toISOString().split('T')[0],
                                    WeekNumber: Math.ceil((date.getDate() + date.getDay()) / 7),
                                    NH: null
                                });
                            }
                        }

                        convertToTasks(microplandata);
                        populateBuyerDropdown();
                       // populateStyleDropdown();
                        renderBacklogItems();
                        generateGanttChart(lineDates);

                        // Style search filter
                        $('#styleSearchInput').on('input', function() {
                            const searchTerm = $(this).val().trim().toLowerCase();
                            selectedStyle = searchTerm || null;
                            const dropdownMenu = $('#styleFilterDropdown').next('.dropdown-menu');
                            dropdownMenu.find('li:not(:first)').each(function() {
                                const styleText = $(this).text().toLowerCase();
                                $(this).toggle(styleText.includes(searchTerm));
                            });

                            // Filter backlogData based on search term
                            backlogData = OriginalbacklogData.filter(item => 
                                item.Style && item.Style.toLowerCase().includes(searchTerm)
                            );

                            if (backlogData.length === 0) {
                                $('#backlog').html('<div class="text-secondary p-2">No orders for this selection.</div>');
                            } else {
                                renderBacklogItems();
                            }
                        });
                    
                },
                error: function(xhr, status, error) {
                    console.error('Failed to fetch backlog data:', status, error, xhr.responseText);
                    $('#backlog').html('<div class="text-danger p-2">Error loading backlog.</div>');
                }
            });
        }

        function populateFactoryDropdown() {
            $.ajax({
                url: '/unitdata',
                method: 'GET',
                success: function(response) {
                    const dropdownMenu = $('#factoryDropdown').next('.dropdown-menu').empty();
                    if (response && Array.isArray(response.data) && response.data.length > 0) {
                        response.data.forEach(item => {
                            if (item.Unit && item.Unit_Code) {
                                dropdownMenu.append(`<li><a class="dropdown-item" href="#" data-unit-code="${item.Unit_Code}">${item.Unit}</a></li>`);
                            }
                        });
                        const defaultUnit = response.data.find(item => item.Unit_Code == selectedUnitCode);
                        if (defaultUnit) {
                            $('#factoryDropdown').html(`<i class="bi bi-building-gear"></i> ${defaultUnit.Unit}`);
                        }
                    } else {
                        dropdownMenu.append('<li><span class="dropdown-item text-secondary">No units available</span></li>');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Failed to fetch unit data:', status, error);
                    $('#factoryDropdown').next('.dropdown-menu').empty().append('<li><span class="dropdown-item text-danger">Error loading units</span></li>');
                }
            });
        }
        
        function populateBuyerDropdown() {
            const dropdownMenu = $('#buyerFilterDropdown').next('.dropdown-menu').empty();
            const buyers = [...new Set(backlogData.map(item => item.Buyer).filter(Boolean))].sort();
            dropdownMenu.append('<li><a class="dropdown-item" href="#" data-buyer="">All</a></li>');
            buyers.forEach(buyer => {
                dropdownMenu.append(`<li><a class="dropdown-item" href="#" data-buyer="${buyer}">${buyer}</a></li>`);
            });
            $('#buyerFilterDropdown').html(`<i class="bi bi-person"></i> ${selectedBuyer || 'All'}`);
        }
        
        $('#styleFilterDropdown').next('.dropdown-menu').on('click', '.dropdown-item', function(e) {
            e.preventDefault();
            selectedStyle = $(this).data('style') || null;
            $('#styleFilterDropdown').html(`<i class="bi bi-filter"></i> ${selectedStyle || 'All'}`);
            renderBacklogItems();
            $('#styleSearchInput').val(''); // Clear search input
          //  populateStyleDropdown(); // Refresh dropdown to show all items
        });
        
        function renderBacklogItems() {
            const backlogContainer = $('#backlog').empty();
            let filteredData = backlogData;

            // Apply filters for selectedBuyer and selectedStyle
            if (selectedBuyer) {
                filteredData = filteredData.filter(item => item.Buyer === selectedBuyer);
            }
            if (selectedStyle) {
                // Filter items where the style field contains the search term (case-insensitive)
                filteredData = filteredData.filter(item => 
                    item.Style && item.Style.toLowerCase().includes(selectedStyle.toLowerCase())
                );
            }

            // Remove duplicates based on ocnNumber
            const uniqueOcnMap = new Map();
            filteredData.forEach(item => {
                if (item.Ocn) {
                    const ocnNumber = item.Ocn.split('\\').pop().replace(/^OCN/, '');
                    // Keep the first occurrence of each ocnNumber
                    if (!uniqueOcnMap.has(ocnNumber)) {
                        uniqueOcnMap.set(ocnNumber, item);
                    }
                }
            });
            const uniqueFilteredData = Array.from(uniqueOcnMap.values());

            console.log('=== RENDER BACKLOG DEBUG ===');
            console.log('Filtered data length:', filteredData.length);
            console.log('Unique filtered data length:', uniqueFilteredData.length);
            console.log('Selected buyer:', selectedBuyer);
            console.log('Selected style:', selectedStyle);

            if (uniqueFilteredData.length > 0) {
                uniqueFilteredData.forEach(item => {
                    if (item.Ocn) {
                        const ocnNumber = item.Ocn.split('\\').pop().replace(/^OCN/, '');
                        const $backlogItem = $('<div>', {
                            class: `backlog-item ${outOfBoundsOCNs.has(ocnNumber) ? 'out-of-bounds' : ''}`,
                            'data-ocn': ocnNumber,
                            'data-order-qty': item.Order_Qty || 0,
                            'data-item-id': item.Itemid || 0,
                            'data-color-id': item.Colorid || 0,
                            'data-plan-qty': item.Plan_Qty || 2000,
                            'data-factory-exit': item.Ex_Fact_Dt || '',
                            role: 'option',
                            title: item.Style || 'No Style', // Add Style as tooltip
                            css: { 
                                cursor: 'grab'
                            },
                            html: `
                                <span>${ocnNumber}</span>
                                <span class="spinner-border spinner-border-sm text-white d-none" role="status" id="spinner-${ocnNumber}">
                                    <span class="visually-hidden">Loading...</span>
                                </span>
                            `
                        });

                        console.log('Created backlog item:', {
                            ocn: ocnNumber,
                            orderQty: item.Order_Qty,
                            itemId: item.Itemid,
                            colorId: item.Colorid,
                            planQty: item.Plan_Qty,
                            style: item.Style,
                            isOutOfBounds: outOfBoundsOCNs.has(ocnNumber)
                        });

                        backlogContainer.append($backlogItem);
                    }
                });

                // Make the newly created items draggable
                backlogContainer.find('.backlog-item').draggable({
                    helper: 'clone',
                    revert: 'invalid',
                    appendTo: 'body',
                    zIndex: 100,
                    start: function(event, ui) {
                        console.log('Started dragging:', $(this).data('ocn'));
                    },
                    stop: function(event, ui) {
                        console.log('Stopped dragging:', $(this).data('ocn'));
                    }
                });

                console.log('Made', backlogContainer.find('.backlog-item').length, 'items draggable');
            } else {
                backlogContainer.append('<div class="text-secondary p-2">No orders for this selection.</div>');
            }
        }

        // --- DEBUG FUNCTIONS ---
        function debugTasksArray() {
            console.log('=== TASKS ARRAY DEBUG ===');
            console.log('Tasks array length:', tasks.length);
            console.log('Tasks array content:', tasks);
            console.log('Global lineDates length:', globalLineDates ? globalLineDates.length : 0);
            console.log('Lines array:', lines);
            console.log('Cell width:', cellWidth);
            console.log('Row height:', rowHeight);
            
            // Check if task layer exists
            const $taskLayer = $("#task-layer");
            console.log('Task layer exists:', $taskLayer.length > 0);
            console.log('Task layer children count:', $taskLayer.children().length);
            
            // Check date inputs
            const startDate = document.getElementById('start-date')?.value;
            const endDate = document.getElementById('end-date')?.value;
            console.log('Start date input:', startDate);
            console.log('End date input:', endDate);
        }

        // Add debug function to window for console access
        window.debugTasks = debugTasksArray;

        function addTaskWithSmartLineAssignment(newTask, preferredLine = null, maxDateShiftDays) {
            maxDateShiftDays = maxDateShiftDays || 60;
            // Validate task properties
            if (!newTask.start || !newTask.end || isNaN(new Date(newTask.start)) || isNaN(new Date(newTask.end))) {
                console.error('Invalid task dates:', {
                    ocn: newTask.ocn,
                    itemId: newTask.itemid,
                    colorId: newTask.colorid,
                    start: newTask.start,
                    end: newTask.end
                });
                return { taskAdded: false, assignedLine: null, hasConflict: false, adjustedDates: null };
            }

            // Ensure end date is on or after start date
            const startDate = new Date(newTask.start);
            const endDate = new Date(newTask.end);
            if (endDate < startDate) {
                console.error('End date cannot be before start date:', {
                    ocn: newTask.ocn,
                    start: newTask.start,
                    end: newTask.end
                });
                return { taskAdded: false, assignedLine: null, hasConflict: false, adjustedDates: null };
            }

            // Calculate duration in working days
            const originalWorkingDays = [];
            let current = new Date(startDate);
            while (current <= endDate) {
                if (current.getDay() !== 0 && !isHoliday(current, globalLineDates)) {
                    originalWorkingDays.push(current.toISOString().split('T')[0]);
                }
                current.setDate(current.getDate() + 1);
            }
            const durationInWorkingDays = originalWorkingDays.length;

            if (durationInWorkingDays < 0) {
                console.error('Invalid task duration (no working days):', {
                    ocn: newTask.ocn,
                    itemId: newTask.itemid,
                    colorId: newTask.colorid,
                    start: newTask.start,
                    end: newTask.end
                });
                return { taskAdded: false, assignedLine: null, hasConflict: false, adjustedDates: null };
            }

            // Log tasks before adding
            console.log('Before adding - tasks:', tasks.map(t => ({
                id: t.id,
                ocn: t.ocn,
                itemId: t.itemid,
                colorId: t.colorid,
                line: t.line,
                start: t.start,
                end: t.end
            })));

            // Step 1: Check if any line is conflict-free for original dates
            let assignedLine = findAvailableLine(newTask.start, newTask.end, preferredLine);
            let hasConflict = assignedLine === null;

            // Step 2: If all lines are occupied, try shifting dates to find a conflict-free slot
            let adjustedDates = null;
            if (hasConflict) {
                console.log(`All lines occupied for task ${newTask.ocn} on dates ${newTask.start} to ${newTask.end}. Searching for conflict-free dates...`);
                let attemptCount = 0;
                let currentStart = new Date(newTask.start);
                const maxAttempts = maxDateShiftDays;

                while (hasConflict && attemptCount < maxAttempts) {
                    // Shift start date by one day
                    currentStart.setDate(currentStart.getDate() + 1);
                    const currentEnd = new Date(currentStart);

                    // Adjust end date to maintain duration in working days
                    let workingDays = 0;
                    let tempDate = new Date(currentStart);
                    while (workingDays < durationInWorkingDays) {
                        if (tempDate.getDay() !== 0 && !isHoliday(tempDate, globalLineDates)) {
                            workingDays++;
                        }
                        tempDate.setDate(tempDate.getDate() + 1);
                    }
                    currentEnd.setDate(tempDate.getDate() - 1); // Set end date to last valid working day

                    // Ensure end date is on or after start date
                    if (currentEnd < currentStart) {
                        console.warn(`Adjusted end date ${currentEnd.toISOString().split('T')[0]} is before start date ${currentStart.toISOString().split('T')[0]}. Skipping attempt.`);
                        attemptCount++;
                        continue;
                    }

                    // Check for conflict with new dates
                    const newStartStr = currentStart.toISOString().split('T')[0];
                    const newEndStr = currentEnd.toISOString().split('T')[0];
                    assignedLine = findAvailableLine(newStartStr, newEndStr, preferredLine);
                    hasConflict = assignedLine === null;

                    if (!hasConflict) {
                        // Update task with new dates
                        newTask.start = newStartStr;
                        newTask.end = newEndStr;
                        adjustedDates = { start: newTask.start, end: newTask.end };
                        console.log(`Task ${newTask.ocn} dates adjusted to: start=${newTask.start}, end=${newTask.end}`);
                    }

                    attemptCount++;
                }
            }

            // Step 3: If still has conflict after max attempts, do not place the task
            if (hasConflict) {
                const conflictingTasks = tasks.filter(task => {
                    const taskStart = new Date(task.start);
                    const taskEnd = new Date(task.end);
                    const start = new Date(newTask.start);
                    const end = new Date(newTask.end);
                    return (start <= taskEnd && end >= taskStart);
                });
                console.warn(`Cannot add task ${newTask.ocn}: No conflict-free line or date range found within ${maxDateShiftDays} days`, conflictingTasks.map(t => ({
                    id: t.id,
                    ocn: t.ocn,
                    itemId: t.itemid,
                    colorId: t.colorid,
                    start: t.start,
                    end: t.end
                })));
                return { taskAdded: false, assignedLine: null, hasConflict: true, adjustedDates: null };
            }

            // Step 4: Update task with assigned line
            newTask.line = assignedLine;

            // Step 5: Add task with deduplication
            const taskAdded = addTaskSafely(newTask);

            if (taskAdded) {
                console.log(`Task ${newTask.ocn} assigned to line ${lines[assignedLine]} (conflict-free)`);
                // Visual feedback
                setTimeout(() => {
                    $(`div.task-bar[data-id="${newTask.id}"]`)
                        .css('backgroundColor', '#ffeb3b')
                        .animate({ backgroundColor: '#87ceeb' }, 1000);
                }, 100); // Delay to ensure DOM is updated
            } else {
                console.warn(`Cannot add task ${newTask.ocn}: Task already exists`);
            }

            // Log tasks after adding
            console.log('After adding - tasks:', tasks.map(t => ({
                id: t.id,
                ocn: t.ocn,
                itemId: t.itemid,
                colorId: t.colorid,
                line: t.line,
                start: t.start,
                end: t.end
            })));

            return { taskAdded, assignedLine, hasConflict: false, adjustedDates };
        }

        // Helper function to check for line conflicts on specific dates
        function checkLineConflict(startDate, endDate, lineIndex) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            return tasks.some(task => {
                if (task.line !== lineIndex) return false;
                
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                
                // Check if date ranges overlap
                return (start <= taskEnd && end >= taskStart);
            });
        }

        // Helper function to find available line for a date range
        function findAvailableLine(startDate, endDate, preferredLine = null) {
            // If preferred line is available, use it
            if (preferredLine !== null && !checkLineConflict(startDate, endDate, preferredLine)) {
                return preferredLine;
            }
            
            // Find first available line
            for (let i = 1; i < lines.length; i++) {
                if (!checkLineConflict(startDate, endDate, i)) {
                    return i;
                }
            }
            
            // If no line is available, return null (no fallback to least conflicted)
            return null;
        }

        // Helper function to find line with least conflicts
        function findLeastConflictedLine(startDate, endDate) {
            const conflictCounts = new Array(lines.length).fill(0);
            
            tasks.forEach(task => {
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                const start = new Date(startDate);
                const end = new Date(endDate);
                
                if (start <= taskEnd && end >= taskStart) {
                    conflictCounts[task.line]++;
                }
            });
            
            // Return line with minimum conflicts
            return conflictCounts.indexOf(Math.min(...conflictCounts));
        }

        // Function to show conflict information
        function showConflictInfo(task) {
            const conflictingTasks = tasks.filter(otherTask => {
                if (otherTask.id === task.id) return false;
                if (otherTask.line !== task.line) return false;
                
                const otherStart = new Date(otherTask.start);
                const otherEnd = new Date(otherTask.end);
                const taskStart = new Date(task.start);
                const taskEnd = new Date(task.end);
                
                return (taskStart <= otherEnd && taskEnd >= otherStart);
            });
            
            if (conflictingTasks.length > 0) {
                let conflictMessage = `⚠️ CONFLICT DETECTED!\n\nTask: ${task.ocn} (${task.color || 'N/A'})\nLine: ${lines[task.line]}\n\nConflicting tasks:\n`;
                conflictingTasks.forEach((conflictTask, index) => {
                    conflictMessage += `${index + 1}. ${conflictTask.ocn} (${conflictTask.color || 'N/A'}) - ${conflictTask.start} to ${conflictTask.end}\n`;
                });
                conflictMessage += `\nConsider moving one of these tasks to a different line.`;
                
                alert(conflictMessage);
            }
        }

        // Enhanced task click handler
        function handleTaskClick(task) {
            if (task.hasConflict) {
                showConflictInfo(task);
            }
            
            // Continue with normal task selection
            selectedOCN = task.ocn;
            selectedLineNo = lines[task.line];
            selectedOrderData = task;
            
            console.log("✅ Task clicked:", task.ocn, "Line:", selectedLineNo, "Conflict:", task.hasConflict);
        }

        // Test function to verify smart line assignment
        window.testSmartLineAssignment = function() {
            console.log('🧪 Testing Smart Line Assignment System...');
            
            // Clear tasks first
            clearTasks();
            
            // Test 1: Add tasks with overlapping dates on same line
            const task1 = {
                ocn: 'TEST001',
                start: '2025-06-23',
                end: '2025-06-25',
                duration: 3,
                units: 1000,
                colorid: 100,
                color: 'BLACK'
            };
            
            const task2 = {
                ocn: 'TEST002',
                start: '2025-06-24', // Overlaps with task1
                end: '2025-06-26',
                duration: 3,
                units: 1000,
                colorid: 200,
                color: 'WHITE'
            };
            
            const result1 = addTaskWithSmartLineAssignment(task1, 0); // Try to place on line 0
            console.log('Test 1 - First task:', result1.taskAdded ? 'SUCCESS' : 'FAILED', 'Line:', lines[result1.assignedLine]);
            
            const result2 = addTaskWithSmartLineAssignment(task2, 0); // Try to place on line 0 (should conflict)
            console.log('Test 2 - Second task (conflict expected):', result2.taskAdded ? 'SUCCESS' : 'FAILED', 'Line:', lines[result2.assignedLine], 'Conflict:', result2.hasConflict);
            
            // Test 3: Add task with no overlap (should go to preferred line)
            const task3 = {
                ocn: 'TEST003',
                start: '2025-06-27', // No overlap
                end: '2025-06-29',
                duration: 3,
                units: 1000,
                colorid: 300,
                color: 'RED'
            };
            
            const result3 = addTaskWithSmartLineAssignment(task3, 0); // Should go to line 0
            console.log('Test 3 - Third task (no overlap):', result3.taskAdded ? 'SUCCESS' : 'FAILED', 'Line:', lines[result3.assignedLine], 'Conflict:', result3.hasConflict);
            
            // Re-render to see visual results
            renderTasks(globalLineDates);
            
            console.log('Final tasks count:', tasks.length);
            console.log('Final tasks:', tasks);
            
            return {
                totalTests: 3,
                passedTests: [result1.taskAdded, result2.taskAdded, result3.taskAdded].filter(Boolean).length,
                conflictsDetected: [result1.hasConflict, result2.hasConflict, result3.hasConflict].filter(Boolean).length,
                finalTaskCount: tasks.length
            };
        };

        function printGanttWithTasks() {
            const planningArea = document.getElementById('planning-area');
            const clonedArea = planningArea.cloneNode(true);

            // Inline styles
            const allStyles = [...document.styleSheets].map(sheet => {
                try {
                    return [...sheet.cssRules].map(rule => rule.cssText).join('\n');
                } catch (err) {
                    return ''; // Skip cross-origin styles
                }
            }).join('\n');

            // Fix container height so everything is visible
            clonedArea.style.height = 'auto';
            clonedArea.style.overflow = 'visible';

            const printWindow = window.open('', '_blank');
            printWindow.document.write(`
                <html>
                <head>
                    <title>Print Gantt</title>
                    <style>
                        ${allStyles}
                        body { margin: 0; padding: 10px; background: #fff; font-family: sans-serif; }

                        table { border-collapse: collapse; width: 100%; }
                        th, td { border: 1px solid #ccc; padding: 4px; text-align: center; }

                        #planning-area {
                            position: relative !important;
                            overflow: visible !important;
                            height: auto !important;
                        }

                        #task-layer, #dependency-layer {
                            position: absolute !important;
                            top: 0; left: 0;
                            width: 100%; height: 100%;
                            z-index: 5;
                        }

                        .task-bar {
                            position: absolute !important;
                            background-color: #4caf50 !important;
                            color: #fff;
                            border-radius: 4px;
                            font-size: 10px;
                            padding: 2px 4px;
                            box-sizing: border-box;
                        }

                        @media print {
                            .no-print, button { display: none !important; }
                            body { zoom: 90%; }
                        }
                    </style>
                </head>
                <body>
                    <div id="print-wrapper">${clonedArea.outerHTML}</div>
                </body>
                </html>
            `);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            $('#floating-chatbot-card, #chatbot-toggle-btn').hide();
        }

        function filterTaskbars(term) {
            const searchTerm = term.trim().toLowerCase();
            const bars = document.querySelectorAll('.task-bar');
            let firstMatch = null;

            bars.forEach(bar => {
                // Remove any existing highlight/blur to reset state
                bar.classList.remove('task-highlight', 'task-blur');

                if (!searchTerm) return; // No filter, all reset

                const ocn = (bar.dataset.ocn || '').toLowerCase();
                const color = (bar.dataset.color || '').toLowerCase();
                const itemid = (bar.dataset.itemid || '').toLowerCase();
                const line = (bar.dataset.line || '').toLowerCase();
                const label = (bar.dataset.label || '').toLowerCase();
                const tooltip = (bar.dataset.tooltip || '').toLowerCase();
                const itemname = (bar.dataset.itemname || '').toLowerCase();

                const match = ocn.includes(searchTerm) ||
                            color.includes(searchTerm) ||
                            itemid.includes(searchTerm) ||
                            line.includes(searchTerm) ||
                            label.includes(searchTerm) ||
                            tooltip.includes(searchTerm) ||
                            itemname.includes(searchTerm);

                if (match) {
                    bar.classList.add('task-highlight');
                    if (!firstMatch) firstMatch = bar;
                } else {
                    bar.classList.add('task-blur');
                }
            });

            if (firstMatch) {
                firstMatch.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }

        function clearTaskbarFilter() {
            document.getElementById('taskSearch').value = '';
            filterTaskbars('');
        }

    </script>
</body>
</html>
