<?php
markBreakdownAffectedWorkOrders($conn, 45, '2025-10-22 16:31:00', $breakdownEnd);

function markBreakdownAffectedWorkOrders($conn, $machineId, $breakdownStart, $breakdownEnd = null) {
    // Use breakdownEnd or fallback to current timestamp for ongoing breakdown
    $endCondition = $breakdownEnd ? "'$breakdownEnd'" : "NOW()";

    // Find overlapping tasks on this machine
    echo $overlapQuery = "
        SELECT id, start_date, end_date
        FROM vac_machine_table
        WHERE machine_id = $machineId
          AND is_break = 0
          AND start_date < $endCondition
          AND end_date > '$breakdownStart'
    ";

    $overlapResult = mysqli_query($conn, $overlapQuery);
    $affectedCount = 0;

    while ($row = mysqli_fetch_assoc($overlapResult)) {
        $taskId = $row['id'];
        mysqli_query($conn, "
            UPDATE vac_machine_table 
            SET is_breakdown_affected = 1
            WHERE id = $taskId
        ");
        $affectedCount++;
    }

    echo "<br>⚙️ Marked $affectedCount overlapping work orders as breakdown-affected for Machine #$machineId<br>";
}

function recalculateMachineDatesforvac($conn, $machineId) {
    set_time_limit(300); // Avoid timeout

    // Load shifts grouped by day
    $shiftsByDay = [];
    $shiftResult = mysqli_query($conn, "SELECT * FROM working_hours");
    while ($row = mysqli_fetch_assoc($shiftResult)) {
        $day = (int)$row['day_shifts'];
        $shiftsByDay[$day][] = $row;
    }

    // Get current date
    $currentDateStr = date('Y-m-d');
    $tasks = [];

    // Get tasks (with setting_instruction column)
   $taskResult = mysqli_query($conn,
    "SELECT 
        v.id, 
        v.is_break, 
		v.is_breakdown_affected, 
		v.breakdown_hours, 
        v.total_hours_update AS hours_to_schedule, 
		v.total_hours AS hours,
        v.setting_instruction
     FROM vac_machine_table v
     LEFT JOIN manufacture_machine_table m
       ON v.work_order_id = m.work_order_id
      AND v.part_id = m.part_id
    WHERE v.machine_id = $machineId
  AND (v.end_date >= '$currentDateStr' OR v.is_breakdown_affected = 1)

     ORDER BY v.priority"
);

$tasks = [];
while ($row = mysqli_fetch_assoc($taskResult)) {
    $tasks[] = $row;
}


    // Start scheduling from now
    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');
    $previous_setting_instruction = null; // track last instruction

 foreach ($tasks as $task) {
    $total_hours = (float)$task['hours_to_schedule']; // cast once
    $setting_instruction = $task['setting_instruction'];
    $is_break = (int)$task['is_break'];
	$breakdown_hours = (float)$task['breakdown_hours'];

    $setup_hours = 0.00; // default

    if ($is_break === 1) {
        $total_hours = (float)$task['hours']; 
        $setup_hours = 0.00;
    } else {
        // Normal task → apply setup logic
        if ($previous_setting_instruction !== null) {
            if (strcasecmp($previous_setting_instruction, $setting_instruction) === 0) {
                $setup_hours = 1.00;
            } else {
                $setup_hours = 2.00;
            }
        } else {
            $setup_hours = 2.00; // first task in the sequence
        }
        $total_hours = (float)($total_hours + $setup_hours + $breakdown_hours);
// add setup to scheduling time
    }

    $hoursRemaining = $total_hours;
        $dateHoursMap = [];
        $taskStartTime = null;
        $taskEndTime = null;
        $firstShiftUsed = null;

        while ($hoursRemaining > 0) {
            $currentDate = date('Y-m-d', $currentDateTime);
            $dayOfWeek = date('w', $currentDateTime);

            if (!isset($shiftsByDay[$dayOfWeek])) {
                $currentDateTime = strtotime($currentDate . ' +1 day');
                continue;
            }

            foreach ($shiftsByDay[$dayOfWeek] as $shift) {
                $shiftStart = strtotime($currentDate . ' ' . $shift['start_time']);
                $shiftEnd   = strtotime($currentDate . ' ' . $shift['end_time']);
                $shiftName  = $shift['shift_name'];

                // Skip if this shift is already passed
                if ($shiftEnd <= $currentDateTime) continue;

                // Clamp start to now if mid-shift
                $actualStart = max($currentDateTime, $shiftStart);
                $availableSeconds = max(0, $shiftEnd - $actualStart);
                $availableHours = $availableSeconds / 3600;

                if ($availableHours <= 0) continue;

                $allocatable = min($hoursRemaining, $availableHours);

                if (!$taskStartTime) {
                    $taskStartTime = $actualStart;
                    $firstShiftUsed = $shiftName;
                }

                $taskEndTime = $actualStart + ($allocatable * 3600);
                $hoursRemaining -= $allocatable;

                // Add to map
                $dateOnly = date('Y-m-d', $actualStart);
                if (!isset($dateHoursMap[$dateOnly])) {
                    $dateHoursMap[$dateOnly] = 0;
                }
                $dateHoursMap[$dateOnly] += $allocatable;

                // Update current pointer
                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

            if ($hoursRemaining > 0) {
                // Move to next day 00:00
                $currentDateTime = strtotime(date('Y-m-d', $currentDateTime) . ' +1 day 00:00:00');
            }
        }

        // Format remaining_hours like "2025-07-03=2,2025-07-04=6"
        $remainingHoursStr = '';
        foreach ($dateHoursMap as $date => $hrs) {
            $remainingHoursStr .= $date . '=' . round($hrs, 2) . ',';
        }
        $remainingHoursStr = rtrim($remainingHoursStr, ',');

        // Save formatted times
        $startStr = date('Y-m-d H:i:s', $taskStartTime);
        $endStr   = date('Y-m-d H:i:s', $taskEndTime);

        // Update DB (make sure vac_machine_table has `setup_hours` column)
        $query = "UPDATE vac_machine_table SET 
            start_date = '$startStr',
            end_date = '$endStr',
            shift_ids = '$firstShiftUsed',
            remaing_hours = '$remainingHoursStr',
            setup_hours = $setup_hours, total_hours = $total_hours
            WHERE id = {$task['id']}";
        mysqli_query($conn, $query);

        // Track last instruction for next loop
        $previous_setting_instruction = $setting_instruction;
    }
}
//error_reporting(E_ALL);
//ini_set('display_errors',1);
$today = date('Y-m-d');

// Update remaining hours for ongoing tasks
$query = "
    SELECT id, remaing_hours, total_hours
    FROM vac_machine_table
    WHERE DATE(start_date) < '$today'
      AND DATE(end_date) >= '$today'
";
$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['id'];
    $remaingHoursStr = $row['remaing_hours'];
    $totalHours = $row['total_hours'];

    $newRemaingStrParts = [];
    $pastHours = 0;

    $dayHourPairs = explode(',', $remaingHoursStr);
    foreach ($dayHourPairs as $pair) {
        if (strpos($pair, '=') !== false) {
            list($date, $hours) = explode('=', $pair);
            if (strtotime($date) < strtotime($today)) {
                $pastHours += floatval($hours);
            } else {
                $newRemaingStrParts[] = "$date=$hours";
            }
        }
    }

    $updatedRemaingStr = implode(',', $newRemaingStrParts);
    $updatedTotalHours = max(0, $totalHours - $pastHours);

    $updateSql = "
        UPDATE vac_machine_table
        SET 
            remaing_hours = '$updatedRemaingStr',
            total_hours_update = '$updatedTotalHours',
            total_hours = '$updatedTotalHours'
        WHERE id = $id
    ";
    mysqli_query($conn, $updateSql);
}

// Handle machine breakdowns - update affected work orders
handleMachineBreakdowns($conn);

function handleMachineBreakdowns($conn) {
    //date_default_timezone_set('Asia/Kolkata'); // ensure Indian time zone
    $currentTime = date('Y-m-d H:i:s');

    // Fetch all breakdowns that have started
    $breakdownQuery = "
        SELECT mb.*, sdt.resource_code 
        FROM machine_breakdown mb
        JOIN station_detail_table sdt 
            ON mb.machine_id = sdt.id
        WHERE mb.breakdown_start <= '$currentTime'
    ";

    $breakdownResult = mysqli_query($conn, $breakdownQuery);

    if (!$breakdownResult) {
        echo "❌ Breakdown query failed: " . mysqli_error($conn);
        return;
    }

    while ($breakdown = mysqli_fetch_assoc($breakdownResult)) {
        $machineId        = (int)$breakdown['machine_id'];
        $breakdownId      = (int)$breakdown['id'];
        $lastUpdate       = $breakdown['updated_at'];
        $isActive         = (int)$breakdown['is_active'];
        $breakdownEnd     = $breakdown['breakdown_end'];
        $existingHours    = (float)$breakdown['breakdown_hours'];
		echo "<br>";
       echo $hoursSinceUpdate = max(0, (strtotime($currentTime) - strtotime($lastUpdate)) / 3600);

        // 🔴 CASE 1: Breakdown is ACTIVE
        if ($isActive === 1) {

            if ($hoursSinceUpdate > 0) {
                // Increment breakdown total hours
                $newBreakdownHours = $existingHours + $hoursSinceUpdate;

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

            // Update only the tasks already flagged as affected
            $affectedTasksQuery = "
                SELECT id, total_hours,setup_hours,total_hours_update, breakdown_hours 
                FROM vac_machine_table 
                WHERE machine_id = $machineId 
                  AND is_breakdown_affected = 1
                  AND is_break = 0
            ";

            $tasksResult = mysqli_query($conn, $affectedTasksQuery);
            if ($tasksResult && mysqli_num_rows($tasksResult) > 0) {
                while ($task = mysqli_fetch_assoc($tasksResult)) {
                    $taskId = (int)$task['id'];
                    $prevBreakdownHrs = (float)$task['breakdown_hours'];
                    $prevTotalHrs     = (float)$task['total_hours']; 
					$prevTotalHrs_1     = (float)$task['setup_hours']; 
					$prevTotalHrs_2   = (float)$task['total_hours_update'];

                    $newBreakdownTaskHours = $prevBreakdownHrs + $hoursSinceUpdate;
                    $newTotalHours = $prevTotalHrs_1 + $prevBreakdownHrs+ $prevTotalHrs_2;

                 echo   $updateQuery = "
                        UPDATE vac_machine_table 
                        SET total_hours = $newTotalHours,
                            breakdown_hours = $newBreakdownTaskHours
                        WHERE id = $taskId
                    ";
                    mysqli_query($conn, $updateQuery);

                    echo "<br>🔧 Updated Task #$taskId on Machine #$machineId with +$hoursSinceUpdate hr(s) breakdown<br>";
                }

                // Recalculate schedule once after updating all affected tasks
                recalculateMachineDatesforvac($conn, $machineId);
            }

        } 
        // 🟢 CASE 2: Breakdown has ENDED
        else if ($isActive === 0 && !empty($breakdownEnd) && strtotime($breakdownEnd) <= strtotime($currentTime)) {

            // Reset all affected tasks on this machine
            $resetQuery = "
                UPDATE vac_machine_table 
                SET is_breakdown_affected = 0
                WHERE machine_id = $machineId
                  AND is_breakdown_affected = 1
            ";
            mysqli_query($conn, $resetQuery);

            echo "<br>✅ Breakdown ended for Machine #$machineId — affected tasks reset<br>";

            // Recalculate machine schedule after breakdown end
            recalculateMachineDatesforvac($conn, $machineId);
        }
    }
}



?>
<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');

// Generate current and adjacent months
$monthsToShow = [];
$currentDate = new DateTime(); // Today's date
for ($i = 0; $i < 3; $i++) {  // Today + next 2 months
    $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');

// Fetch tasks from database
$workOrders = [];
$tasks = [];

$query = "SELECT 
    mmt.machine_id AS task, 
    mmt.id as task_id, 
    wo.work_order_no, 
    mmt.part_id,
    mmt.setup_hours, 
    mmt.setting_instruction, 
    mmt.priority,
    mmt.total_hours AS hours_to_schedule,
    mmt.total_hours, 
    mmt.work_order_id,
    mmt.product_name,
    mmt.quantity,
    mmt.set_id, 
    mmt.set_part, 
    won.work_order_name, 
    mmt.parent_ids, 
    mmt.shift_ids AS shift_name, 
    DATE(mmt.start_date) AS start_date, 
    DATE(mmt.end_date) AS end_date,
    TIME(mmt.start_date) AS start_time,
    mmt.is_break,
    mmt.break_reason,
    mmt.is_breakdown_affected,
    mmt.breakdown_hours,
    mb.id as breakdown_id,
    mb.breakdown_reason as machine_breakdown_reason
FROM 
    vac_machine_table mmt
LEFT JOIN 
    work_order wo ON mmt.work_order_id = wo.id
LEFT JOIN 
    work_order_name won ON mmt.work_order_id = won.work_order_id AND mmt.part_id = won.part_id
LEFT JOIN 
    machine_breakdown mb ON mmt.machine_id = mb.machine_id AND mb.is_active = 1
WHERE 
    mmt.end_date >= '$currentDateStr' 
ORDER BY 
    mmt.priority, mmt.machine_id"; // Removed table_id from order
    
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    // Check if this task's start date is after the manufacture end date
    $part_id = $row['part_id'];
	$parent_ids = $row['parent_ids'];
    $work_order_id = $row['work_order_id'];
    
    // Get manufacture end date for this part and work order
     $manufactureQuery = "SELECT start_date FROM manufacture_machine_table 
                        WHERE part_id = '$parent_ids' AND work_order_id = '$work_order_id'
                        ORDER BY start_date DESC LIMIT 1";
    $manufactureResult = mysqli_query($conn, $manufactureQuery);
    
    $isLate = false;
    if ($manufactureResult && mysqli_num_rows($manufactureResult) > 0) {
        $manufactureData = mysqli_fetch_assoc($manufactureResult);
        $manufactureEndDate = $manufactureData['start_date'];
        
        if ($row['end_date'] > $manufactureEndDate) {
            $isLate = true;
        }
    }
    
     $row['is_late'] = $isLate;
    $tasks[] = $row;
    
    if (!in_array($row['work_order_no'], array_column($workOrders, 'work_order_no'))) {
        $workOrders[] = ['work_order_no' => $row['work_order_no'], 'part_id' => $row['part_id']];
    }
}

// Get shifts with hours
$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'];
        $startTime = $row['start_time'];
        $endTime = $row['end_time'];
        $dayIndex = (int)$row['day_shifts'];
        $hours = (float)$row['hours'];

        $shifts[] = $shiftName;
        $shiftHours[$shiftName] = $hours;
        $shiftDays[$shiftName] = $dayMap[$dayIndex];
        $shiftTimes[$shiftName] = [
            'start' => $startTime,
            'end' => $endTime,
            'hours' => $hours
        ];
    }
}

// Function to generate time intervals for a shift
function generateTimeIntervals($startTime, $endTime) {
    $intervals = [];
    $current = new DateTime($startTime);
    $end = new DateTime($endTime);
    
    // Add first interval
    $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'));
    }
    
    // Handle any remaining time
    if ($intervalStart !== $end->format('H:i')) {
        $intervals[] = [
            'start' => $intervalStart,
            'end' => $end->format('H:i'),
            'minutes' => (strtotime($end->format('H:i')) - strtotime($intervalStart)) / 60
        ];
    }
    
    return $intervals;
}

// Simplified priority-based scheduling
function scheduleByPriority($tasks) {
    // Sort tasks by priority
    usort($tasks, function($a, $b) {
        return $a['priority'] <=> $b['priority'];
    });
    
    $scheduledTasks = [];
    $machineAllocations = []; // Track allocated time per machine
    
    foreach ($tasks as $task) {
        $machineId = $task['task'];
        $key = $machineId;
        
        // Initialize if not exists
        if (!isset($machineAllocations[$key])) {
            $machineAllocations[$key] = [
                'current_time' => 0,
                'tasks' => []
            ];
        }
        
        // Create scheduled task
        $scheduledTask = [
            'task' => $task['task'], 
            'is_late' => $task['is_late'], 
            'task_id' => $task['task_id'],
            'setting_instruction' => $task['setting_instruction'],
            'allocated_hours' => $task['hours_to_schedule'],
            'start_datetime' => '',
            'end_datetime' => '',
            'work_order_id' => $task['work_order_id'],
            'part_id' => $task['part_id'],
            'setup_hours' => $task['setup_hours'],
            'work_order_no' => $task['work_order_no'],
            'product_name' => $task['product_name'],
            'quantity' => $task['quantity'],
            'work_order_name' => $task['work_order_name'],
            'set_id' => $task['set_id'],
            'parent_ids' => $task['parent_ids'],
            'is_break' => $task['is_break'],
            'break_reason' => $task['break_reason'],
            'shift_name' => $task['shift_name'],
            'priority' => $task['priority'],
            'is_breakdown_affected' => $task['is_breakdown_affected'],
            'breakdown_hours' => $task['breakdown_hours'],
            'has_breakdown' => $hasBreakdown,
            'breakdown_reason' => $hasBreakdown ? $activeBreakdowns[$machineId] : '',
            'position' => $machineAllocations[$key]['current_time']
        ];
        
        $machineAllocations[$key]['tasks'][] = $scheduledTask;
        $machineAllocations[$key]['current_time'] += $task['hours_to_schedule'];
    }
    
    // Flatten the scheduled tasks
    foreach ($machineAllocations as $allocations) {
        $scheduledTasks = array_merge($scheduledTasks, $allocations['tasks']);
    }
    
    return $scheduledTasks;
}

// Schedule all tasks by priority
$distributedTasks = scheduleByPriority($tasks);
$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'];
}

// Group tasks by machine
$groupedTasks = [];
foreach ($distributedTasks as $task) {
    $groupKey = $task['task'];
    if (!isset($groupedTasks[$groupKey])) {
        $groupedTasks[$groupKey] = [];
    }
    $groupedTasks[$groupKey][] = $task;
}

// Get machine names
$machineQuery = mysqli_query($conn, "SELECT id, resource_code FROM station_detail_table WHERE machine_type = 1");
$taskNames = [];
while ($row = mysqli_fetch_assoc($machineQuery)) {
    $taskNames[$row['id']] = $row['resource_code'];
}

// Calendar generator - starts from today's date
function generateCalendar($month, $year, $shifts, $shiftDays, $shiftTimes) {
    $calendar = [];
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $validWeekdays = array_unique(array_values($shiftDays));
    
    // Get today's date
    $today = new DateTime();
    $currentYear = (int)$today->format('Y');
    $currentMonth = (int)$today->format('m');
    $currentDay = (int)$today->format('d');

    // If this is the current month, start from today
    $startDay = ($year == $currentYear && $month == $currentMonth) ? $currentDay : 1;

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

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

    return $calendar;
}

// Generate calendar days for all months
$calendarDays = [];
foreach ($monthsToShow as $m) {
    $calendarDays = array_merge(
        $calendarDays,
        generateCalendar($m['month'], $m['year'], $shifts, $shiftDays, $shiftTimes)
    );
}

// Calculate total width needed for the grid and day positions
$totalWidth = 0;
$dayPositions = [];
$dayWidths = [];
$dayMinutes = [];
foreach ($calendarDays as $index => $day) {
    $dayWidth = count($day['intervals']) * 40;
    $dayPositions[$day['date'] . '-' . $day['shift']] = $totalWidth;
    $dayWidths[$day['date'] . '-' . $day['shift']] = $dayWidth;
    $dayMinutes[$day['date'] . '-' . $day['shift']] = $day['total_minutes'];
    $totalWidth += $dayWidth;
}

// Machine colors
$machineColors = [];
$colorPalette = [
    '#e6f5f5', '#f5e6f5', '#e6ffe6', '#fff2e6', '#f0e6ff', 
    '#e6ffff', '#ffe6f2', '#f5f5e6', '#e6f5f5', '#f5e6ff',
    '#e6ffec', '#fff0e6', '#e6f0ff', '#ffe6ff', '#e6ffe6',
    '#f5e6e6', '#e6e6f5', '#f5f5e6', '#e6f5f5', '#f5e6f5'
];
$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>
        /* Your existing CSS styles remain the same */
        :root {
            --primary-color: #3498db;
            --secondary-color: #2c3e50;
            --accent-color: #e74c3c;
            --light-bg: #f8f9fa;
            --dark-bg: #343a40;
            --success-color: #2ecc71;
            --warning-color: #f39c12;
            --danger-color: #e74c3c;
            --info-color: #3498db;
            --current-time-color: #e74c3c;
            --time-marker-color: #fff3cd;
            --shift-highlight: #d4edda;
            --time-interval-width: 40px;
            --task-bar-height: 130px;
            --grid-line-color: rgba(0, 0, 0, 0.1);
        }

        .gantt-container {
            position: relative;
            width: 100%;
            overflow-x: auto;
            margin-top: 20px;
            display: flex;
            background-color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-radius: 8px;
        }

        .gantt-labels {
            position: sticky;
            left: 0;
            top: 0;
            width: 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: 0.9rem;
            transform: rotate(-45deg);
            transform-origin: left center;
            white-space: nowrap;
            left: 0%;
            bottom: -15px;
            color: #000;
        }

        .gantt-row {
            display: block;
            border-bottom: 1px solid #000;
            min-height: var(--task-bar-height);
            position: relative;
            white-space: nowrap;
            background-image: linear-gradient(to right, var(--grid-line-color) 1px, transparent 1px);
            background-size: var(--time-interval-width) 1px;
            background-position: left center;
        }

        .gantt-task {
            position: absolute;
            height: 100%;
            top: 0;
            background: #3498db;
            color: white;
            text-align: center;
            border-radius: 5px;
            padding: 5px;
            line-height: 1.2;
            font-size: 12px;
            cursor: grab;
            transition: background-color 0.3s ease;
            box-shadow: 1px 1px 3px rgba(0,0,0,0.2);
            z-index: 1;
            overflow: hidden;
            box-sizing: border-box;
        }

        .gantt-task .task-content {
            padding: 3px;
            font-size: 10px;
            height: calc(100% - 20px);
            overflow: hidden;
        }

        .gantt-task .task-hours {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0,0,0,0.2);
            text-align: center;
            font-size: 9px;
            padding: 1px 0;
            border-radius: 0 0 4px 4px;
        }

        .task-color-1 { background-color: #FFA500; }
        .task-color-2 { background-color: #32CD32; }
        .task-color-3 { background-color: #ff6b6b; }
        .task-color-4 { background-color: #3498db; }

        .no-tasks {
            color: #999;
            font-style: italic;
            padding: 10px;
            text-align: center;
            width: 100%;
        }
		
	

        .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;
        }
		
		
		

        .dot-indicator {
            position: absolute;
            top: 3px;
            right: 3px;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 3px solid black;
        }

        .green-dot-indicator {
            background-color: #00cc66;
        }

        .red-dot-indicator {
            background-color: #ff3333;
        }

        .blue-dot-indicator {
            background-color: #3399ff;
        }
        
        .hour-indicator {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            font-size: 0.65rem;
            text-align: center;
            background: rgba(0,0,0,0.15);
            padding: 1px 0;
            border-radius: 0 0 4px 4px;
        }

        .machine-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .circle-button {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 20px;
            height: 20px;
            border: none;
            border-radius: 50%;
            background-color: #4CAF50;
            cursor: pointer;
            z-index: 10;
        }

        .controls {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .machine-section {
            margin-bottom: 15px;
        }

        .card {
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: transform 0.2s;
        }

        .card:hover {
            transform: translateY(-2px);
        }

        .card-header {
            font-weight: 500;
            padding: 8px 12px;
        }

        .form-control {
            font-size: 0.85rem;
            padding: 0.25rem 0.5rem;
        }

        .gantt-task.dragging {
            opacity: 0.5;
            background-color: #f39c12;
        }
       
        .gantt-row.drop-target {
            outline: 2px dashed #007bff;
            background-color: #e6f7ff;
        }

        .gantt-day.today {
            background-color: #fff3cd;
            box-shadow: 0 0 0 2px #ffc107;
        }

        .gantt-day.today strong {
            background-color: #ffc107;
            color: #000;
            font-weight: bold;
        }

        .current-time-marker {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 2px;
            background-color: var(--current-time-color);
            z-index: 10;
        }

        .current-time-marker::after {
            content: '';
            position: absolute;
            top: 0;
            left: -4px;
            width: 10px;
            height: 10px;
            background-color: var(--current-time-color);
            border-radius: 50%;
        }
        .gantt-task {
            border-right: 3px solid rgba(255, 255, 255, 0.5);
            box-sizing: border-box;
        }
        .gantt-task.highlight-border {
            border-right: 100px solid rgba(255, 255, 0, 0.8) !important;
            box-shadow: 0 0 10px rgba(255, 255, 0, 0.5);
            transition: all 0.3s ease;
        }
        .break-task {
            background-color: #999 !important;
            border-left: 3px dashed #fff !important;
            border-right: 3px dashed #fff !important;
            color: #fff !important;
        }
    </style>
<style>
    /* Add this new style for late tasks */
    .gantt-task.late-task {
        background-color: #ff6b6b !important;
        border-left: 3px solid #ff0000 !important;
        border-right: 3px solid #ff0000 !important;
    }
</style>
<style>
    
/* Modal styles */
.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;   /* modal body height */
    overflow-y: auto;    /* scroll after 300px*/
}

</style>
<style>
    /* Add this new style for late tasks */
    .gantt-task.late-task {
        background-color: #ff6b6b !important;
        border-left: 3px solid #ff0000 !important;
        border-right: 3px solid #ff0000 !important;
    }
    
    /* Add this for on-time tasks (green) */
    .gantt-task.on-time-task {
        background-color: #78c679 !important;
        border-left: 3px solid #2ecc71 !important;
        border-right: 3px solid #2ecc71 !important;
    }
    
    /* Ensure break tasks maintain their style */
    .gantt-task.break-task {
        background-color: #999 !important;
        border-left: 3px dashed #fff !important;
        border-right: 3px dashed #fff !important;
        color: #fff !important;
    }
</style>
    <div class="container-fluid">
        <div class="controls">
            <div class="row">
                <div class="col-md-6">
                    <h3><i class="fas fa-calendar-day me-2"></i>VAC Gantt Chart</h3>
                    <h4><?php echo date('l, F j, Y'); ?></h4>
                </div>
                <div class="col-md-6 text-end">   
 <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"></i> Show Work Orders
    </button>				
                    <button class="btn btn-primary" onclick="window.location.reload()">
                        <i class="fas fa-sync-alt me-2"></i>Refresh
                    </button>
                    <button class="btn btn-warning ms-2" id="addBreakBtn">
                        <i class="fas fa-clock me-2"></i>Add Break
                    </button>
					   <button class="btn btn-danger ms-2" id="addBreakdownBtn">
                        <i class="fas fa-exclamation-triangle me-2"></i>Machine Breakdown
                    </button>
                </div>
            </div>
        </div>

        <div class="gantt-container">
            <!-- Machines Section -->
            <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;">
                            <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>
                                        <div style="display: flex; justify-content: center; align-items: center; height: 100%; font-weight: bold;">
                                            <?php echo $taskName; ?>
                                            <?php if ($hasBreakdown): ?>
                                                <br/><small style="color: #ff0000; font-size: 10px;">BREAKDOWN</small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php 
                        endif;
                    endforeach; ?>
                </div>
            </div>
            
       

            <div class="gantt-scrollable-content">
                <div class="gantt-grid">
                    <!-- Time Slots 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 -->
                    <?php foreach ($taskNames as $machineId => $taskName): 
                        $groupKey = $machineId;
                        $rowColor = $machineColors[$machineId];
                    ?>
                        <div class="gantt-row" 
                             data-machine-id="<?php echo $machineId; ?>"  
                             style="background-color: <?php echo $rowColor; ?>;">
                            
                            <?php if (isset($groupedTasks[$groupKey])): ?>
                                <?php 
                                $cumulativePosition = 0; // Track cumulative position for this machine
                                foreach ($groupedTasks[$groupKey] as $task): 
                                    // Calculate width based on hours (40px per hour)
                                    $taskWidth = $task['allocated_hours'] * 80;
                                    $leftPosition = $cumulativePosition;
                                    $cumulativePosition += $taskWidth;
                                    
                                    $part_id = $task["part_id"];
                                    $work_order_id = $task["work_order_id"];
                                    $set_id = $task["set_id"];
                                    $parent_ids = $task["parent_ids"]; 
									$setup_hours = $task["setup_hours"];
									$part_name = $task["product_name"];
									$quantity = $task["quantity"];
                                    
                                    $sql_for_raw_material = "SELECT work_order_no FROM work_order_customer_ref_mapping WHERE work_order_id = '$work_order_id'";
                                    $result_for_raw_material = mysqli_query($conn, $sql_for_raw_material);
                                    $work_order_nos = [];
                                    
                                    if ($result_for_raw_material) {
                                        while ($row = mysqli_fetch_assoc($result_for_raw_material)) {
                                            $work_order_nos[] = $row['work_order_no'];
                                        }
                                        $comma_customer_order_nos = implode(", ", $work_order_nos);
                                    }
                                    
                                   									                                    $route_detail = "";
$set_number = "";

if ($set_id != 0) {
    // ✅ Case 1: Part belongs to a set
    $sql = "
        SELECT 
            srd.route_desc,
            sm.set_number
        FROM 
            set_route_details AS srd
        LEFT JOIN 
            set_mangmnt AS sm ON sm.id = srd.set_id
        WHERE 
            srd.set_id = ?
        LIMIT 1
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $set_id);

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $route_detail = $row['route_desc'];
            $set_number = $row['set_number'];
        }
    }
    //$stmt->close();

} else {
    // ✅ Case 2: Standalone part — no set_number involved
    $sql = "
        SELECT 
            route_desc
        FROM 
            route_details
        WHERE 
            item_id = ?
        LIMIT 1
    ";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $part_id);

    if ($stmt->execute()) {
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $route_detail = $row['route_desc'];
        }
    }
   
}
                                    
                                   // $due_date = utility::getTableFieldByTwoCondition("work_order_detail","required_date","work_order_id",$work_order_id,"product_id",$part_id);
                                    
                                    /*if($set_id != 0){
                                        $quantity = $task["absolute_quantity_if_set"]; 
                                    }else{
                                        $quantity = utility::getTableFieldByTwoCondition("work_order_detail","quantity","work_order_id",$work_order_id,"product_id",$part_id);
                                    }*/
									// $quantity = utility::getTableFieldByTwoCondition("work_order_detail","quantity","work_order_id",$work_order_id,"product_id",$part_id);
                                    
                                    //$part_name = utility::getTableFieldById("item_management","part_number","id",$part_id);
                                ?> 
    
                                   <div class="gantt-task 
    <?php echo $task['is_break'] ? 'break-task' : ''; ?> 
    <?php echo $task['is_late'] ? 'late-task' : 'on-time-task'; ?>"  
                                         draggable="<?php echo $task['is_break'] ? 'true' : 'true'; ?>"
                                         data-task-id="<?php echo $task["task_id"]; ?>"
                                         data-priority="<?php echo $task["priority"]; ?>"
                                         data-work-order="<?php echo $task["work_order_no"]; ?>" 
                                         data-part-id="<?php echo $task["part_id"]; ?>" 
                                         data-work-order-id="<?php echo $task["work_order_id"]; ?>"
                                         data-hours="<?php echo $task['allocated_hours']; ?>"
                                         data-current-machine="<?php echo $machineId; ?>"
                                         style="left: <?php echo $leftPosition; ?>px; width: <?php echo $taskWidth; ?>px;">
                                        
                                        <?php if ($task['is_break']): ?>
                                            <!-- Break Task Content -->
                                            <div class="task-content">
                                                <strong>BREAK</strong><br/>
                                                <?php echo htmlspecialchars($task['break_reason']); ?><br/>
                                                Duration: <?php echo $task['allocated_hours']; ?>h
                                            </div>
                                        <?php else: ?>
                                            <!-- Regular Task Content -->
                                           <!-- <?php //if ($task['set_id'] != 0): ?>
                                                <div class="blue-dot-indicator" title="This is a set task"></div>
                                            <?php //endif; ?>-->
                                            
                                           <?php
$dotClass = "red-dot-indicator";

// Get all child parts for the given work order and part
$childQuery = "
    SELECT mc.child_part_id, i.quantity_in_stock
    FROM manufacture_machine_children AS mc
    LEFT JOIN inventory AS i 
        ON mc.child_part_id = i.item_id
    WHERE mc.part_id = {$task['part_id']}
      AND mc.work_order_id = {$task['work_order_id']}
      AND i.quantity_in_stock > 0
    LIMIT 1
";

$childResult = $conn->query($childQuery);

// If at least one child part has stock > 0 → mark as green
if ($childResult && $childResult->num_rows > 0) {
    $dotClass = "green-dot-indicator";
}
?>

                                            <div class="dot-indicator <?php echo $dotClass; ?>" title=""></div>

                                            <div class="task-content" style="font-size:15px;">
                                                <?php if ($parent_ids == 0): ?>
                                                    <?php echo $comma_customer_order_nos; ?>
                                                <?php else: ?>
                                                    <?php echo utility::getTableFieldById("item_management","part_number","id",$parent_ids); ?>
                                                <?php endif; ?>
                                                <br/>
                                               <?php 
echo $task["work_order_name"] . " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; 
if ($set_id != 0) {
    echo "Set No.: " . $set_number;
}
?>


												<br/> 
												<strong>Item:</strong> <?php echo $part_name; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Qty:</strong> <?php echo $quantity; ?><br>
<strong>Set Hours:</strong> <?php echo $setup_hours; ?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Setting Inst:</strong> <?php echo $task["setting_instruction"]; ?><br>
<?php if ($task['is_breakdown_affected']): ?>
                                                <strong style="color: #ff0000;">Breakdown Delay: +<?php echo $task['breakdown_hours']; ?>h</strong><br>
                                            <?php endif; ?>
                                                 <?php // echo $task["priority"]; ?>
                                                <div style="margin-top: 2px;">
                                                    <strong>Desc:</strong> <?php echo $route_detail; ?>
                                                </div>
                                                <div style="margin-top: 1px;">
                                                    <strong>Due Date:</strong> <?php echo "12"; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <div class="hour-indicator">
                                            <?php echo $task['allocated_hours']; ?>h
											<?php if ($task['is_breakdown_affected']): ?>
                                            <br><small>+<?php echo $task['breakdown_hours']; ?>h delay</small>
                                        <?php endif; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="no-tasks">No tasks scheduled</div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>

                </div>
            </div>
        </div>
    </div>
<div class="modal fade" id="breakdownModal" tabindex="-1" aria-labelledby="breakdownModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="breakdownModalLabel">Report Machine Breakdown</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="breakdownForm">
                    <div class="mb-3">
                        <label for="breakdownMachine" class="form-label">Machine</label>
                        <select class="form-select" id="breakdownMachine" 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="breakdownStart" class="form-label">Breakdown Start</label>
                        <input type="datetime-local" class="form-control" id="breakdownStart" 
                               value="<?php echo date('Y-m-d\TH:i'); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label for="breakdownEnd" class="form-label">Breakdown End (Optional)</label>
                        <input type="datetime-local" class="form-control" id="breakdownEnd">
                        <div class="form-text">Leave empty if breakdown is ongoing</div>
                    </div>
                    <div class="mb-3">
                        <label for="breakdownReason" class="form-label">Breakdown Reason</label>
                        <textarea class="form-control" id="breakdownReason" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="saveBreakdownBtn">Report Breakdown</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>
// Breakdown functionality
document.getElementById('addBreakdownBtn').addEventListener('click', function() {
    var breakdownModal = new bootstrap.Modal(document.getElementById('breakdownModal'));
    breakdownModal.show();
});

document.getElementById('saveBreakdownBtn').addEventListener('click', function() {
    const machineId = document.getElementById('breakdownMachine').value;
    const breakdownStart = document.getElementById('breakdownStart').value;
    const breakdownEnd = document.getElementById('breakdownEnd').value;
    const breakdownReason = document.getElementById('breakdownReason').value;
    
    if (!machineId || !breakdownStart || !breakdownReason) {
        alert('Please fill all required fields');
        return;
    }
    
    const breakdownData = {
        machine_id: machineId,
        breakdown_start: breakdownStart,
        breakdown_end: breakdownEnd || null,
        breakdown_reason: breakdownReason
    };
    
    $.ajax({
        url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=report_machine_breakdown",
        method: 'POST',
        data: breakdownData,
        dataType: 'json',
        success: function(response) {
            if (response.status === 'success') {
                alert('Breakdown reported successfully');
                window.location.reload();
            } else {
                alert('Error reporting breakdown: ' + response.message);
            }
        },
        error: function(xhr, status, error) {
            alert('Error reporting breakdown: ' + error);
        }
    });
});

// Auto-refresh every 5 minutes to update breakdown times
setInterval(function() {
    // You can add a subtle refresh indicator or auto-refresh
    console.log('Auto-refreshing for breakdown updates...');
}, 300000); // 5 minutes
</script>


<!-- Break Modal -->
<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 $workOrderss = [];
$query = "
SELECT 
    m.work_order_id,
    m.part_id,
    m.end_date,
	m.product_name,
    m.machine_id,
    m.quantity,
    m.total_hours,
    m.id,
    w.work_order_name
FROM 
    manufacture_machine_table m
LEFT JOIN 
    work_order_name w 
    ON m.work_order_id = w.work_order_id 
    AND m.part_id = w.part_id
JOIN 
    station_detail_table s 
    ON m.machine_id = s.id
WHERE 
    s.machine_type = 1
    AND m.in_scheduler_check = 0 ";

$workOrderQuery = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($workOrderQuery)) {
    $workOrderss[] = $row;
}
//print_r($workOrderss);
?>
<style>
.custom-scroll {
    max-height: 400px;  /* adjust as needed */
    overflow-y: auto;
}
.select2-container {
    z-index: 9999 !important;
}
.select2-dropdown {
    z-index: 99999 !important;
}
</style>
<div class="modal fade" id="workOrderModal" tabindex="-1" aria-labelledby="workOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <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">
                <form id="workOrderForm">
                    <table class="table">
                             <thead>
            <tr>
                <th>WO Number</th>
                <th>Part Number</th>
                <th>Part Description</th>
                <th>Due Date</th>
                <th>Qty</th>
                <th>Std Hours</th>
                <th>Machine</th>
                <th>Select</th>
            </tr>
        </thead>
                                <tbody>
            <?php foreach ($workOrderss as $workOrder): ?>
                <tr data-part-id="<?php echo htmlspecialchars($workOrder['part_id']); ?>" data-wo-id="<?php echo $workOrder['work_order_id']; ?>">
                  <td><?php echo htmlspecialchars($workOrder['work_order_name'] ?? '-'); ?></td>

                     <td><?php echo $parent_number = $workOrder['product_name']; ?></td>
                    <td><?php echo $parent_name = utility::getTableFieldById("item_management","product_description","id",$workOrder['part_id']); ?></td>
                    <td><?php echo htmlspecialchars($workOrder['end_date']); ?></td>
                    <td><?php echo htmlspecialchars($workOrder['quantity']); ?></td>
                    <td><?php echo htmlspecialchars($workOrder['total_hours']); ?></td>
					<td>
                        <?= $gsi->getvacStationList("machine_id_" . $workOrder['id'], $workOrder['machine_id'], "100%", false, "form-control select2 machine-select", "");

							
							
                        ?>
                    </td>
                    <td>
                       <input 
							class="form-check-input" 
							type="checkbox" 
							style="margin-left: 10px;" 
							name="workOrder[]" 
							value="<?php echo $workOrder['work_order_id']; ?>" 
							id="workOrder<?php echo $workOrder['work_order_id']; ?>"
							data-machine-id="<?php echo $workOrder['machine_id']; ?>"
							data-id="<?php echo $workOrder['id']; ?>"
						>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
                    </table>
                </form>
            </div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button 
        type="button" 
        id="submitWorkOrdersBtn" 
        class="btn btn-primary" 
        onclick="showSelectedWorkOrders()"
    >
        <span class="btn-text">Show Selected</span>
        <span 
            id="spinner" 
            class="spinner-border spinner-border-sm ms-2 d-none" 
            role="status" 
            aria-hidden="true"
        ></span>
    </button>
</div>

        </div>
    </div>
</div>
<script>
function showSelectedWorkOrders() {
    const workOrders = [];

    $('input[name="workOrder[]"]:checked').each(function () {
        const workOrderId = $(this).val();
        const row = $(this).closest('tr');
        const partId = row.data('part-id');
        const dbId = $(this).data('id');
        const machineSelectId = "machine_id_" + dbId;
        const machineId = $("#" + machineSelectId).val();

        workOrders.push({
            id: dbId,
            work_order_id: workOrderId,
            part_id: partId,
            machine_id: machineId
        });
    });

    if (workOrders.length === 0) {
        alert("Please select at least one work order.");
        return;
    }

    // Disable button and show spinner
    const $btn = $("#submitWorkOrdersBtn");
    $btn.prop("disabled", true);
    $("#spinner").removeClass("d-none");
    $btn.find(".btn-text").text("Submitting...");

    $.ajax({
        url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=select_order_for_vac",
        method: "POST",
        data: { work_orders: JSON.stringify(workOrders) },
        success: function (response) {
            alert("Work orders submitted successfully!");
            location.reload();
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", error);
           // alert("Failed to submit work orders. Please try again.");
		   location.reload();
        },
        complete: function () {
            // Re-enable button and hide spinner
            $btn.prop("disabled", false);
            $("#spinner").addClass("d-none");
            $btn.find(".btn-text").text("Show Selected");
        }
    });
}
</script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
    let draggedTask = null;
    let highlightedNeighbor = null;

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

        task.addEventListener('dragend', (e) => {
            task.classList.remove('dragging');
            if (highlightedNeighbor) {
                highlightedNeighbor.classList.remove('highlight-border');
                highlightedNeighbor = null;
            }
        });
    });

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

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

        row.addEventListener('drop', (e) => {
            e.preventDefault();
            row.classList.remove('drop-target');

            if (!draggedTask) return;

            const dropX = e.clientX - row.getBoundingClientRect().left;
            const tasks = [...row.querySelectorAll('.gantt-task')];
            const otherTasks = tasks.filter(t => t !== draggedTask);
            
            otherTasks.sort((a, b) => parseFloat(a.style.left) - parseFloat(b.style.left));

            let leftNeighbor = null;
            for (let i = 0; i < otherTasks.length; i++) {
                const task = otherTasks[i];
                const taskLeft = parseFloat(task.style.left);
                const taskRight = taskLeft + parseFloat(task.style.width);
                
                if (taskRight < dropX) {
                    leftNeighbor = task;
                } else {
                    break;
                }
            }

            if (highlightedNeighbor) {
                highlightedNeighbor.classList.remove('highlight-border');
                highlightedNeighbor = null;
            }

            const taskId = draggedTask.dataset.taskId;
            const newMachineId = row.dataset.machineId;
            const partId = draggedTask.dataset.partId;
            const workOrderId = draggedTask.dataset.workOrderId;
            const leftNeighborPriority = leftNeighbor ? leftNeighbor.dataset.priority : null;
            const leftNeighborTaskId = leftNeighbor ? leftNeighbor.dataset.taskId : null;
            const newPosition = dropX;
            
            if (confirm("Are you sure you want to move this task?")) {
                $.ajax({
                    url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=update_vac_task_priority",
                    method: 'POST',
                    data: { 
                        task_id: taskId,
                        new_machine_id: newMachineId,
                        part_id: partId, 
                        work_order_id: workOrderId, 
                        left_neighbor_priority: leftNeighborPriority,
                        left_neighbor_task_id: leftNeighborTaskId,
                        new_position: newPosition
                    }, 
                    dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success') {
                            window.location.reload();
                        } else {
                            alert("Error updating task: " + response.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert("Error updating task: " + error);
                    }
                });
            }
        });
    });

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

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

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

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

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

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

    // Add Break functionality
    document.getElementById('addBreakBtn').addEventListener('click', function() {
        var breakModal = new bootstrap.Modal(document.getElementById('breakModal'));
        breakModal.show();
    });

    document.getElementById('saveBreakBtn').addEventListener('click', function() {
        const machineId = document.getElementById('breakMachine').value;
        const 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;
        }
        
        // Find the highest priority task for this machine
        const tasks = [...document.querySelectorAll('.gantt-task')];
        const machineTasks = tasks.filter(task => 
            task.dataset.currentMachine === machineId
        );
        
        let highestPriorityTask = null;
        if (machineTasks.length > 0) {
            machineTasks.sort((a, b) => a.dataset.priority - b.dataset.priority);
            highestPriorityTask = machineTasks[0];
        }
        
        // Prepare data for AJAX
        const breakData = {
            machine_id: machineId,
            duration: duration,
            reason: reason,
            highest_priority_task_id: highestPriorityTask ? highestPriorityTask.dataset.taskId : null,
            highest_priority: highestPriorityTask ? highestPriorityTask.dataset.priority : null
        };
        
        // Send AJAX request
        $.ajax({
            url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=add_vac_break",
            method: 'POST',
            data: breakData,
            dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert('Break added successfully');
                    window.location.reload();
                } else {
                    alert('Error adding break: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                alert('Error adding break: ' + error);
            }
        });
    });
    </script>
</div>