
<div class="container-fluid" style="background-color: #ffe6e6; height: 100vh;">
  <div class="split-container">
    <div class="split-panel" id="left-panel">
      <div class="container mt-4">
	  <?php $workOrderss_pending = [];
 $query_pending = "SELECT 
  m.work_order_id, 
  m.part_id, 
  m.table_id, 
  m.start_date AS child_start, 
  m.end_date, 
  m.machine_id, 
  m.quantity, 
  m.total_hours, 
  m.in_scheduler_check, 
  m.id, m.part_id, m.parent_ids, m.child_ids, 
   p.id,
  p.start_date,
 
  m.part_id, m.parent_ids, m.child_ids,
  w.work_order_name 
FROM manufacture_machine_table AS m 
LEFT JOIN work_order_name AS w 
  ON m.work_order_id = w.work_order_id AND m.part_id = w.part_id 
JOIN station_master_table AS s 
  ON m.machine_id = s.id 
JOIN vac_machine_table AS p 
  ON p.work_order_id = m.work_order_id 
  AND FIND_IN_SET(m.part_id, REPLACE(p.parent_ids, ' ', '')) > 0 
WHERE s.machine_type = 3 
  AND m.in_scheduler_check = 0 
  AND p.start_date > CURDATE()";


$workOrderQuery_pending = mysqli_query($conn, $query_pending);
while ($row_pending = mysqli_fetch_assoc($workOrderQuery_pending)) {
    $workOrderss_pending[] = $row_pending;
}
$workOrderss_for_wip_vac = [];

$query_wip_vac = "
SELECT 
  m.work_order_id, 
  m.part_id, 
  m.table_id, 
  m.start_date AS child_start, 
  m.end_date, 
  m.machine_id, 
  m.quantity, 
  m.total_hours, 
  m.in_scheduler_check, 
  m.id, 
  m.parent_ids, 
  m.child_ids, 
  p.id AS parent_id,
  p.start_date AS parent_start,
  p.end_date AS parent_end,
  w.work_order_name 
FROM manufacture_machine_table AS m 
LEFT JOIN work_order_name AS w 
  ON m.work_order_id = w.work_order_id 
  AND m.part_id = w.part_id 
JOIN station_master_table AS s 
  ON m.machine_id = s.id 
JOIN vac_machine_table AS p 
  ON p.work_order_id = m.work_order_id 
  AND FIND_IN_SET(m.part_id, REPLACE(p.parent_ids, ' ', '')) > 0 
WHERE s.machine_type = 3 
  AND m.in_scheduler_check = 0 
  AND DATE(p.start_date) <= CURDATE() 
  AND DATE(p.end_date) >= CURDATE();
";

$workOrderQuery_wip_vac = mysqli_query($conn, $query_wip_vac);
while ($rowwip_vac = mysqli_fetch_assoc($workOrderQuery_wip_vac)) {
    $workOrderss_for_wip_vac[] = $rowwip_vac;
}
//print_r($workOrderss_for_wip_vac);

$workOrderss_for_ready = [];

$query_ready = "
    SELECT 
  m.work_order_id, 
  m.part_id, 
  m.table_id, 
  m.start_date AS child_start, 
  m.end_date, 
  m.machine_id, 
  m.quantity, 
  m.total_hours, 
  m.in_scheduler_check, 
  m.id, 
  m.parent_ids, 
  m.child_ids, 
  p.id AS parent_id,
  p.end_date AS parent_end,
  w.work_order_name 
FROM manufacture_machine_table AS m 
LEFT JOIN work_order_name AS w 
  ON m.work_order_id = w.work_order_id 
  AND m.part_id = w.part_id 
JOIN station_master_table AS s 
  ON m.machine_id = s.id 
JOIN vac_machine_table AS p 
  ON p.work_order_id = m.work_order_id 
  AND FIND_IN_SET(m.part_id, REPLACE(p.parent_ids, ' ', '')) > 0 
WHERE s.machine_type = 3 
  AND m.in_scheduler_check = 0 
  AND DATE(p.end_date) < CURDATE();

";

$workOrderQuery_ready = mysqli_query($conn, $query_ready);
while ($rowready = mysqli_fetch_assoc($workOrderQuery_ready)) {
    $workOrderss_for_ready[] = $rowready;
}

 ?>
<h3 class="mb-3" style="background-color: #f8d7da;">Ready Orders</h3>
<form id="workOrderForm">
    <table class="table table-bordered">
        <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>Table</th>
                <th>Select</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($workOrderss_for_ready 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_name = utility::getTableFieldById("item_management","part_number","id",$workOrder['part_id']); ?></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>
                        <?php
                         echo  $machineSelect = $gsi->getStationList("machine_id_" . $workOrder['id'], $workOrder['machine_id'], "100%", false, "form-control select2 machine-select", "");

                        ?>
                    </td>
                    <td>
                        <select class="form-select" name="table_assignment[<?php echo $workOrder['work_order_id']; ?>]">
                            <option value="Table 1">Table 1</option>
                            <option value="Table 2">Table 2</option>
                        </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>
    <div class="mt-3">
        <button type="button" class="btn btn-primary" onclick="showSelectedWorkOrders()">Show Selected</button>
    </div>
</form>
</div>
<div class="container mt-4">
<h3 class="mb-3" style="background-color: #ffc107;">WIP VAC</h3>


    <form id="workOrderForm">
        <table class="table table-bordered">
            <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>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($workOrderss_for_wip_vac as $workOrderss_for_wip_vac): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($workOrderss_for_wip_vac['work_order_name']); ?></td>
                        <td><?php echo $parent_name = utility::getTableFieldById("item_management", "part_number", "id", $workOrderss_for_wip_vac['part_id']); ?></td>
                        <td><?php echo $route_detail = utility::getTableFieldById("route_details", "route_desc", "item_id", $workOrderss_for_wip_vac['part_id']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderss_for_wip_vac['end_date']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderss_for_wip_vac['quantity']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderss_for_wip_vac['total_hours']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="mt-3">
            <!--<button type="button" class="btn btn-secondary" onclick="history.back()">Back</button>-->
        </div>
    </form>
</div>
<div class="container mt-4">
<h3 class="mb-3" style="background-color: #e0e0e0;">Pending Orders</h3>


    <form id="workOrderForm">
        <table class="table table-bordered">
            <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>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($workOrderss_pending as $workOrderpending): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($workOrderpending['work_order_name']); ?></td>
                        <td><?php echo $parent_name = utility::getTableFieldById("item_management", "part_number", "id", $workOrderpending['part_id']); ?></td>
                        <td><?php echo $route_detail = utility::getTableFieldById("route_details", "route_desc", "item_id", $workOrderpending['part_id']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderpending['end_date']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderpending['quantity']); ?></td>
                        <td><?php echo htmlspecialchars($workOrderpending['total_hours']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <div class="mt-3">
            <!--<button type="button" class="btn btn-secondary" onclick="history.back()">Back</button>-->
        </div>
    </form>
</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');

        // Get the machine ID from the select element by dynamic ID
        const machineSelectId = "machine_id_" + dbId;
        const machineId = $("#" + machineSelectId).val();

        const tableValue = row.find('select[name="table_assignment[' + workOrderId + ']"]').val();
        const tableId = tableValue === 'Table 1' ? 1 : (tableValue === 'Table 2' ? 2 : '');

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

    console.log(workOrders);

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

    $.ajax({
        url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=select_order",
        method: "POST",
        data: {
            work_orders: JSON.stringify(workOrders)
        },
        success: function (response) {
            alert("Work orders submitted successfully!");
            location.reload(); // Reload the page after success
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error:", error);
            alert("Failed to submit work orders.");
        }
    });
}
</script>

    <div class="split-divider" id="divider"></div>
    <div class="split-panel" id="right-panel">
<?php
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');

// Generate current and adjacent months
$monthsToShow = [];
for ($i = -1; $i <= 1; $i++) {
    $date = strtotime("$year-$month-01 +$i months");
    $monthsToShow[] = [
        'month' => (int)date('m', $date),
        'year' => (int)date('Y', $date),
        'label' => date('F Y', $date)
    ];
}

// Fetch tasks from database
$workOrders = [];
$tasks = [];
$query = "SELECT 
    mmt.machine_id AS task, 
    mmt.table_id, 
    wo.work_order_no, 
    mmt.part_id, 
    mmt.total_hours, 
    mmt.work_order_id,
    mmt.absolute_quantity_if_set, 
    mmt.set_id, 
    mmt.set_part, 
    won.work_order_name,
    mmt.color, 
    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
FROM 
    cnc_machine_table mmt
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
WHERE 
    (YEAR(mmt.start_date) = $year OR YEAR(mmt.end_date) = $year)";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $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']];
    }
}
//print_r($tasks);
// 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;
}

// Function to distribute tasks across shifts
function distributeTasks($tasks, $shifts, $shiftHours, $shiftDays, $shiftTimes) {
    $distributedTasks = [];
    
    foreach ($tasks as $task) {
        $startDate = new DateTime($task['start_date'] . ' ' . $task['start_time']);
        $dayOfWeek = $startDate->format('l');
        
        // Find matching shift for this day
        foreach ($shifts as $shift) {
            if ($shiftDays[$shift] === $dayOfWeek) {
                $distributedTask = [
                    'task' => $task['task'],
                    'table_id' => $task['table_id'],
                    'allocated_hours' => $task['total_hours'],
                    'start_datetime' => $startDate->format('Y-m-d H:i:s'),
                    'work_order_id' => $task['work_order_id'],
                    'part_id' => $task['part_id'],
                    'work_order_no' => $task['work_order_no'],
                    'work_order_name' => $task['work_order_name'],
                    'color' => $task['color'],
                    'set_id' => $task['set_id'],
                    'parent_ids' => $task['parent_ids'],
                    'shift_name' => $shift,
                    'continuous' => true
                ];
                
                $distributedTasks[] = $distributedTask;
                break;
            }
        }
    }
    
    return $distributedTasks;
}

// Distribute all tasks
$distributedTasks = distributeTasks($tasks, $shifts, $shiftHours, $shiftDays, $shiftTimes);

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

// Get machine names
$machineQuery = mysqli_query($conn, "SELECT id, station FROM station_master_table WHERE machine_type = 3");
$taskNames = [];
while ($row = mysqli_fetch_assoc($machineQuery)) {
    $taskNames[$row['id'] . '-1'] = $row['station'] . ' - Table 1';
    $taskNames[$row['id'] . '-2'] = $row['station'] . ' - Table 2';
}

// Calendar generator
function generateCalendar($month, $year, $shifts, $shiftDays, $shiftTimes) {
    $calendar = [];
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $validWeekdays = array_unique(array_values($shiftDays));

    for ($day = 1; $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 $taskKey => $taskName) {
    $parts = explode('-', $taskKey);
    $machineId = $parts[0];
    if (!isset($machineColors[$machineId])) {
        $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);
        }

       

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

        .gantt-labels {
            position: sticky;
            left: 0;
            top: 0;
            width: 350px;
            background: #f9f9f9;
            padding: 15px;
            border-right: 1px solid #ddd;
            z-index: 20;
            height: fit-content;
            flex-shrink: 0;
        }

        .gantt-scrollable-content {
            flex: 1;
            min-width: 0;
            overflow-x: auto;
            position: relative;
        }

        .gantt-grid {
            display: inline-block;
            min-width: <?php echo $totalWidth; ?>px;
            position: relative;
        }

        .gantt-header {
            display: inline-flex;
            background: #f5f5f5;
            border-bottom: 1px solid #ddd;
            position: sticky;
            top: 0;
            z-index: 15;
        }

        .gantt-day {
            display: inline-flex;
            flex-direction: column;
            text-align: center;
            background-color: #fff;
            float: none;
            vertical-align: top;
            position: relative;
        }
        
        .gantt-day strong {
            font-size: 12px;
            color: #333;
            background: #f3f3f3;
            padding: 3px;
            border-radius: 3px;
            margin-bottom: 5px;
        }
        
        .gantt-time-intervals {
            display: flex;
            flex-wrap: nowrap;
            justify-content: flex-start;
            width: 100%;
            background-color: #f8f9fa;
            border-top: 1px solid #dee2e6;
        }

        .gantt-time-interval {
            flex: 0 0 var(--time-interval-width);
            text-align: center;
            font-size: 10px;
            color: #555;
            border-right: 1px solid var(--grid-line-color);
            //padding: 2px;
            height: 30px;
			
            position: relative;
        }

        .gantt-time-interval-label {
            position: absolute;
            font-size: 0.9rem;
            transform: rotate(-45deg);
            transform-origin: left center;
            white-space: nowrap;
            left: 0%;
            bottom: -15px;
            color: #000;
        }

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

        .gantt-row.table-1 {
            background-color: rgba(230, 242, 255, 0.3); 
        }

        .gantt-row.table-2 {
            background-color: rgba(255, 230, 230, 0.3);
        }

.gantt-task {
    position: absolute;
    height: 100%; /* Changed from fixed height to 100% */
    top: 0; /* Ensure it starts at the top of the row */
    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;
        }

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

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

/* Color variations */
.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;
        }

        /* Drag and drop styles */
        .gantt-task.dragging {
            opacity: 0.5;
            background-color: #f39c12;
        }

       
		.gantt-row.drop-target {
    outline: 2px dashed #007bff;
    background-color: #e6f7ff;
}
/* Add to your existing styles */
.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%;
}

/* New styles for drag and drop */
.dragging-time {
    opacity: 0.8;
    box-shadow: 0 0 10px rgba(0,0,0,0.3);
}

.drop-indicator {
    position: absolute;
    width: 2px;
    background-color: #007bff;
    z-index: 100;
    pointer-events: none;
    display: none;
}
</style>

    <div class="container-fluid">
        <div class="controls">
            <div class="row">
                <div class="col-md-6">
                    <h3><i class="fas fa-calendar-day me-2"></i>CNC Gantt Chart</h3>
                    <h4><?php echo date('l, F j, Y'); ?></h4>
                </div>
                <div class="col-md-6 text-end">                 
                    <button class="btn btn-primary" onclick="window.location.reload()">
                        <i class="fas fa-sync-alt me-2"></i>Refresh
                    </button>
                </div>
            </div>
        </div>

        <div class="gantt-container">
            <!-- Machines & Tables Section -->
            <div class="gantt-labels">
                <div>
                    <h5>
                        <i class="fas fa-server me-2"></i>
                        Machines
                        <span class="mx-2">and</span>
                        <i class="fas fa-user-tie me-2"></i>
                        Engineers
                    </h5>
                </div>

                <div class="machine-list d-flex flex-wrap" style="gap: 16px;">
                    <div style=" margin-bottom: 20px;"></div>
                    <?php
                    $renderedMachines = [];
                    foreach ($taskNames as $taskKey => $taskName): 
                        $parts = explode('-', $taskKey);
                        $machineId = $parts[0];
                        $tableId = $parts[1];
                        
                        if (!in_array($machineId, $renderedMachines)):
                            $renderedMachines[] = $machineId;
                    ?>
                    <div class="mb-1">
                        <div class="card" style="background-color: #f2edf2; width: 300px; height: 220px; display: flex; align-items: center; justify-content: center; position: relative;">
                            <button class="circle-button" data-machine-id="<?php echo $machineId; ?>"></button>
                            
                            <div class="card-body text-center" style="width: 100%;">
                                <h5 class="card-title"><?php 
                                    $parts = explode(' - ', $taskName);
                                    echo $parts[0]; 
                                ?></h5>
								<br><br>
                                <?php $gsi->getEmployeeList("machine_high_priority", $machine_high_priority, "100%", false, "form-control select2", ""); ?>
                            </div>
                        </div>
                    </div>
                    <?php 
                        endif;
                    endforeach; 
                    ?>
                </div>
            </div>
            
            <div class="gantt-labels" style="left: 350px; width: 250px;">
                <h5><i class="fas fa-server me-2"></i>Table</h5>
                <div style=" margin-bottom: 30px;"></div>
                <div class="machine-list">
                    <?php
                    $renderedMachines = [];
                    foreach ($taskNames as $taskKey => $taskName): 
                        $parts = explode('-', $taskKey);
                        $machineId = $parts[0];
                        $tableId = $parts[1];
                        
                        if (!in_array($machineId, $renderedMachines)):
                            $renderedMachines[] = $machineId;
                            $machineName = explode(' - ', $taskName)[0];
                    ?>
                        <div class="machine-section mb-1" style="width: 200px;">
                            <div class="row" style="margin-bottom: 2px; height: 120px;">
                                <div class="card" class="card-header text-dark" style="background-color: #e6f2ff;">
                                    <div>
                                        Table 1
                                        <label for="efficiency_<?= $machineId ?>_1"></label>
                                        <input type="text" class="form-control" id="efficiency_<?= $machineId ?>_1" name="efficiency[<?= $machineId ?>][1]" placeholder=" efficiency">
                                    </div>
                                </div>
                            </div>

                            <div class="row" style="margin-top: 8px; height: 120px;">
                                <div class="card" class="card-header text-dark" style="background-color: #ffe6e6;">
                                    <div>
                                        Table 2
                                        <label for="efficiency_<?= $machineId ?>_2"></label>
                                        <input type="text" class="form-control" id="efficiency_<?= $machineId ?>_2" name="efficiency[<?= $machineId ?>][2]" placeholder=" efficiency">
                                    </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;
                        ?>
                            <div class="gantt-day" 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 $taskKey => $taskName): 
                        $parts = explode('-', $taskKey);
                        $machineId = $parts[0];
                        $tableId = $parts[1];
                        $groupKey = $machineId . '-' . $tableId;
                        $rowColor = $machineColors[$machineId];
                    ?>
                        <div class="gantt-row table-<?php echo $tableId; ?>" 
                             data-machine-id="<?php echo $machineId; ?>" 
                             data-table-id="<?php echo $tableId; ?>"  
                             style="background-color: <?php echo $rowColor; ?>;">
                            
                            <?php if (isset($groupedTasks[$groupKey])): ?>
                                <?php foreach ($groupedTasks[$groupKey] as $task): ?>
                                    <?php
                                    $startDatetime = new DateTime($task['start_datetime']);
                                    $startDate = $startDatetime->format('Y-m-d');
                                    $startTime = $startDatetime->format('H:i:s');
                                    $totalHours = $task['allocated_hours'];
                                    $shiftName = $task['shift_name'];
                                    $dayKey = $startDate . '-' . $shiftName;

                                    // Skip if this day/shift combination doesn't exist in our calendar
                                    if (!isset($dayPositions[$dayKey])) continue;

                                    // Get the day details
                                    $dayDetails = null;
                                    foreach ($calendarDays as $day) {
                                        if ($day['date'] === $startDate && $day['shift'] === $shiftName) {
                                            $dayDetails = $day;
                                            break;
                                        }
                                    }
                                    if (!$dayDetails) continue;

                                    // Calculate exact position in minutes from shift start
                                    $taskTime = new DateTime($startTime);
                                    $shiftStart = new DateTime($dayDetails['start_time']);
                                    $timeDiff = $taskTime->diff($shiftStart);
                                    $minutesFromShiftStart = $timeDiff->h * 60 + $timeDiff->i;
                                    
                                    // Calculate pixels per minute for this day
                                    $pixelsPerMinute = $dayWidths[$dayKey] / $dayDetails['total_minutes'];
                                    
                                    // Calculate exact position in pixels
                                    $positionInPixels = $minutesFromShiftStart * $pixelsPerMinute;
                                    
                                    // Calculate task width in pixels
                                    $taskWidth = $totalHours * 60 * $pixelsPerMinute;
                                    
                                    // Calculate left position (day offset + position within day)
                                    $leftPosition = $dayPositions[$dayKey] + $positionInPixels;

                                    // Get additional task details
                                    $part_id = $task["part_id"];
                                    $work_order_id = $task["work_order_id"];
                                    $set_id = $task["set_id"];
                                    $parent_ids = $task["parent_ids"];
                                    
                                    $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);
                                    }
                                    
                                    if($set_id != 0){
                                        $route_detail = utility::getTableFieldById("set_route_details","route_desc","set_id",$set_id);
                                    }else{
                                        $route_detail = utility::getTableFieldById("route_details","route_desc","item_id",$part_id);
                                    }
                                    
                                    $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);
                                    }
                                    
                                    $part_name = utility::getTableFieldById("item_management","part_number","id",$part_id);
                                    ?>
                                    <div class="gantt-task task-color-<?php echo $task['color']; ?>" 
                                         draggable="true"
                                         data-task-id="<?php echo $task["task"]; ?>" 
                                         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-date="<?php echo $startDate; ?>" 
                                         data-shift="<?php echo $shiftName; ?>"
                                         data-hours="<?php echo $totalHours; ?>"
                                         data-current-machine="<?php echo $machineId; ?>"
                                         data-current-table="<?php echo $tableId; ?>"
                                         style="left: <?php echo $leftPosition; ?>px; width: <?php echo $taskWidth; ?>px;">
                                        
                                        <?php if ($task['set_id'] != 0): ?>
                                            <div class="blue-dot-indicator" title="This is a set task"></div>
                                        <?php endif; ?>
																			 <?php
// Get the child_id from cnc_machine_table
$task_part_id = $task["part_id"];
  $childQuery = "SELECT child_ids FROM cnc_machine_table WHERE part_id = $task_part_id AND work_order_id = $work_order_id";
$childResult = $conn->query($childQuery);

$dotClass = "red-dot-indicator"; // default class

if ($childResult && $childResult->num_rows > 0) {
    $row = $childResult->fetch_assoc();
    $child_id = $row['child_ids'];

    // Get the quantity_in_stock from inventory
    $query = "SELECT quantity_in_stock FROM inventory WHERE item_id = $child_id";
    $result = $conn->query($query);

    if ($result && $result->num_rows > 0) {
        $invRow = $result->fetch_assoc();
        $quantity_in_stock = $invRow['quantity_in_stock'];

        if ($quantity_in_stock > 0) {
            $dotClass = "green-dot-indicator";
        }
    }
}
?>

										<!-- Dot indicator with dynamic class -->
<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"]; ?><br>
                                            Item: <?php echo $part_name; ?><br>
                                            Qty: <?php echo $quantity; ?>
                                            <div style="margin-top: 5px;">
                                                <strong>Desc:</strong> <?php echo $route_detail; ?>
                                            </div>
                                            <div style="margin-top: 5px;">
                                                <strong>Due Date:</strong> <?php echo $due_date; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="hour-indicator">
                                            <?php echo $totalHours; ?>h
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <div class="no-tasks">No tasks scheduled</div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    // Initialize variables for both drag functionalities
    let timeDragTask = null;
    let dropIndicator = null;
    let initialX = 0;
    let initialLeft = 0;
    let snapInterval = 40; 
    let minDragDistance = snapInterval / 2;
    
    let draggedTask = null;
    let originalRow = null;

    // Create drop indicator for time dragging
    dropIndicator = document.createElement('div');
    dropIndicator.className = 'drop-indicator';
    document.body.appendChild(dropIndicator);
    dropIndicator.style.display = 'none';

    function calculateTotalWidth() {
        const days = document.querySelectorAll('.gantt-day');
        let totalWidth = 0;

        days.forEach(day => {
            totalWidth += day.offsetWidth;
        });

        const minWidth = Math.max(totalWidth, document.querySelector('.gantt-container').offsetWidth);
        document.querySelector('.gantt-grid').style.minWidth = minWidth + 'px';
    }

    calculateTotalWidth();
    window.addEventListener('resize', calculateTotalWidth);

    // Modified event listeners to prevent conflicts
    document.querySelectorAll('.gantt-task').forEach(task => {
        // For time dragging - only on the task content (not the whole task)
        const taskContent = task.querySelector('.task-content');
        if (taskContent) {
            taskContent.addEventListener('mousedown', startTimeDrag);
            taskContent.addEventListener('touchstart', startTimeDrag, { passive: false });
        }
        
        // For machine changing - on the whole task
        task.addEventListener('dragstart', onDragStart);
        task.addEventListener('dragend', onDragEnd);
    });

    // Set up row event listeners for machine changes
    document.querySelectorAll('.gantt-row').forEach(row => {
        row.addEventListener('dragover', onDragOver);
        row.addEventListener('dragleave', onDragLeave);
        row.addEventListener('drop', onDrop);
    });

    // Time dragging functions
    function startTimeDrag(e) {
        // Only start time drag if not already dragging for machine change
        if (draggedTask) return;
        
        e.preventDefault();
        e.stopPropagation();

        const clientX = e.clientX || e.touches[0].clientX;
        timeDragTask = e.currentTarget.closest('.gantt-task');
        initialX = clientX;
        initialLeft = parseInt(timeDragTask.style.left, 10) || 0;

        timeDragTask.classList.add('dragging-time');

        document.addEventListener('mousemove', performTimeDrag);
        document.addEventListener('touchmove', performTimeDrag, { passive: false });
        document.addEventListener('mouseup', stopTimeDrag);
        document.addEventListener('touchend', stopTimeDrag);
    }

    function performTimeDrag(e) {
        if (!timeDragTask) return;
        e.preventDefault();
        e.stopPropagation();

        const clientX = e.clientX || e.touches[0].clientX;
        const deltaX = clientX - initialX;
        let newLeft = initialLeft + deltaX;
        const snappedLeft = Math.round(newLeft / snapInterval) * snapInterval;

        if (Math.abs(newLeft - snappedLeft) < minDragDistance) {
            newLeft = snappedLeft;
        }

        timeDragTask.style.left = newLeft + 'px';
        updateDropIndicator(newLeft);
    }

    function updateDropIndicator(leftPosition) {
        if (!timeDragTask || !dropIndicator) return;

        const taskRow = timeDragTask.closest('.gantt-row');
        const container = taskRow.closest('.gantt-container');

        dropIndicator.style.display = 'block';
        dropIndicator.style.left = (container.offsetLeft + leftPosition) + 'px';
        dropIndicator.style.top = taskRow.offsetTop + 'px';
        dropIndicator.style.height = taskRow.offsetHeight + 'px';
    }

    function stopTimeDrag(e) {
        if (!timeDragTask) return;
        e.preventDefault();
        e.stopPropagation();

        timeDragTask.classList.remove('dragging-time');
        dropIndicator.style.display = 'none';
        updateTaskTime(timeDragTask);

        document.removeEventListener('mousemove', performTimeDrag);
        document.removeEventListener('touchmove', performTimeDrag);
        document.removeEventListener('mouseup', stopTimeDrag);
        document.removeEventListener('touchend', stopTimeDrag);

        timeDragTask = null;
    }

    function updateTaskTime(task) {
        const leftPosition = parseInt(task.style.left, 10);
        const taskRow = task.closest('.gantt-row');
        const taskId = task.dataset.taskId;
        const workOrderId = task.dataset.workOrderId;
        const partId = task.dataset.partId;
        const currentMachine = task.dataset.currentMachine;
        const currentTable = task.dataset.currentTable;
        const hours = task.dataset.hours;

        const days = Array.from(document.querySelectorAll('.gantt-day'));
        let cumulativeWidth = 0;
        let targetDay = null;
        let intervalIndex = 0;

        for (const day of days) {
            const dayWidth = parseInt(day.style.minWidth, 10) || 0;

            if (leftPosition >= cumulativeWidth && leftPosition < cumulativeWidth + dayWidth) {
                targetDay = day;
                const positionInDay = leftPosition - cumulativeWidth;
                intervalIndex = Math.floor(positionInDay / snapInterval);
                break;
            }

            cumulativeWidth += dayWidth;
        }

        if (targetDay) {
            const date = targetDay.dataset.date;
            const shift = targetDay.dataset.shift;
            const intervals = Array.from(targetDay.querySelectorAll('.gantt-time-interval'));

            if (intervals[intervalIndex]) {
                const interval = intervals[intervalIndex].dataset.interval;
                const [startTime] = interval.split('-');

                // Update task data attributes
                task.dataset.date = date;
                task.dataset.shift = shift;
                task.dataset.startTime = startTime;

                // Prepare data for AJAX request
                const postData = {
                    work_order_id: workOrderId,
                    part_id: partId,
                    task_id: taskId,
                    new_date: date,
                    new_shift: shift,
                    new_start_time: startTime,
                    hours: hours,
                    current_machine: currentMachine,
                    current_table: currentTable
                };

                // Show confirmation dialog
                if (confirm("Are you sure you want to update this task's schedule?")) {
                    // Send AJAX request
                   $.ajax({
                        url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=update_task_time_cnc",
                        method: "POST",
                        data: postData,
                        dataType: 'json',
                       /* beforeSend: function() {
                            // Show loading indicator if needed
                        },*/
                        success: function(response) {
                            if (response.success) {
                                // Task position updated successfully
                                console.log("Task schedule updated successfully");
                                // You might want to refresh the Gantt chart or update the UI
                            } else {
                                // Handle error
                                //console.error("Error updating task schedule:", response.message);
                                //alert("Error updating task schedule: " + response.message);
                                // Revert the task position if needed
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error("AJAX error:", error);
                            alert("An error occurred while updating the task schedule.");
                            // Revert the task position if needed
                        }
                    });
                } else {
                    // User cancelled - revert the task position
                    task.style.left = initialLeft + 'px';
                }
            }
        }
    }

    // Machine change functions
    function onDragStart(event) {
        // Only start machine drag if not already time dragging
        if (timeDragTask) return;
        
        draggedTask = event.target;
        originalRow = event.target.parentElement;
        event.target.classList.add('dragging');
        event.dataTransfer.setData('text/plain', event.target.dataset.taskId);
        event.dataTransfer.effectAllowed = 'move';
    }

    function onDragOver(event) {
        if (!draggedTask) return;
        event.preventDefault();
        const targetRow = event.currentTarget;
        if (targetRow !== originalRow) {
            targetRow.classList.add('drop-target');
        }
    }

    function onDragLeave(event) {
        event.currentTarget.classList.remove('drop-target');
    }

    function onDrop(event) {
        if (!draggedTask) return;
        event.preventDefault();
        const targetRow = event.currentTarget;
        targetRow.classList.remove('drop-target');

        if (targetRow !== originalRow && draggedTask) {
            const targetMachineId = targetRow.dataset.machineId;
            const targetTableId = targetRow.dataset.tableId;

            draggedTask.dataset.currentMachine = targetMachineId;
            draggedTask.dataset.currentTable = targetTableId;

            targetRow.appendChild(draggedTask);

            if (confirm("Are you sure you want to change the machine?")) {
                $.ajax({
                    url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=update_task_position_cnc",
                    method: "POST",
                    data: {
                        task_id: draggedTask.dataset.taskId,
                        work_order_id: draggedTask.dataset.workOrderId,
                        part_id: draggedTask.dataset.partId,
                        new_machine_id: targetMachineId,
                        new_table_id: targetTableId
                    },
                    success: function (response) {
                        console.log("Tasks updated successfully:", response);
                    },
                    error: function () {
                        console.error("Failed to update task positions.");
                    }
                });
            }
        }
    }

    function onDragEnd(event) {
        if (!draggedTask) return;
        event.target.classList.remove('dragging');
        event.target.style.height = '100%';
        document.querySelectorAll('.gantt-row').forEach(row => {
            row.classList.remove('drop-target');
        });
        draggedTask = null;
        originalRow = null;
    }
});
</script>

	<script>
document.addEventListener('DOMContentLoaded', function() {
    // ... your existing drag-and-drop code ...

    // Function to find and highlight today's date
    function highlightToday() {
        const today = new Date();
        const todayStr = formatDate(today); // Format: YYYY-MM-DD
        
        // Remove any existing today highlights
        document.querySelectorAll('.gantt-day').forEach(day => {
            day.classList.remove('today');
        });
        
        // Find today's date in the header
        const todayElements = document.querySelectorAll(`.gantt-day[data-date="${todayStr}"]`);
        
        if (todayElements.length > 0) {
            // Highlight all today elements
            todayElements.forEach(el => {
                el.classList.add('today');
            });
            
            // Scroll to the first today element
            const firstTodayElement = todayElements[0];
            const scrollContainer = document.querySelector('.gantt-scrollable-content');
            
            // Calculate scroll position to center today
            const containerWidth = scrollContainer.offsetWidth;
            const todayPosition = firstTodayElement.offsetLeft;
            const todayWidth = firstTodayElement.offsetWidth;
            
            const scrollLeft = todayPosition - (containerWidth / 2) + (todayWidth / 2);
            
            // Apply scroll position
            scrollContainer.scrollLeft = scrollLeft;
            
            // Add current time marker
            addCurrentTimeMarker(todayStr);
        }
    }

    // Helper function to format date as YYYY-MM-DD
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // Function to add current time marker
    function addCurrentTimeMarker(todayStr) {
        // Remove any existing time marker
        const existingMarker = document.querySelector('.current-time-marker');
        if (existingMarker) {
            existingMarker.remove();
        }
        
        const now = new Date();
        const currentHours = now.getHours();
        const currentMinutes = now.getMinutes();
        const currentTimeInMinutes = (currentHours * 60) + currentMinutes;
        
        // Find today's day element
        const todayElement = document.querySelector(`.gantt-day[data-date="${todayStr}"]`);
        if (!todayElement) return;
        
        // Get the time intervals container
        const timeIntervals = todayElement.querySelector('.gantt-time-intervals');
        if (!timeIntervals) return;
        
        // Calculate position based on current time
        const intervals = Array.from(timeIntervals.querySelectorAll('.gantt-time-interval'));
        let totalWidth = 0;
        let markerPosition = 0;
        let found = false;
        
        intervals.forEach(interval => {
            const timeRange = interval.dataset.interval;
            if (!timeRange) return;
            
            const [startTime, endTime] = timeRange.split('-');
            const [startHour, startMinute] = startTime.split(':').map(Number);
            const [endHour, endMinute] = endTime.split(':').map(Number);
            
            const startTimeInMinutes = (startHour * 60) + startMinute;
            const endTimeInMinutes = (endHour * 60) + endMinute;
            const intervalWidth = interval.offsetWidth;
            
            if (currentTimeInMinutes >= startTimeInMinutes && currentTimeInMinutes <= endTimeInMinutes) {
                // Current time is within this interval
                const progress = (currentTimeInMinutes - startTimeInMinutes) / (endTimeInMinutes - startTimeInMinutes);
                markerPosition = totalWidth + (progress * intervalWidth);
                found = true;
            }
            
            totalWidth += intervalWidth;
        });
        
        if (found) {
            // Create and position the marker
            const marker = document.createElement('div');
            marker.className = 'current-time-marker';
            marker.style.left = `${todayElement.offsetLeft + markerPosition}px`;
            
            // Add to the grid
            document.querySelector('.gantt-grid').appendChild(marker);
        }
    }

    // Call the function when the page loads
    highlightToday();
    
    // Also add a button to jump to today
    const jumpToTodayBtn = document.createElement('button');
    jumpToTodayBtn.className = 'btn btn-warning ms-2';
    jumpToTodayBtn.innerHTML = '<i class="fas fa-calendar-day me-2"></i>Jump to Today';
    jumpToTodayBtn.onclick = highlightToday;
    
    // Add button to your controls section (adjust selector as needed)
    document.querySelector('.col-md-6.text-end').appendChild(jumpToTodayBtn);
});

	</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>
$('body').addClass('sidebar-collapse');

$(document).ready(function () {
    $(document).on("click", ".circle-button", function () {
        const machineId = $(this).data("machine-id");

        $.ajax({
            url: site_url + "/modules/machines_management/index.php?page=ajax_actions&action=new_hours_for_workorder",
            method: "POST",
            data: { machine_id: machineId },
            beforeSend: function () {
                console.log("⏳ Sending request for machine:", machineId);
            },
            success: function (response) {
               // console.log("✅ AJAX success:", response);
                alert("✅ Efficiency and Schedule Updated Successfully.\n\n" + response);
            },
            error: function (xhr, status, error) {
                console.error("❌ AJAX error:", error);
                alert("❌ Failed to process data for machine " + machineId + ". Please try again.");
            }
        });
    });
});
</script>





    </div>
  </div>
</div>

<style>
  .split-container {
    display: flex;
    height: calc(100vh - 60px); /* Adjust based on your header height */
    width: 100%;
  }
  
  .split-panel {
    flex: 1;
    overflow: auto;
    padding: 10px;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
  }
  
  #left-panel {
    background-color: #e6f7ff;
  }
  
  #right-panel {
    background-color: #fff2e6;
  }
  
  .split-divider {
    width: 10px;
    background-color: #ccc;
    cursor: col-resize;
  }
  #container {
    display: flex;
    width: 100%;
    height: 100vh;
  }

  #left-panel {
    flex: 20;
  }

  #divider {
    width: 5px;
    cursor: col-resize;
    background-color: #aaa;
  }

  #right-panel {
    flex: 70;
  }
</style>



<script>
  document.addEventListener('DOMContentLoaded', function() {
    const leftPanel = document.getElementById('left-panel');
    const rightPanel = document.getElementById('right-panel');
    const divider = document.getElementById('divider');

    let isDragging = false;

    divider.addEventListener('mousedown', function(e) {
      isDragging = true;
      document.body.style.cursor = 'col-resize';
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    });

    function onMouseMove(e) {
      if (!isDragging) return;

      const container = divider.parentNode;
      const containerWidth = container.offsetWidth;
      const offsetX = e.clientX - container.getBoundingClientRect().left;

      // Minimum and maximum limits (optional)
      const minLeft = 10;  // in %
      const maxLeft = 90;

      let leftFlex = (offsetX / containerWidth) * 100;
      leftFlex = Math.max(minLeft, Math.min(maxLeft, leftFlex));
      let rightFlex = 100 - leftFlex;

      leftPanel.style.flex = leftFlex;
      rightPanel.style.flex = rightFlex;
    }

    function onMouseUp() {
      isDragging = false;
      document.body.style.cursor = '';
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    }
  });
</script>
