<?php
include 'pu_update_task.inc.php';
?>
<div class="container-fluid" style="background-color: #ffe6e6;">
<?php
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$year  = isset($_GET['year'])  ? intval($_GET['year'])  : date('Y');

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

$shifts     = [];
$shiftHours = [];
$shiftDays  = [];
$shiftTimes = [];

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

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

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

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

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

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

            // Collect this day's shifts first...
            $dayShifts = [];
            foreach ($shifts as $shift) {
                if ($shiftDays[$shift] === $dayOfWeek) {
                    $dayShifts[] = $shift;
                }
            }

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

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

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

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

// Machine names (needed for labels column + modals)
$sql          = "
    SELECT sm.id AS machine_id, sm.resource_code, pm.virtual_id AS id, pm.no_of_table
    FROM station_detail_table sm
    JOIN pu_mapping_tables pm ON pm.machine_id = sm.id
    WHERE sm.machine_type = 4 AND sm.hide = 0  ORDER BY sm.id ASC
";
$machineQuery = mysqli_query($conn, $sql);
$taskNames    = [];
while ($row = mysqli_fetch_assoc($machineQuery)) {
    $taskNames[$row['id']] = $row['resource_code'];
}

// Active breakdowns (needed for label column styling)
$activeBreakdowns = [];
$breakdownQuery   = "SELECT machine_id, breakdown_reason FROM machine_breakdown WHERE is_active = 1";
$breakdownResult  = mysqli_query($conn, $breakdownQuery);
while ($breakdown = mysqli_fetch_assoc($breakdownResult)) {
    $activeBreakdowns[$breakdown['machine_id']] = $breakdown['breakdown_reason'];
}

$colorPalette = [
    '#e6f5f5','#f5e6f5','#e6ffe6','#fff2e6','#f0e6ff',
    '#e6ffff','#ffe6f2','#f5f5e6','#e6f5f5','#f5e6ff',
    '#e6ffec','#fff0e6','#e6f0ff','#ffe6ff','#e6ffe6',
    '#f5e6e6','#e6e6f5','#f5f5e6','#e6f5f5','#f5e6f5'
];
$machineColors = [];
$colorIndex    = 0;
foreach ($taskNames as $machineId => $taskName) {
    $machineColors[$machineId] = $colorPalette[$colorIndex % count($colorPalette)];
    $colorIndex++;
}
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
    :root {
        --primary-color: #3498db;
        --secondary-color: #2c3e50;
        --accent-color: #e74c3c;
        --light-bg: #f8f9fa;
        --dark-bg: #343a40;
        --success-color: #2ecc71;
        --warning-color: #f39c12;
        --danger-color: #e74c3c;
        --info-color: #3498db;
        --current-time-color: #e74c3c;
        --time-marker-color: #fff3cd;
        --shift-highlight: #d4edda;
        --time-interval-width: 40px;
        --task-bar-height: 130px;
        --grid-line-color: rgba(0,0,0,0.1);
        --breakdown-color: #ff4444;
    }
    html { font-size: 14px; }
    .gantt-container { position:relative; width:100%; overflow-x:auto; margin-top:20px; display:flex; background-color:white; box-shadow:0 2px 10px rgba(0,0,0,0.1); border-radius:8px; }
    .gantt-labels { position:sticky; left:0; top:0; width:270px; background:#f9f9f9; padding:15px; border-right:1px solid #ddd; z-index:20; height:fit-content; flex-shrink:0; }
    .gantt-scrollable-content { flex:1; min-width:0; overflow-x:auto; position:relative; }
    .gantt-grid { display:inline-block; min-width:<?php echo $totalWidth; ?>px; position:relative; }
    .gantt-header { display:inline-flex; background:#f5f5f5; border-bottom:1px solid #ddd; position:sticky; top:0; z-index:15; }
    .gantt-day { display:inline-flex; flex-direction:column; text-align:center; background-color:#fff; float:none; vertical-align:top; position:relative; }
    .gantt-day strong { font-size:12px; color:#333; background:#f3f3f3; padding:3px; border-radius:3px; margin-bottom:5px; }
    .gantt-time-intervals { display:flex; flex-wrap:nowrap; justify-content:flex-start; width:100%; background-color:#f8f9fa; border-top:1px solid #dee2e6; }
    .gantt-time-interval { flex:0 0 var(--time-interval-width); text-align:center; font-size:10px; color:#555; border-right:1px solid var(--grid-line-color); height:30px; position:relative; }
    .gantt-time-interval-label { position:absolute; font-size:clamp(8px,0.7vw,11px); transform:rotate(-45deg); transform-origin:left center; white-space:nowrap; left:0%; bottom:-15px; color:#000; }
    .gantt-row { display:block; border-bottom:1px solid #000; min-height:var(--task-bar-height); position:relative; white-space:nowrap; background-image:linear-gradient(to right,var(--grid-line-color) 1px,transparent 1px); background-size:var(--time-interval-width) 1px; background-position:left center; }
    .gantt-task { position:absolute; height:100%; top:0; background:#3498db; color:white; text-align:center; border-radius:5px; padding:5px; line-height:1.2; font-size:12px; cursor:grab; transition:background-color 0.3s ease; box-shadow:1px 1px 3px rgba(0,0,0,0.2); z-index:1; overflow:hidden; box-sizing:border-box; border-right:3px solid rgba(255,255,255,0.5); }
    .gantt-task .task-content { padding:1px; font-size:clamp(10px,0.8vw,13px); height:calc(100% - 20px); overflow:hidden; }
    .no-tasks { color:#999; font-style:italic; padding:10px; text-align:center; width:100%; }
    .breakdown-task { background-color:var(--breakdown-color) !important; border-left:3px solid #cc0000 !important; border-right:3px solid #cc0000 !important; color:white !important; }
    .breakdown-affected { background:repeating-linear-gradient(45deg,#ff6b6b,#ff6b6b 10px,#ff8e8e 10px,#ff8e8e 20px) !important; border:2px dashed #ff0000 !important; }
    .machine-with-breakdown { background-color:#ffe6e6 !important; border-left:4px solid var(--breakdown-color) !important; }
    .breakdown-indicator { position:absolute; top:5px; right:5px; width:12px; height:12px; background-color:var(--breakdown-color); border-radius:50%; animation:pulse 1.5s infinite; }
    @keyframes pulse { 0%{opacity:1} 50%{opacity:0.5} 100%{opacity:1} }
    .dot-indicator { position:absolute; top:4px; right:4px; width:20px; height:20px; border-radius:50%; border:3px solid black; z-index:5; }
    .green-dot-indicator { background-color:#00cc66; }
    .red-dot-indicator   { background-color:#ff3333; }
    .blue-dot-indicator  { background-color:#3399ff; }
    .hour-indicator { position:absolute; bottom:0; left:0; right:0; font-size:0.65rem; text-align:center; background:rgba(0,0,0,0.15); padding:1px 0; border-radius:0 0 4px 4px; }
    .machine-list { display:flex; flex-direction:column; gap:10px; }
    .controls { background:white; padding:15px; border-radius:8px; margin-bottom:20px; box-shadow:0 2px 5px rgba(0,0,0,0.1); }
    .machine-section { margin-bottom:15px; }
    .card { border-radius:8px; box-shadow:0 2px 5px rgba(0,0,0,0.1); transition:transform 0.2s; }
    .card:hover { transform:translateY(-2px); }
    .card-header { font-weight:500; padding:8px 12px; }
    .form-control { font-size:0.85rem; padding:0.25rem 0.5rem; }
    .gantt-task.dragging { opacity:0.5; background-color:#f39c12; }
    .gantt-row.drop-target { outline:2px dashed #007bff; background-color:#e6f7ff; }
    .gantt-day.today { background-color:#fff3cd; box-shadow:0 0 0 2px #ffc107; }
    .gantt-day.today strong { background-color:#ffc107; color:#000; font-weight:bold; }
    .gantt-task.filter-highlight { outline:3px solid yellow; box-shadow:0 0 15px yellow; z-index:10; }
    .gantt-task.drag-highlight { outline:2px dashed #007bff; }
    .gantt-task.late-task    { background-color:#ff6b6b !important; border-left:3px solid #ff0000 !important; border-right:3px solid #ff0000 !important; }
    .gantt-task.on-time-task { background-color:#78c679 !important; border-left:3px solid #2ecc71 !important; border-right:3px solid #2ecc71 !important; }
    .gantt-task.break-task   { background-color:#999 !important; border-left:3px dashed #fff !important; border-right:3px dashed #fff !important; color:#fff !important; }
    .modal-dialog { max-width:1200px; }
    .modal-content { border-radius:10px; border:none; box-shadow:0 5px 20px rgba(0,0,0,0.2); }
    .modal-header { background-color:var(--secondary-color); color:white; border-radius:10px 10px 0 0; padding:15px 20px; }
    .modal-title  { font-weight:600; }
    .modal-body   { padding:20px; }
    .modal-footer { border-top:1px solid #e9ecef; padding:15px 20px; }
    .custom-scroll { max-height:600px; overflow-y:auto; }
    .form-check-input { width:24px !important; height:24px !important; cursor:pointer; border:2px solid #6c757d; border-radius:4px; }
    .form-check-input:checked { background-color:#0d6efd; border-color:#0d6efd; }
    .sortable { cursor:pointer; user-select:none; position:relative; padding-right:25px !important; }
    .sortable:hover { background-color:#e9ecef !important; }
    .sortable::after  { content:'⇅'; position:absolute; right:8px; opacity:0.3; font-size:14px; }
    .sortable.asc::after  { content:'↑'; opacity:1; color:#0d6efd; }
    .sortable.desc::after { content:'↓'; opacity:1; color:#0d6efd; }
    .modal-loading-overlay { position:absolute; top:0; left:0; right:0; bottom:0; background:rgba(255,255,255,0.8); display:none; align-items:center; justify-content:center; z-index:1000; }
    .modal-loading-overlay.active { display:flex; }
    .loading-spinner { display:none; position:absolute; right:25px; top:50%; transform:translateY(-50%); }
    .table-select-container { position:relative; }
    #gantt-rows-loading { padding:40px; text-align:center; color:#666; }
</style>

<div class="container-fluid">
    <!-- Controls with filters -->
    <div class="controls">
        <div class="row align-items-center mb-3">
            <div class="col-md-4">
                <h3 class="mb-0"><i class="fas fa-calendar-day me-2"></i>PU Gantt Chart</h3>
                <h5 class="text-muted"><?php echo date('l, F j, Y'); ?></h5>
            </div>
            <div class="col-md-8">
                <!-- Filter Row -->
                <div class="row g-2 mb-2">
                    <div class="col-md-4">
                        <input type="text" id="filter_part" class="form-control" placeholder="Part Number">
                    </div>
                    <div class="col-md-4">
                        <input type="text" id="filter_wo" class="form-control" placeholder="Work Order">
                    </div>
                    <div class="col-md-4">
                        <button class="btn btn-success w-100" onclick="applyFilters()">Apply</button>
                    </div>
                </div>
                <!-- Action Buttons -->
                <div class="d-flex justify-content-end flex-wrap gap-2">
                    <button type="button" class="btn btn-primary show-work-order-button" data-bs-toggle="modal" data-bs-target="#workOrderModal">
                        <i class="fas fa-list-check me-1"></i> Work Orders
                    </button>
                    <button class="btn btn-primary" onclick="loadGanttRows()">
                        <i class="fas fa-sync-alt me-1"></i> Refresh
                    </button>
                    <button class="btn btn-warning" id="addBreakBtn">
                        <i class="fas fa-clock me-1"></i> Add Break
                    </button>
                    <button class="btn btn-danger hide" id="startBreakdownBtn">
                        <i class="fas fa-exclamation-triangle me-1"></i> Start Breakdown
                    </button>
                    <button class="btn btn-success hide" id="stopBreakdownBtn">
                        <i class="fas fa-check me-1"></i> Stop Breakdown
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="gantt-container">
        <!-- Sticky machine labels -->
        <div class="gantt-labels">
            <h5><i class="fas fa-server me-2"></i>Machine Detail</h5>
            <div style="margin-bottom:20px;"></div>
            <div class="machine-list">
                <?php
                $renderedMachines = [];
                foreach ($taskNames as $machineId => $taskName):
                    if (!in_array($machineId, $renderedMachines)):
                        $hasBreakdown       = isset($activeBreakdowns[$machineId]);
                        $renderedMachines[] = $machineId;
                ?>
                    <div class="machine-section mb-0" style="width:200px;" data-machine-id="<?php echo $machineId; ?>">
                        <div class="row" style="margin-bottom:1px; height:120px;">
                            <div class="card <?php echo $hasBreakdown ? 'machine-with-breakdown' : ''; ?>"
                                 style="background-color:#e6f2ff; margin-left:12px; position:relative;">
                                <?php if ($hasBreakdown): ?>
                                    <div class="breakdown-indicator" title="Machine Breakdown Active"></div>
                                <?php endif; ?>
                                <div style="display:flex; margin-top:9px; justify-content:center; align-items:center; height:100%; font-weight:bold; flex-direction:column;">
                                    <?php echo $taskName; ?>
                                    <?php
                                        $lastDigit = substr($machineId, -1);
                                        echo '<small>Table ' . $lastDigit . '</small>';
                                    ?>
                                    <?php if ($hasBreakdown): ?>
                                        <small style="color:#ff0000; font-size:10px;">BREAKDOWN</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php
                    endif;
                endforeach;
                ?>
            </div>
        </div>

        <!-- Scrollable Gantt content -->
        <div class="gantt-scrollable-content">
            <div class="gantt-grid">

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

                <!-- Task Rows: loaded via AJAX -->
                <div id="gantt-rows-container">
                    <div id="gantt-rows-loading">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2">Loading schedule...</p>
                    </div>
                </div>

            </div><!-- /.gantt-grid -->
        </div><!-- /.gantt-scrollable-content -->
    </div><!-- /.gantt-container -->
</div><!-- /.container-fluid -->

<!-- Work Order Detail Modal -->
<div class="modal fade" id="workOrderDetailModal" tabindex="-1" aria-labelledby="workOrderDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="workOrderDetailModalLabel">
                    <i class="fas fa-info-circle me-2"></i>Work Order Details
                </h5>
               
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
				  <span aria-hidden="true">&times;</span>
				</button>
            </div>
            <div class="modal-body">
                <div id="detailLoadingSpinner" class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <p class="mt-2">Loading details...</p>
                </div>
                <div id="workOrderDetailContent" style="display: none;">
                    <!-- Work Order Information -->
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0"><i class="fas fa-clipboard-list me-2"></i>Order Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                   <!-- <p><strong>Work Order No:</strong> <span id="detail_wo_no"></span></p>-->
                                    <p><strong>Customer Order:</strong> <span id="detail_customer_order"></span></p>
                                    <p><strong>Work Order Name:</strong> <span id="detail_wo_name"></span></p>
									<p><strong>Status:</strong> <span id="detail_status" class="badge"></span></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Final Part:</strong> <span id="detail_final_part"></span></p>
                                    <p><strong>Customer code:</strong> <span id="detail_customer_code" class=""></span></p>
									<p><strong>RefSalescode:</strong> <span id="detail_RefSalesCode" class=""></span></p>
                                    
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Part Information -->
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0"><i class="fas fa-cog me-2"></i>Part Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Part/Set Name:</strong> <span id="detail_part_name"></span></p>
									<p><strong>Desc:</strong> <span id="detail_desc"></span></p>
                                    <p><strong>Quantity:</strong> <span id="detail_quantity"></span></p>
                                   
                                </div>
                                <div class="col-md-6">
                                    <p><strong>Setup Hours:</strong> <span id="detail_setup_hours"></span></p>
                                    <p><strong>Total Hours:</strong> <span id="detail_total_hours"></span></p>
                                    <p><strong>Due Date:</strong> <span id="detail_due_date"></span></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Production Details -->
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0"><i class="fas fa-wrench me-2"></i>Production Details</h6>
                        </div>
                        <div class="card-body">
                            <p><strong>Description:</strong> <span id="detail_route_desc"></span></p>
                            <div id="breakdown_info" style="display: none;" class="alert alert-danger">
                                <strong><i class="fas fa-exclamation-triangle me-2"></i>Breakdown Impact:</strong>
                                <span id="detail_breakdown_hours"></span> hours delay
                            </div>
                        </div>
                    </div>

                    <!-- Schedule Information -->
                <!--    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0"><i class="fas fa-calendar me-2"></i>Schedule Information</h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <p><strong>Start Date:</strong> <span id="detail_start_date"></span></p>
                                    <p><strong>Start Time:</strong> <span id="detail_start_time"></span></p>
                                </div>
                                <div class="col-md-6">
                                    <p><strong>End Date:</strong> <span id="detail_end_date"></span></p>
                                    <p><strong>Shift:</strong> <span id="detail_shift"></span></p>
                                </div>
                            </div>
                        </div>
                    </div>-->
                </div>
                <div id="detailErrorMessage" class="alert alert-danger d-none" role="alert">
                    Failed to load work order details. Please try again.
                </div>
            </div>
            <div class="modal-footer">
				 <button type="button" class="btn btn-secondary" data-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
                <button type="button" class="btn btn-warning hide" id="editWorkOrderBtn">
                    <i class="fas fa-edit me-2"></i>Edit
                </button>
				<button type="button" class="btn btn-info" id="splitWorkOrderBtn" style="display:none;">
    <i class="fas fa-cut me-2"></i>Split Work Order
</button>
                <button type="button" class="btn btn-danger" id="deleteWorkOrderBtn">
                    <i class="fas fa-trash me-2"></i>Delete
                </button>
            </div>
        </div>
    </div>
</div>
<!-- Split Work Order Modal -->
<div class="modal fade" id="splitWorkOrderModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title"><i class="fas fa-cut me-2"></i>Split Work Order</h5>
                <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info"><i class="fas fa-info-circle me-2"></i>Split this work order into two based on quantity.</div>
                <form id="splitWorkOrderForm">
                    <input type="hidden" id="split_task_id" name="task_id">
                    <div class="mb-3">
                        <label class="form-label"><strong>Current Quantity:</strong></label>
                        <p id="split_current_quantity" class="form-control-plaintext">-</p>
                    </div>
                    <div class="mb-3">
                        <label for="split_quantity" class="form-label">Split Quantity <span class="text-danger">*</span></label>
                        <input type="number" class="form-control" id="split_quantity" name="split_quantity" min="1" step="1" required>
                        <small class="form-text text-muted">Enter the quantity for the new work order</small>
                    </div>
                    <div id="split_preview" style="display:none;" class="mt-3">
                        <h6 class="border-bottom pb-2">Preview:</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card bg-light"><div class="card-body">
                                    <h6 class="card-title text-primary">Original WO</h6>
                                    <p class="mb-1"><strong>Quantity:</strong> <span id="preview_remaining_qty">-</span></p>
                                    <p class="mb-0"><strong>Hours:</strong> <span id="preview_remaining_hours">-</span></p>
                                </div></div>
                            </div>
                            <div class="col-md-6">
                                <div class="card bg-light"><div class="card-body">
                                    <h6 class="card-title text-success">New WO</h6>
                                    <p class="mb-1"><strong>Quantity:</strong> <span id="preview_split_qty">-</span></p>
                                    <p class="mb-0"><strong>Hours:</strong> <span id="preview_split_hours">-</span></p>
                                </div></div>
                            </div>
                        </div>
                    </div>
                    <div id="split_error" class="alert alert-danger mt-3" style="display:none;"></div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-info" id="confirmSplitBtn"><i class="fas fa-check me-2"></i>Confirm Split</button>
            </div>
        </div>
    </div>
</div>
<!-- Edit Work Order Modal -->
<div class="modal fade" id="editWorkOrderModal" tabindex="-1" aria-labelledby="editWorkOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title" id="editWorkOrderModalLabel">
                    <i class="fas fa-edit me-2"></i>Edit Work Order
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editWorkOrderForm">
                    <input type="hidden" id="edit_task_id" name="task_id">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="edit_priority" class="form-label">Priority</label>
                            <input type="number" class="form-control" id="edit_priority" name="priority" min="1">
                        </div>
                        <div class="col-md-6">
                            <label for="edit_machine" class="form-label">Machine</label>
                            <select class="form-control" id="edit_machine" name="machine_id">
                                <?php foreach ($taskNames as $machineId => $taskName): ?>
                                    <option value="<?php echo $machineId; ?>"><?php echo $taskName; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="edit_setup_hours" class="form-label">Setup Hours</label>
                            <input type="number" class="form-control" id="edit_setup_hours" name="setup_hours" step="0.5" min="0">
                        </div>
                        <div class="col-md-6">
                            <label for="edit_total_hours" class="form-label">Total Hours</label>
                            <input type="number" class="form-control" id="edit_total_hours" name="total_hours" step="0.5" min="0">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="edit_setting_instruction" class="form-label">Setting Instruction</label>
                        <textarea class="form-control" id="edit_setting_instruction" name="setting_instruction" rows="3"></textarea>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="edit_start_date" class="form-label">Start Date</label>
                            <input type="date" class="form-control" id="edit_start_date" name="start_date">
                        </div>
                        <div class="col-md-6">
                            <label for="edit_quantity" class="form-label">Quantity</label>
                            <input type="number" class="form-control" id="edit_quantity" name="quantity" min="1">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveEditBtn">
                    <i class="fas fa-save me-2"></i>Save Changes
                </button>
            </div>
        </div>
    </div>
</div>


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

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

<div class="modal fade" id="breakModal" tabindex="-1" aria-labelledby="breakModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="breakModalLabel">Add Machine Break</h5>
                 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
				  <span aria-hidden="true">&times;</span>
				</button>
            </div>
            <div class="modal-body">
                <form id="breakForm">
                    <div class="mb-3">
                        <label for="breakMachine" class="form-label">Machine</label>
                        <select class="form-select" id="breakMachine" required>
                            <option value="">Select Machine</option>
                            <?php foreach ($taskNames as $machineId => $taskName): ?>
                                <option value="<?php echo $machineId; ?>">
                                    <?php echo $taskName; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="breakDuration" class="form-label">Duration (hours)</label>
                        <input type="number" class="form-control" id="breakDuration" 
                               min="1" max="10" step="1" required>
                        <div class="form-text">Minimum 1 hours, Maximum 10 hours</div>
                    </div>
                    <div class="mb-3">
                        <label for="breakReason" class="form-label">Reason</label>
                        <textarea class="form-control" id="breakReason" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="saveBreakBtn">Save Break</button>
            </div>
        </div>
    </div>
</div>
<?php 
// This replaces the work order modal section in your main file
?>

<style>
.custom-scroll {
    max-height: 400px;
    overflow-y: auto;
}
.select2-container {
    z-index: 9999 !important;
}
.select2-dropdown {
    z-index: 99999 !important;
}
.spinner-border-sm {
    width: 1rem;
    height: 1rem;
}
.loading-spinner {
    display: none;
    position: absolute;
    right: 25px;
    top: 50%;
    transform: translateY(-50%);
}
.table-select-container {
    position: relative;
}
.form-check-input {
    width: 24px !important;
    height: 24px !important;
    cursor: pointer;
    border: 2px solid #6c757d;
    border-radius: 4px;
    transition: all 0.3s ease;
    margin: 0;
    vertical-align: middle;
}
.form-check-input:hover {
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.15);
    transform: scale(1.1);
}
.form-check-input:checked {
    background-color: #0d6efd;
    border-color: #0d6efd;
    box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}
.form-check-input:focus {
    border-color: #86b7fe;
    outline: 0;
    box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.table > :not(caption) > * > * {
    padding: 0.75rem;
    vertical-align: middle;
}
.table td:last-child,
.table th:last-child {
    width: 30px;
    text-align: center;
}
@media (max-width: 768px) {
    .form-check-input {
        width: 28px !important;
        height: 28px !important;
    }
}
.modal-loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    display: none;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}
.modal-loading-overlay.active {
    display: flex;
}

/* === SORTABLE COLUMNS === */
.sortable {
    cursor: pointer;
    user-select: none;
    position: relative;
    padding-right: 25px !important;
}

.sortable:hover {
    background-color: #e9ecef !important;
}

.sortable::after {
    content: '⇅';
    position: absolute;
    right: 8px;
    opacity: 0.3;
    font-size: 14px;
}

.sortable.asc::after {
    content: '↑';
    opacity: 1;
    color: #0d6efd;
}

.sortable.desc::after {
    content: '↓';
    opacity: 1;
    color: #0d6efd;
}
</style>

<!-- Work Order Modal -->
<div class="modal fade" id="workOrderModal" tabindex="-1" aria-labelledby="workOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="workOrderModalLabel">Work Orders</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body custom-scroll" style="position: relative;">
                <!-- Loading Overlay -->
                <div class="modal-loading-overlay" id="modalLoadingOverlay">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
                
                <form id="workOrderForm">
                    <table class="table table-bordered table-striped" id="workOrderTable">
                        <thead>
                            <tr>
                                <th class="sortable" data-column="work_order_name" data-type="string">WO Number</th>
                                <th class="sortable" data-column="part_number" data-type="string">Part Number</th>
                                <th class="sortable" data-column="part_description" data-type="string">Part Description</th>
                                <th class="sortable" data-column="end_date" data-type="date">Due Date</th>
                                <th class="sortable" data-column="quantity" data-type="number">Qty</th>
                                <th class="sortable" data-column="total_hours" data-type="number">Std Hours</th>
                                <th>Machine</th> 
                                <th>Table</th>
                                <th>Select</th>
                            </tr>
                        </thead>
                        <tbody id="workOrderTableBody">
                            <!-- Content will be loaded via AJAX -->
                            <tr>
                                <td colspan="9" class="text-center">
                                    <div class="spinner-border text-primary" role="status">
                                        <span class="visually-hidden">Loading...</span>
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="showSelectedWorkOrdersBtn">Show Selected</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('body').addClass('sidebar-collapse');

// ─────────────────────────────────────────────────────────────────────────────
// 1. LOAD GANTT ROWS VIA AJAX
// ─────────────────────────────────────────────────────────────────────────────
function loadGanttRows() {
    $('#gantt-rows-container').html(
        '<div style="padding:40px;text-align:center;color:#666;">' +
        '<div class="spinner-border text-primary" role="status"></div>' +
        '<p class="mt-2">Loading schedule...</p></div>'
    );

    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=get_gantt_rows',
        method: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                $('#gantt-rows-container').html(response.html);
                setTimeout(function() {
                    document.querySelectorAll('.gantt-task').forEach(function(t) {
                        t.classList.remove('drag-highlight', 'filter-highlight');
                    });
                    if (document.getElementById('filter_part').value ||
                        document.getElementById('filter_wo').value) {
                        applyFilters();
                    }
                }, 100);
            } else {
                $('#gantt-rows-container').html(
                    '<div class="alert alert-danger m-3">Failed to load: ' + (response.message || 'Unknown error') + '</div>'
                );
            }
        },
        error: function(xhr, status, error) {
            console.error('Gantt load error:', error, xhr.responseText);
            $('#gantt-rows-container').html(
                '<div class="alert alert-danger m-3">Error loading schedule rows.</div>'
            );
        }
    });
}

$(document).ready(function() {
    loadGanttRows();
});

// ─────────────────────────────────────────────────────────────────────────────
// 2. WORK ORDER DETAIL MODAL (delegated — works on AJAX rows)
// ─────────────────────────────────────────────────────────────────────────────
let currentTaskDetails = null;

$(document).on('click', '.gantt-task:not(.break-task):not(.dragging)', function() {
    loadWorkOrderDetails(
        $(this).data('task-id'),
        $(this).data('work-order-id'),
        $(this).data('part-id'),
        $(this).data('current-machine')
    );
});

function loadWorkOrderDetails(taskId, workOrderId, partId, machineId) {
    const modal = new bootstrap.Modal(document.getElementById('workOrderDetailModal'));
    modal.show();
    $('#detailLoadingSpinner').show();
    $('#workOrderDetailContent').hide();
    $('#detailErrorMessage').addClass('d-none');

    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=get_pu_task_details',
        method: 'POST',
        data: { task_id: taskId, work_order_id: workOrderId, part_id: partId, machine_id: machineId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                currentTaskDetails = response.data;
                displayWorkOrderDetails(response.data);
                $('#detailLoadingSpinner').hide();
                $('#workOrderDetailContent').show();
            } else {
                $('#detailLoadingSpinner').hide();
                $('#detailErrorMessage').text(response.message || 'Failed to load details').removeClass('d-none');
            }
        },
        error: function() {
            $('#detailLoadingSpinner').hide();
            $('#detailErrorMessage').removeClass('d-none');
        }
    });
}

function displayWorkOrderDetails(data) {
    $('#detail_wo_no').text(data.work_order_no || '-');
    $('#detail_customer_order').text(data.customer_order_nos || '-');
    $('#detail_wo_name').text(data.work_order_name || '-');
    $('#detail_final_part').text(data.parent_part_number || '-');
    $('#detail_customer_code').text(data.customer_code || '-');
    $('#detail_RefSalesCode').text(data.RefSalesCode || '-');

    const statusBadge = $('#detail_status');
    if (data.is_late) {
        statusBadge.text('Late').removeClass().addClass('badge bg-danger');
    } else {
        statusBadge.text('On Time').removeClass().addClass('badge bg-success');
    }

    $('#detail_part_name').text(data.product_name || '-');
    $('#detail_quantity').text(data.quantity || '-');
    $('#detail_desc').text(data.manufacture_description || '-');
    $('#detail_setup_hours').text(data.setup_hours || '-');
    $('#detail_total_hours').text(data.total_hours || '-');
    $('#detail_due_date').text(data.end_date || '-');
    $('#detail_route_desc').text(data.route_desc || '-');

    // Raw materials
    const materialsDiv = $('#detail_bought_in_materials');
    if (materialsDiv.length) {
        if (data.bought_in_materials && data.bought_in_materials !== 'None') {
            materialsDiv.removeClass('alert-info alert-warning').addClass('alert-success');
            $('#materials_list').html('<strong>' + data.bought_in_materials + '</strong>');
        } else {
            materialsDiv.removeClass('alert-info alert-success').addClass('alert-warning');
            $('#materials_list').html('<em>No bought-in materials required</em>');
        }
    }

    if (data.is_breakdown_affected && data.breakdown_hours > 0) {
        $('#breakdown_info').show();
        $('#detail_breakdown_hours').text(data.breakdown_hours);
    } else {
        $('#breakdown_info').hide();
    }

    $('#detail_start_date').text(data.start_date || '-');
    $('#detail_start_time').text(data.start_time || '-');
    $('#detail_end_date').text(data.end_date || '-');
    $('#detail_shift').text(data.shift_name || '-');

    if (data.is_break == 1 || data.quantity <= 1) {
        $('#splitWorkOrderBtn').hide();
    } else {
        $('#splitWorkOrderBtn').show();
    }
}

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

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

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

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

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

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

// ─────────────────────────────────────────────────────────────────────────────
// 3. DRAG & DROP (delegated — works on AJAX rows)
// ─────────────────────────────────────────────────────────────────────────────
let draggedTask = null;
let highlightedNeighbor = null;

document.addEventListener('dragstart', function(e) {
    const task = e.target.closest('.gantt-task');
    if (!task) return;
    draggedTask = task;
    task.classList.add('dragging');
});

document.addEventListener('dragend', function(e) {
    const task = e.target.closest('.gantt-task');
    if (!task) return;
    task.classList.remove('dragging');
    if (highlightedNeighbor) { highlightedNeighbor.classList.remove('drag-highlight'); highlightedNeighbor = null; }
    draggedTask = null;
});

document.addEventListener('dragover', function(e) {
    const ganttScrollable = document.querySelector('.gantt-scrollable-content');
    if (draggedTask && ganttScrollable) {
        const sr = ganttScrollable.getBoundingClientRect();
        const xPos = e.clientX - sr.left;
        if (xPos < 50) ganttScrollable.scrollLeft -= 20;
        else if (xPos > sr.width - 50) ganttScrollable.scrollLeft += 20;
    }
    const row = e.target.closest('.gantt-row');
    if (!row || !draggedTask) return;
    e.preventDefault();
    row.classList.add('drop-target');
    const dropX = e.clientX - row.getBoundingClientRect().left;
    const otherTasks = [...row.querySelectorAll('.gantt-task')]
        .filter(t => t !== draggedTask)
        .sort((a, b) => parseFloat(a.style.left) - parseFloat(b.style.left));
    if (highlightedNeighbor) { highlightedNeighbor.classList.remove('drag-highlight'); highlightedNeighbor = null; }
    for (let t of otherTasks) {
        if (parseFloat(t.style.left) + parseFloat(t.style.width) < dropX) highlightedNeighbor = t;
        else break;
    }
    if (highlightedNeighbor) highlightedNeighbor.classList.add('drag-highlight');
});

document.addEventListener('dragleave', function(e) {
    const row = e.target.closest('.gantt-row');
    if (!row) return;
    if (!row.contains(e.relatedTarget)) {
        row.classList.remove('drop-target');
        if (highlightedNeighbor) { highlightedNeighbor.classList.remove('drag-highlight'); highlightedNeighbor = null; }
    }
});

document.addEventListener('drop', function(e) {
    const row = e.target.closest('.gantt-row');
    if (!row || !draggedTask) return;
    e.preventDefault();
    row.classList.remove('drop-target');
    if (highlightedNeighbor) { highlightedNeighbor.classList.remove('drag-highlight'); highlightedNeighbor = null; }
    const dropX = e.clientX - row.getBoundingClientRect().left;
    const otherTasks = [...row.querySelectorAll('.gantt-task')]
        .filter(t => t !== draggedTask)
        .sort((a, b) => parseFloat(a.style.left) - parseFloat(b.style.left));
    let leftNeighbor = null;
    for (let t of otherTasks) {
        if (parseFloat(t.style.left) + parseFloat(t.style.width) < dropX) leftNeighbor = t;
        else break;
    }
    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=update_pu_task_priority',
        method: 'POST',
        data: {
            task_id: draggedTask.dataset.taskId, new_machine_id: row.dataset.machineId,
            part_id: draggedTask.dataset.partId, work_order_id: draggedTask.dataset.workOrderId,
            left_neighbor_priority: leftNeighbor ? leftNeighbor.dataset.priority : null,
            left_neighbor_task_id: leftNeighbor ? leftNeighbor.dataset.taskId : null,
            new_position: dropX
        },
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') { loadGanttRows(); }
            else { alert('Error updating task: ' + response.message); }
        },
        error: function(xhr, status, error) { alert('Error updating task: ' + error); }
    });
});

// ─────────────────────────────────────────────────────────────────────────────
// 4. FILTERS
// ─────────────────────────────────────────────────────────────────────────────
function applyFilters() {
    const partFilter = document.getElementById('filter_part').value.trim().toLowerCase();
    const woFilter   = document.getElementById('filter_wo').value.trim().toLowerCase();

    const tasks = document.querySelectorAll('.gantt-task');
    if (!partFilter && !woFilter) {
        tasks.forEach(t => t.classList.remove('filter-highlight'));
        document.querySelectorAll('.gantt-labels .card').forEach(c => {
            c.style.outline = ''; c.style.boxShadow = ''; c.style.backgroundColor = '';
        });
        return;
    }

    const matchedMachineIds = new Set();
    tasks.forEach(function(task) {
        const part = (task.dataset.part || '').toLowerCase();
        const wo   = (task.dataset.wo   || '').toLowerCase();
        let match  = true;
        if (partFilter && !part.includes(partFilter)) match = false;
        if (woFilter   && !wo.includes(woFilter))     match = false;
        if (match) {
            task.classList.add('filter-highlight');
            const row = task.closest('.gantt-row');
            if (row && row.dataset.machineId) matchedMachineIds.add(row.dataset.machineId);
        } else {
            task.classList.remove('filter-highlight');
        }
    });

    document.querySelectorAll('.machine-section').forEach(function(section) {
        const card = section.querySelector('.card');
        if (!card) return;
        const machineId = section.dataset.machineId;
        if (matchedMachineIds.has(machineId)) {
            card.style.outline = '3px solid #f5c518';
            card.style.boxShadow = '0 0 12px rgba(245,197,24,0.8)';
            card.style.backgroundColor = '#fffbe6';
        } else {
            card.style.outline = ''; card.style.boxShadow = ''; card.style.backgroundColor = '';
        }
    });
}

// ─────────────────────────────────────────────────────────────────────────────
// 5. ADD BREAK
// ─────────────────────────────────────────────────────────────────────────────
document.getElementById('addBreakBtn').addEventListener('click', function() {
    new bootstrap.Modal(document.getElementById('breakModal')).show();
});

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

// ─────────────────────────────────────────────────────────────────────────────
// 6. BREAKDOWN START / STOP
// ─────────────────────────────────────────────────────────────────────────────
document.getElementById('startBreakdownBtn').addEventListener('click', function() {
    new bootstrap.Modal(document.getElementById('startBreakdownModal')).show();
});
document.getElementById('stopBreakdownBtn').addEventListener('click', function() {
    new bootstrap.Modal(document.getElementById('stopBreakdownModal')).show();
});
$('#startBreakdownModal').on('show.bs.modal', function() { document.getElementById('startBreakdownForm').reset(); });

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

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

setInterval(function() {
    $.ajax({ url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=get_machine_breakdown_status', method: 'GET', dataType: 'json', success: function(r) { console.log('Breakdown status', r); } });
}, 120000);

// ─────────────────────────────────────────────────────────────────────────────
// 7. WORK ORDERS LIST MODAL
// ─────────────────────────────────────────────────────────────────────────────
$('#workOrderModal').on('show.bs.modal', loadWorkOrders);
$('#workOrderModal').on('hidden.bs.modal', function() {
    $('#workOrderTableBody').html('');
    $('#modalLoadingOverlay').removeClass('active');
    $('#showSelectedWorkOrdersBtn').prop('disabled', false);
});

function loadWorkOrders() {
    $('#modalLoadingOverlay').addClass('active');
    $('#workOrderTableBody').html('<tr><td colspan="9" class="text-center"><div class="spinner-border text-primary" role="status"></div></td></tr>');
    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=get_work_orders',
        method: 'GET', dataType: 'json',
        success: function(response) {
            $('#modalLoadingOverlay').removeClass('active');
            if (response.success && response.data.length > 0) {
                renderWorkOrders(response.data);
            } else {
                $('#workOrderTableBody').html('<tr><td colspan="9" class="text-center">No work orders found</td></tr>');
            }
        },
        error: function() {
            $('#modalLoadingOverlay').removeClass('active');
            $('#workOrderTableBody').html('<tr><td colspan="9" class="text-center text-danger">Error loading work orders.</td></tr>');
        }
    });
}

function renderWorkOrders(workOrders) {
    let html = '';
    workOrders.forEach(function(wo) {
        html += '<tr data-part-id="' + wo.part_id + '" data-wo-id="' + wo.work_order_id + '">' +
            '<td>' + (wo.work_order_name || '-') + '</td>' +
            '<td>' + (wo.part_number || '-') + '</td>' +
            '<td>' + (wo.part_description || '-') + '</td>' +
            '<td>' + (wo.end_date || '-') + '</td>' +
            '<td>' + (wo.quantity || '-') + '</td>' +
            '<td>' + (wo.total_hours || '-') + '</td>' +
            '<td>' + wo.machine_dropdown + '</td>' +
            '<td>' + wo.table_dropdown + '</td>' +
            '<td><input class="form-check-input" type="checkbox" name="workOrder[]" value="' + wo.work_order_id + '" data-machine-id="' + wo.machine_id + '" data-id="' + wo.id + '"></td>' +
            '</tr>';
    });
    $('#workOrderTableBody').html(html);
    $('.select2').select2({ dropdownParent: $('#workOrderModal'), width: '100%' });
    attachMachineChangeHandlers();
    initTableSort();
}

function attachMachineChangeHandlers() {
    $('#workOrderTableBody').off('change', '.machine-select').on('change', '.machine-select', function() {
        const machineId = $(this).val();
        const rowId = $(this).attr('id').replace('machinee_id_', '');
        updateTableDropdown(machineId, 'machine_table_id_' + rowId, 'spinner_' + rowId);
    });
}

function updateTableDropdown(machineId, tableSelectId, spinnerId) {
    const $tableSelect = $('#' + tableSelectId);
    const $spinner = $('#' + spinnerId);
    if (!machineId) { $tableSelect.html('<option value="">Please Select</option>'); return; }
    if ($spinner.length) $spinner.show();
    $tableSelect.prop('disabled', true);
    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=get_tables_by_machine',
        method: 'POST', dataType: 'json', data: { machine_id: machineId },
        success: function(data) {
            let options = '<option value="">Please Select</option>';
            if (data.success && data.tables) {
                $.each(data.tables, function(key, value) {
                    options += '<option value="' + key + '">' + value + '</option>';
                });
            }
            $tableSelect.html(options);
            if ($tableSelect.hasClass('select2-hidden-accessible')) $tableSelect.select2('destroy');
            $tableSelect.select2({ dropdownParent: $('#workOrderModal'), width: '100%' });
        },
        error: function() { $tableSelect.html('<option value="">Error loading tables</option>'); },
        complete: function() { if ($spinner.length) $spinner.hide(); $tableSelect.prop('disabled', false); }
    });
}

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

$('#showSelectedWorkOrdersBtn').on('click', showSelectedWorkOrders);

function showSelectedWorkOrders() {
    const workOrders = [];
    let validationFailed = false;
    $('input[name="workOrder[]"]:checked').each(function() {
        const dbId = $(this).data('id');
        const machineId = $('#machine_table_id_' + dbId).val();
        if (!machineId) { validationFailed = true; return false; }
        workOrders.push({
            id: dbId, work_order_id: $(this).val(),
            part_id: $(this).closest('tr').data('part-id'), machine_id: machineId
        });
    });
    if (validationFailed) { alert('Please select a table for all selected work orders.'); return; }
    if (!workOrders.length) { alert('Please select at least one work order.'); return; }
    $('#modalLoadingOverlay').addClass('active');
    $('#showSelectedWorkOrdersBtn').prop('disabled', true);
    $.ajax({
        url: site_url + '/modules/machines_management/index.php?page=ajax_actions_for_pu&action=select_order_for_pu',
        method: 'POST', data: { work_orders: JSON.stringify(workOrders) }, dataType: 'json',
        success: function(response) {
            if (response.status === 'success') { alert('Work orders submitted successfully!'); $('#workOrderModal').modal('hide'); loadGanttRows(); }
            else { alert('Error: ' + (response.message || 'Failed to submit')); }
        },
        error: function() { alert('Error submitting work orders.'); },
        complete: function() { $('#modalLoadingOverlay').removeClass('active'); $('#showSelectedWorkOrdersBtn').prop('disabled', false); }
    });
}
</script>
</div>