<?php
include("../../../include/startup.php"); 
function recalculateMachineDates($conn, $machineId, $tableId) {
    set_time_limit(300);

    $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
    $taskResult = mysqli_query($conn,
        "SELECT id, total_hours  AS hours_to_schedule
         FROM cnc_machine_table
         WHERE machine_id = $machineId 
           AND table_id = $tableId 
           AND end_date >= '$currentDateStr'
         ORDER BY priority"
    );

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

    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

    foreach ($tasks as $task) {
        $hoursRemaining = floatval($task['hours_to_schedule']);
        $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'];

                if ($shiftEnd <= $currentDateTime) continue;

                $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;

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

                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

        $remainingHoursStr = '';
        foreach ($dateHoursMap as $date => $hrs) {
            $remainingHoursStr .= $date . '=' . round($hrs, 2) . ',';
        }
        $remainingHoursStr = rtrim($remainingHoursStr, ',');

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

$query = "UPDATE cnc_machine_table SET
    start_date = '$startStr',
    end_date = '$endStr',
    shift_ids = '$firstShiftUsed',
    remaing_hours = '$remainingHoursStr'
    WHERE id = {$task['id']}";

mysqli_query($conn, $query);



    }
}
function recalculateMachineDates_fororiginal($conn, $machineId, $tableId) {
    set_time_limit(300);

    $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
    $taskResult = mysqli_query($conn,
        "SELECT id, original_total_hours  AS hours_to_schedule
         FROM cnc_machine_table
         WHERE machine_id = $machineId 
           AND table_id = $tableId 
           AND original_end_date >= '$currentDateStr'
         ORDER BY priority"
    );

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

    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

    foreach ($tasks as $task) {
        $hoursRemaining = floatval($task['hours_to_schedule']);
        $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'];

                if ($shiftEnd <= $currentDateTime) continue;

                $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;

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

                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

        $remainingHoursStr = '';
        foreach ($dateHoursMap as $date => $hrs) {
            $remainingHoursStr .= $date . '=' . round($hrs, 2) . ',';
        }
        $remainingHoursStr = rtrim($remainingHoursStr, ',');

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

$query = "UPDATE cnc_machine_table SET
    original_start_date = '$startStr',
    original_end_date = '$endStr',
    shift_ids = '$firstShiftUsed',
    original_remaing_hours = '$remainingHoursStr'
    WHERE id = {$task['id']}";

mysqli_query($conn, $query);



    }
}
####################################################################################################################

$updatedOrders = [];

function displayOrder($order) {
    // Removed display output
}

function getCurrentOrders($machineId, $conn) {
    global $updatedOrders;
    $currentDate = date('Y-m-d');
    $sql = "SELECT *, 
                   original_start_date AS start_date, 
                   original_end_date AS end_date, 
                   original_total_hours AS total_hours
            FROM cnc_machine_table 
            WHERE machine_id = ? 
            AND original_end_date >= ? 
            AND is_break = 0
            ORDER BY priority ASC, original_start_date ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $machineId, $currentDate);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $orders = [];
    while ($row = $result->fetch_assoc()) {
        if (isset($updatedOrders[$row['id']]['end_date'])) {
            $row['end_date'] = $updatedOrders[$row['id']]['end_date'];
            $row['total_hours'] = $updatedOrders[$row['id']]['total_hours'];
            $row['remaing_hours'] = $updatedOrders[$row['id']]['remaing_hours'];
        }
        $orders[] = $row;
    }
    return $orders;
}

function processMachineScheduling($machineId, $conn) {
    global $updatedOrders;
    $orders = getCurrentOrders($machineId, $conn);
    
    // First, update remaing_hours for all orders (using shifts)
    foreach ($orders as $order) {
        $orderId = $order['id'];
        $originalHours = (float)$order['original_total_hours'];
        $remainingHours = generateRemainingHours($order, strtotime($order['end_date']), $conn); 
        
        // Store in updatedOrders for consistency
        $updatedOrders[$orderId] = [
            'end_date' => $order['end_date'],
            'total_hours' => $originalHours,
            'remaing_hours' => $remainingHours
        ];
        
        // Update database (keeps existing behaviour)
        $sql = "UPDATE cnc_machine_table 
                SET total_hours = $originalHours, 
                    remaing_hours = '$remainingHours'
                WHERE id = $orderId";
        $conn->query($sql);
    }
    
    // If less than 2 orders, no need to check for overlaps
    if (count($orders) < 2) {
        return;
    }
    
    $potentialOverlaps = findPotentialOverlaps($orders);
    
    // If no overlaps found, we're done (already updated remaing_hours above)
    if (empty($potentialOverlaps)) {
        return;
    }
    
    // Process overlaps
    foreach ($potentialOverlaps as $overlapPair) {
        $order1 = fetchOrder($overlapPair[0]['id'], $conn);
        $order2 = fetchOrder($overlapPair[1]['id'], $conn);
        
        if (!$order1 || !$order2) continue;
        
        $alternated = calculateAlternatingSchedule($order1, $order2, $conn);
        
        storeUpdatedSchedule($order1['id'], $alternated['order1']);
        storeUpdatedSchedule($order2['id'], $alternated['order2']);
        
        updateOrderHours($order1['id'], $alternated['order1'], $conn);
        updateOrderHours($order2['id'], $alternated['order2'], $conn);
    }
}

function fetchOrder($orderId, $conn) {
    global $updatedOrders;
    $sql = "SELECT *, 
                   original_start_date AS start_date, 
                   original_end_date AS end_date, 
                   original_total_hours AS total_hours
            FROM cnc_machine_table WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $orderId);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    
    if ($row && isset($updatedOrders[$row['id']]['end_date'])) {
        $row['end_date'] = $updatedOrders[$row['id']]['end_date'];
        $row['total_hours'] = $updatedOrders[$row['id']]['total_hours'];
        $row['remaing_hours'] = $updatedOrders[$row['id']]['remaing_hours'];
    }
    return $row;
}

function findPotentialOverlaps($orders) {
    $overlaps = [];
    for ($i = 0; $i < count($orders) - 1; $i++) {
        for ($j = $i + 1; $j < count($orders); $j++) {
            $order1 = $orders[$i];
            $order2 = $orders[$j];
            
            // Apply setup hours offset to start times
            //$setupHours1 = (float)$order1['setup_hours'];
			$setupHours1 = (float)$order1['setup_hours'] + (float)$order1['breakdown_hours'];

            //$setupHours2 = (float)$order2['setup_hours'];
			$setupHours2 = (float)$order2['setup_hours'] + (float)$order2['breakdown_hours'];

            
            $start1 = strtotime($order1['start_date']) + ($setupHours1 * 3600);
            $end1 = strtotime($order1['end_date']);
            $start2 = strtotime($order2['start_date']) + ($setupHours2 * 3600);
            $end2 = strtotime($order2['end_date']);
            
            if (($start1 < $end2) && ($start2 < $end1)) {
                $overlaps[] = [$order1, $order2];
            }
        }
    }
    return $overlaps;
}

function calculateAlternatingSchedule($order1, $order2, $conn) {
    // Apply setup hours offset to start times
    //$setupHours1 = (float)$order1['setup_hours'];
	$setupHours1 = (float)$order1['setup_hours'] + (float)$order1['breakdown_hours'];
	
   // $setupHours2 = (float)$order2['setup_hours'];
	$setupHours2 = (float)$order2['setup_hours'] + (float)$order2['breakdown_hours'];
    
    $start1 = strtotime($order1['start_date']) + ($setupHours1 * 3600);
    $end1 = strtotime($order1['end_date']);
    $start2 = strtotime($order2['start_date']) + ($setupHours2 * 3600);
    $end2 = strtotime($order2['end_date']);

    $overlapStart = max($start1, $start2);
    $overlapEnd = min($end1, $end2);
    
    if ($overlapStart >= $overlapEnd) {
        // no overlap: keep original
        $remainingHours1 = generateRemainingHours($order1, $end1, $conn);
        $remainingHours2 = generateRemainingHours($order2, $end2, $conn);
        return [
            'order1' => [
                'end_date' => date('Y-m-d H:i:s', $end1),
                'total_hours' => computeAvailableHoursBetween($start1, $end1, $conn),
                'remaing_hours' => $remainingHours1
            ],
            'order2' => [
                'end_date' => date('Y-m-d H:i:s', $end2),
                'total_hours' => computeAvailableHoursBetween($start2, $end2, $conn),
                'remaing_hours' => $remainingHours2
            ]
        ];
    }

    // Compute available shift-hours (in hours) in the overlap window
    $overlapAvailableHours = computeAvailableHoursBetween($overlapStart, $overlapEnd, $conn);

    // cycles (in minutes) for both orders
    $cycle1_min = (float)$order1['cycle'];
    $cycle2_min = (float)$order2['cycle'];

    // How many cycles fit into the overlap available hours
    $total_cycles1 = floor(($overlapAvailableHours * 60) / max(0.0001, $cycle1_min)); // protect /0
    $total_cycles2 = floor(($overlapAvailableHours * 60) / max(0.0001, $cycle2_min));

    $alternating_cycles = min($total_cycles1, $total_cycles2);
    $alternating_time = ($alternating_cycles * $cycle1_min + $alternating_cycles * $cycle2_min) / 60.0; // in hours

    $remaining_cycles1 = max(0, $total_cycles1 - $alternating_cycles);
    $remaining_cycles2 = max(0, $total_cycles2 - $alternating_cycles);

    $remaining_time1 = ($remaining_cycles1 * $cycle1_min) / 60.0;
    $remaining_time2 = ($remaining_cycles2 * $cycle2_min) / 60.0;

    // Compute available hours for full original durations (including setup hours)
    $originalStart1 = strtotime($order1['start_date']);
    $originalStart2 = strtotime($order2['start_date']);
    
    $available_full1 = computeAvailableHoursBetween($originalStart1, $end1, $conn);
    $available_full2 = computeAvailableHoursBetween($originalStart2, $end2, $conn);

    // Original non-overlap available hours:
    $original_non_overlap1 = max(0, $available_full1 - $overlapAvailableHours);
    $original_non_overlap2 = max(0, $available_full2 - $overlapAvailableHours);

    // New total required working hours (in hours) for each order after alternating
    // Include setup hours in the total calculation
    $new_total1 = $setupHours1 + $original_non_overlap1 + $alternating_time + $remaining_time1;
    $new_total2 = $setupHours2 + $original_non_overlap2 + $alternating_time + $remaining_time2;

    // Find new calendar end timestamps by advancing through shifts from original start (including setup)
    $newEnd1 = advanceTimestampByWorkHours($originalStart1, $new_total1, $conn);
    $newEnd2 = advanceTimestampByWorkHours($originalStart2, $new_total2, $conn);

    // Generate per-date remaining-hours strings (respecting shifts)
    $remainingHours1 = generateRemainingHours($order1, $newEnd1, $conn);
    $remainingHours2 = generateRemainingHours($order2, $newEnd2, $conn);

    return [
        'order1' => [
            'end_date' => date('Y-m-d H:i:s', $newEnd1),
            'total_hours' => $new_total1,
            'remaing_hours' => $remainingHours1
        ],
        'order2' => [
            'end_date' => date('Y-m-d H:i:s', $newEnd2),
            'total_hours' => $new_total2,
            'remaing_hours' => $remainingHours2
        ]
    ];
}

/**
 * Generate remaining hours per date based on shifts between order start and provided new end timestamp.
 * Returns string like: "2025-01-09=8,2025-01-10=4"
 */
function generateRemainingHours($order, $newEndTimestamp, $conn) {
   // $setupHours = (float)$order['setup_hours'];
	$setupHours = (float)$order['setup_hours'] + (float)$order['breakdown_hours'];
    $start = strtotime($order['start_date']);
    $end = $newEndTimestamp;
    $remainingHours = [];
    $current = $start;

    // Handle setup hours - first period might be partially consumed by setup
    $setupSecondsRemaining = $setupHours * 3600;
    
    // iterate date by date
    while ($current < $end) {
        $currentDate = date('Y-m-d', $current);
        $dayStartTs = strtotime($currentDate . ' 00:00:00');
        $nextDay = strtotime('tomorrow', $current);
        $periodEnd = min($nextDay, $end);

        // For this date, compute total available shift-hours overlapping [current, periodEnd)
        $dateAvailable = 0.0;
        $shifts = getShiftsForDate($currentDate, $conn);
        if (!empty($shifts)) {
            foreach ($shifts as $shift) {
                $shiftStart = $shift['start_ts'];
                $shiftEnd = $shift['end_ts'];

                // Clamp to current -> periodEnd
                $segmentStart = max($current, $shiftStart);
                $segmentEnd = min($periodEnd, $shiftEnd);
                if ($segmentEnd > $segmentStart) {
                    $segmentHours = ($segmentEnd - $segmentStart) / 3600.0;
                    
                    // Deduct setup hours from the first available segment
                    if ($setupSecondsRemaining > 0) {
                        $setupHoursToDeduct = min($segmentHours, $setupSecondsRemaining / 3600);
                        $segmentHours -= $setupHoursToDeduct;
                        $setupSecondsRemaining -= $setupHoursToDeduct * 3600;
                    }
                    
                    $dateAvailable += $segmentHours;
                }
            }
            // round to 2 decimals like before
            if ($dateAvailable > 0) {
                $remainingHours[$currentDate] = round($dateAvailable, 2);
            }
        } else {
            // No shift defined for this date: treat as 0 available hours
            $remainingHours[$currentDate] = 0.00;
        }

        $current = $nextDay;
    }

    $formatted = [];
    foreach ($remainingHours as $date => $hours) {
        if ($hours > 0) {
            $formatted[] = "$date=$hours";
        }
    }

    return implode(',', $formatted);
}

/**
 * Store updated schedule in the in-memory map (no DB effect here).
 */
function storeUpdatedSchedule($orderId, $data) {
    global $updatedOrders;
    $updatedOrders[$orderId] = $data;
}

/**
 * Update order hours in DB (keeps existing behaviour)
 */
function updateOrderHours($orderId, $data, $conn) {
    $total_hours = (float)$data['total_hours'];
    $remaing_hours = $conn->real_escape_string($data['remaing_hours']);
    
    $sql = "UPDATE cnc_machine_table 
            SET total_hours = $total_hours, 
                remaing_hours = '$remaing_hours'
            WHERE id = $orderId";
    $conn->query($sql);
}

/* ---------------------------
   Helper functions for shift handling
   --------------------------- */

/**
 * Returns an array of shifts for the given date.
 * Each shift is an associative array with keys 'start_ts' and 'end_ts' (timestamps).
 *
 * Assumptions:
 * - working_hours.day_shifts stores a weekday number (1 = Monday, 2 = Tuesday, ... 7 = Sunday).
 * - If end_time <= start_time, it's treated as an overnight shift ending on the next day.
 * - If no shifts for that weekday, returns empty array.
 */
function getShiftsForDate($date, $conn) {
    // Determine weekday number for the date: 1 (Mon) - 7 (Sun)
    $weekdayNum = (int)date('N', strtotime($date));
    $shifts = [];

    $sql = "SELECT shift_name, start_time, end_time FROM working_hours WHERE day_shifts = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $weekdayNum);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $start_time_str = $row['start_time']; // HH:MM:SS
        $end_time_str = $row['end_time'];

        $start_ts = strtotime($date . ' ' . $start_time_str);
        $end_ts = strtotime($date . ' ' . $end_time_str);

        // If end is less-than-or-equal to start, treat as overnight into next day
        if ($end_ts <= $start_ts) {
            $end_ts = strtotime('tomorrow ' . $end_time_str, $start_ts);
        }

        $shifts[] = [
            'shift_name' => $row['shift_name'],
            'start_ts' => $start_ts,
            'end_ts' => $end_ts
        ];
    }
    return $shifts;
}

/**
 * Compute total available shift-hours (in hours, float) between two timestamps (start exclusive/inclusive consistent with prior code).
 * It sums overlap of provided interval with all shifts on each day.
 */
function computeAvailableHoursBetween($startTs, $endTs, $conn) {
    if ($endTs <= $startTs) return 0.0;

    $totalHours = 0.0;
    $current = $startTs;

    // iterate date by date
    while ($current < $endTs) {
        $currentDate = date('Y-m-d', $current);
        $dayStartTs = strtotime($currentDate . ' 00:00:00');
        $nextDay = strtotime('tomorrow', $current);
        $periodEnd = min($nextDay, $endTs);

        $shifts = getShiftsForDate($currentDate, $conn);
        if (!empty($shifts)) {
            foreach ($shifts as $shift) {
                $shiftStart = $shift['start_ts'];
                $shiftEnd = $shift['end_ts'];

                $segmentStart = max($current, $shiftStart);
                $segmentEnd = min($periodEnd, $shiftEnd);
                if ($segmentEnd > $segmentStart) {
                    $totalHours += ($segmentEnd - $segmentStart) / 3600.0;
                }
            }
        } else {
            // No shifts: add zero (honor shift system)
        }

        $current = $nextDay;
    }

    return round($totalHours, 6); // keep some precision
}

/**
 * Advance from a start timestamp through shift periods until the specified number of working hours
 * have been consumed. Returns the calendar timestamp where the work completes.
 *
 * If shifts are sparse and you cannot complete hours (no shifts found at all in future days),
 * this will continue scanning days forward indefinitely until hours are filled — BE SURE your working_hours
 * contain the appropriate future shifts for this to finish. (This matches expected scheduler behaviour.)
 */
function advanceTimestampByWorkHours($startTs, $hoursNeeded, $conn) {
    if ($hoursNeeded <= 0) return $startTs;

    $remainingSecondsNeeded = $hoursNeeded * 3600.0;
    $current = $startTs;

    // We'll loop day by day until we've consumed required seconds.
    // Safety: avoid infinite loops by setting a high day limit (e.g., 3650 days ~ 10 years).
    $maxDays = 3650;
    $daysLooped = 0;

    while ($remainingSecondsNeeded > 0 && $daysLooped < $maxDays) {
        $currentDate = date('Y-m-d', $current);
        $dayStartTs = strtotime($currentDate . ' 00:00:00');
        $nextDay = strtotime('tomorrow', $current);

        $shifts = getShiftsForDate($currentDate, $conn);

        if (!empty($shifts)) {
            // For each shift in that date, we attempt to take available seconds
            foreach ($shifts as $shift) {
                $shiftStart = $shift['start_ts'];
                $shiftEnd = $shift['end_ts'];

                // If current is after shift end, skip
                if ($current >= $shiftEnd) continue;

                // Determine where we can start within this shift
                $segmentStart = max($current, $shiftStart);
                $availableInShift = $shiftEnd - $segmentStart;
                if ($availableInShift <= 0) continue;

                if ($availableInShift >= $remainingSecondsNeeded) {
                    // we finish inside this shift
                    $finishTs = $segmentStart + $remainingSecondsNeeded;
                    return (int)$finishTs;
                } else {
                    // consume the whole availableInShift and continue
                    $remainingSecondsNeeded -= $availableInShift;
                    $current = $shiftEnd; // move to end of this shift
                }
            }
        }

        // Move to next day start
        $current = $nextDay;
        $daysLooped++;
    }

    // If we've hit the day limit or couldn't find enough shifts, we return current (best-effort).
    return (int)$current;
}
// Add these two new actions to your ajax_actions.php file

// ========================================
// GET CURRENT TASK PRIORITY FOR CNC MACHINE
// ========================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_current_task_priority_cnc') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId = intval($_REQUEST['table_id']);
    $partId = intval($_REQUEST['part_id']);
    
    $query = "SELECT id, priority, machine_id FROM cnc_machine_table 
              WHERE work_order_id = $workOrderId 
              AND table_id = $tableId 
              AND part_id = $partId 
              LIMIT 1";
    
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        echo json_encode([
            'success' => true,
            'task_id' => $row['id'],
            'priority' => $row['priority'],
            'machine_id' => $row['machine_id']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Task not found'
        ]);
    }
    exit;
}

// ========================================
// INSERT SCHEDULE BREAK AFTER CURRENT WORK ORDER FOR CNC MACHINE
// ========================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert_schedule_break_cnc') {
    $machineId = intval($_REQUEST['machine_id']);
    $tableId = intval($_REQUEST['table_id']);
    $duration = floatval($_REQUEST['duration']);
    $reason = mysqli_real_escape_string($conn, $_REQUEST['reason']);
    $afterTaskId = isset($_REQUEST['after_task_id']) ? intval($_REQUEST['after_task_id']) : 0;
    $afterPriority = isset($_REQUEST['after_priority']) ? intval($_REQUEST['after_priority']) : 0;
    
    // Validate inputs
    if ($machineId <= 0 || $tableId <= 0 || $duration < 0.5 || $duration > 10) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid input values']);
        exit;
    }
    
    // Start transaction
    mysqli_autocommit($conn, false);
    $error = false;
    $errorMessage = '';
    
    // Calculate new priority for the break (right after current task)
    $breakPriority = $afterPriority + 1;
    
    // Shift all tasks after this priority
    $shiftQuery = "UPDATE cnc_machine_table 
                   SET priority = priority + 1 
                   WHERE machine_id = $machineId 
                   AND table_id = $tableId 
                   AND priority >= $breakPriority";
    
    if (!mysqli_query($conn, $shiftQuery)) {
        $error = true;
        $errorMessage = mysqli_error($conn);
    }
    
    if (!$error) {
        // Get end date of the current task to start break after it
        $taskQuery = "SELECT end_date FROM cnc_machine_table WHERE id = $afterTaskId";
        $taskResult = mysqli_query($conn, $taskQuery);
        
        if ($taskResult && mysqli_num_rows($taskResult) > 0) {
            $taskRow = mysqli_fetch_assoc($taskResult);
            $startDate = $taskRow['end_date'];
            $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));
            
            // Calculate remaining hours (for multi-day breaks)
            $remainingHours = $duration;
            
            // Insert break as a special task
            $insertQuery = "INSERT INTO cnc_machine_table 
                           (machine_id, table_id, start_date, end_date, original_start_date, 
                            original_end_date, total_hours, original_total_hours, remaing_hours, 
                            original_remaing_hours, is_break, break_reason, priority, 
                            work_order_id, part_id, quantity, product_name)
                           VALUES ($machineId, $tableId, '$startDate', '$endDate', '$startDate', 
                                   '$endDate', $duration, $duration, $remainingHours, $remainingHours, 
                                   1, '$reason', $breakPriority, 0, 0, 0, 'BREAK: $reason')";
            
            if (!mysqli_query($conn, $insertQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
            }
        } else {
            $error = true;
            $errorMessage = "Current task not found";
        }
    }
    
    // Commit or rollback transaction
    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['status' => 'error', 'message' => $errorMessage]);
    } else {
        mysqli_commit($conn);
        
        // Recalculate all dates for this machine/table
        recalculateMachineDates_fororiginal($conn, $machineId, $tableId);
        processMachineScheduling($machineId, $conn);
        recalculateMachineDates($conn, $machineId, $tableId);
        
        echo json_encode(['status' => 'success', 'message' => 'Break scheduled successfully']);
    }
    
    mysqli_autocommit($conn, true);
    exit;
}
// ========================================
// GET CURRENT TASK PRIORITY FOR VAC MACHINE
// ========================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_current_task_priority_vac') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $machineId = intval($_REQUEST['machine_id']);
    $partId = intval($_REQUEST['part_id']);
    
    $query = "SELECT id, priority FROM vac_machine_table 
              WHERE work_order_id = $workOrderId 
              AND machine_id = $machineId 
              AND part_id = $partId 
              LIMIT 1";
    
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        echo json_encode([
            'success' => true,
            'task_id' => $row['id'],
            'priority' => $row['priority']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Task not found'
        ]);
    }
    exit;
}

// ========================================
// INSERT SCHEDULE BREAK AFTER CURRENT WORK ORDER FOR VAC MACHINE
// ========================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert_schedule_break_vac') {
    $machineId = intval($_REQUEST['machine_id']);
    $duration = floatval($_REQUEST['duration']);
    $reason = mysqli_real_escape_string($conn, $_REQUEST['reason']);
    $afterTaskId = isset($_REQUEST['after_task_id']) ? intval($_REQUEST['after_task_id']) : 0;
    $afterPriority = isset($_REQUEST['after_priority']) ? intval($_REQUEST['after_priority']) : 0;
    
    // Validate inputs
    if ($machineId <= 0 || $duration < 0.5 || $duration > 10) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid input values']);
        exit;
    }
    
    // Start transaction
    mysqli_autocommit($conn, false);
    $error = false;
    $errorMessage = '';
    
    // Calculate new priority for the break (right after current task)
    $breakPriority = $afterPriority + 1;
    
    // Shift all tasks after this priority
    $shiftQuery = "UPDATE vac_machine_table 
                   SET priority = priority + 1 
                   WHERE machine_id = $machineId 
                   AND priority >= $breakPriority";
    
    if (!mysqli_query($conn, $shiftQuery)) {
        $error = true;
        $errorMessage = mysqli_error($conn);
    }
    
    if (!$error) {
        // Get end date of the current task to start break after it
        $taskQuery = "SELECT end_date FROM vac_machine_table WHERE id = $afterTaskId";
        $taskResult = mysqli_query($conn, $taskQuery);
        
        if ($taskResult && mysqli_num_rows($taskResult) > 0) {
            $taskRow = mysqli_fetch_assoc($taskResult);
            $startDate = $taskRow['end_date'];
            $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));
            
            // Calculate remaining hours (for multi-day breaks)
            $remainingHours = $duration;
            
            // Insert break as a special task
            $insertQuery = "INSERT INTO vac_machine_table 
                           (machine_id, start_date, end_date, total_hours, remaing_hours,
                            is_break, break_reason, priority, work_order_id, part_id, 
                            quantity, product_name)
                           VALUES ($machineId, '$startDate', '$endDate', 
                                   $duration, $remainingHours, 1, '$reason', $breakPriority, 
                                   0, 0, 0, 'BREAK: $reason')";
            
            if (!mysqli_query($conn, $insertQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
            }
        } else {
            $error = true;
            $errorMessage = "Current task not found";
        }
    }
    
    // Commit or rollback transaction
    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['status' => 'error', 'message' => $errorMessage]);
    } else {
        mysqli_commit($conn);
        
        // Recalculate all dates for this machine
        recalculateMachineDatesforvac($conn, $machineId);
        
        echo json_encode(['status' => 'success', 'message' => 'Break scheduled successfully']);
    }
    
    mysqli_autocommit($conn, true);
    exit;
}

// ========================================
// RECALCULATE MACHINE DATES FOR VAC (Add this function if it doesn't exist)
// ========================================
function recalculateMachineDatesforvac($conn, $machineId) {
    set_time_limit(300); // Avoid timeout

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

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

    $taskResult = mysqli_query($conn,
        "SELECT id, total_hours AS hours_to_schedule
         FROM vac_machine_table
         WHERE machine_id = $machineId 
           AND end_date >= '$currentDateStr'
         ORDER BY priority"
    );

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

    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

    foreach ($tasks as $task) {
        $hoursRemaining = floatval($task['hours_to_schedule']);
        $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'];

                if ($shiftEnd <= $currentDateTime) continue;

                $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;

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

                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

        $remainingHoursStr = '';
        foreach ($dateHoursMap as $date => $hrs) {
            $remainingHoursStr .= $date . '=' . round($hrs, 2) . ',';
        }
        $remainingHoursStr = rtrim($remainingHoursStr, ',');

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

        $query = "UPDATE vac_machine_table SET
            start_date = '$startStr',
            end_date = '$endStr',
            shift_ids = '$firstShiftUsed',
            remaing_hours = '$remainingHoursStr'
            WHERE id = {$task['id']}";

        mysqli_query($conn, $query);
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Note: The recalculateMachineDatesforassmpu() function should already exist in your code
// Make sure it's available in this file or included properly
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_cnc') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId     = intval($_REQUEST['tableId']);
    $partId      = intval($_REQUEST['part_id']);
    $machineId   = intval($_REQUEST['machine_id']);
    $engineerId  = intval($_SESSION['engineer_id'] ?? 0);
    $actionType  = $conn->real_escape_string($_REQUEST['action_type']);
    $createdOn   = date('Y-m-d H:i:s');
    
    // ============================================
    // SPECIAL HANDLING FOR "BREAK" ACTION TYPE
    // ============================================
    if ($actionType === 'break') {
        // Get break parameters
        $breakDuration = isset($_REQUEST['break_duration']) ? floatval($_REQUEST['break_duration']) : 1.0;
        $breakReason = isset($_REQUEST['break_reason']) ? mysqli_real_escape_string($conn, $_REQUEST['break_reason']) : 'Scheduled Break';
        
        // Validate break duration
        if ($breakDuration < 0.5 || $breakDuration > 10) {
            $breakDuration = 1.0;
        }
        
        // Start transaction
        mysqli_autocommit($conn, false);
        $error = false;
        $errorMessage = '';
        
        // Get current task priority
        $priorityQuery = "SELECT id, priority, machine_id FROM cnc_machine_table 
                         WHERE work_order_id = $workOrderId 
                         AND table_id = $tableId 
                         AND part_id = $partId 
                         LIMIT 1";
        
        $priorityResult = mysqli_query($conn, $priorityQuery);
        
        if ($priorityResult && mysqli_num_rows($priorityResult) > 0) {
            $priorityRow = mysqli_fetch_assoc($priorityResult);
            $afterTaskId = $priorityRow['id'];
            $afterPriority = $priorityRow['priority'];
            $machineId = $priorityRow['machine_id'];
            
            // Calculate new priority for the break
            $breakPriority = $afterPriority + 1;
            
            // Shift all tasks after this priority
            $shiftQuery = "UPDATE cnc_machine_table 
                          SET priority = priority + 1 
                          WHERE machine_id = $machineId 
                          AND table_id = $tableId 
                          AND priority >= $breakPriority";
            
            if (!mysqli_query($conn, $shiftQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
            }
            
            if (!$error) {
                // Get end date of the current task
                $taskQuery = "SELECT end_date FROM cnc_machine_table WHERE id = $afterTaskId";
                $taskResult = mysqli_query($conn, $taskQuery);
                
                if ($taskResult && mysqli_num_rows($taskResult) > 0) {
                    $taskRow = mysqli_fetch_assoc($taskResult);
                    $startDate = $taskRow['end_date'];
                    $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($breakDuration * 3600));
                    
                    // Insert break as a special task
                    $insertBreakQuery = "INSERT INTO cnc_machine_table 
                                        (machine_id, table_id, start_date, end_date, 
                                         original_start_date, original_end_date, 
                                         total_hours, original_total_hours, 
                                         remaing_hours, original_remaing_hours,
                                         is_break, break_reason, priority, 
                                         work_order_id, part_id, quantity, product_name)
                                        VALUES ($machineId, $tableId, '$startDate', '$endDate', 
                                                '$startDate', '$endDate', $breakDuration, $breakDuration, 
                                                $breakDuration, $breakDuration, 1, '$breakReason', 
                                                $breakPriority, 0, 0, 0, 'BREAK: $breakReason')";
                    
                    if (!mysqli_query($conn, $insertBreakQuery)) {
                        $error = true;
                        $errorMessage = mysqli_error($conn);
                    }
                } else {
                    $error = true;
                    $errorMessage = "Current task not found";
                }
            }
        } else {
            $error = true;
            $errorMessage = "Task not found for scheduling break";
        }
        
        // Commit or rollback transaction
        if ($error) {
            mysqli_rollback($conn);
            
            // Still log the action even if scheduling fails
            $sql = "INSERT INTO machine_activity_log 
                    (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
            mysqli_query($conn, $sql);
            
            echo json_encode(["success" => false, "message" => "Break logged but scheduling failed: " . $errorMessage]);
        } else {
            mysqli_commit($conn);
            
            // Log the break action
            $sql = "INSERT INTO machine_activity_log 
                    (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
            mysqli_query($conn, $sql);
            
            // Recalculate all dates
            recalculateMachineDates_fororiginal($conn, $machineId, $tableId);
            processMachineScheduling($machineId, $conn);
            recalculateMachineDates($conn, $machineId, $tableId);
            
            echo json_encode(["success" => true, "message" => "Break scheduled and logged successfully"]);
        }
        
        mysqli_autocommit($conn, true);
        exit;
    }
    
    // ============================================
    // STANDARD ACTION HANDLING (start/pause/finish/breakdown/scheduler_break)
    // ============================================
    
    // Handle Scheduler Break logging (start / stop)
    if (in_array($actionType, ['scheduler_break_start', 'scheduler_break_stop'])) {
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        
        if (mysqli_query($conn, $sql)) {
            echo json_encode(["success" => true, "message" => "Scheduler break logged successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
        }
        exit;
    }
    
    // Normal action logging
    $sql = "INSERT INTO machine_activity_log 
            (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
            VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
    
    if ($actionType === 'finish') {
        $sqlFinish = "UPDATE cnc_machine_table 
                     SET finished = 1 
                     WHERE work_order_id = $workOrderId 
                     AND part_id = $partId";
        mysqli_query($conn, $sqlFinish);
    }
    
    if (mysqli_query($conn, $sql)) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    
    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_bulk_action_cnc') {
    include "config.php";
    session_start();
    
    $actionType = mysqli_real_escape_string($conn, $_POST['action_type']);
    $workOrders = json_decode($_POST['work_orders'], true);
    $engineerId = intval($_SESSION['user_id']);
    $createdOn  = date('Y-m-d H:i:s');
    
    $successCount = 0;
    $errorCount = 0;
    $skippedCount = 0;
    
    if (!is_array($workOrders) || empty($workOrders)) {
        echo json_encode(['success' => false, 'message' => 'No work orders provided.']);
        exit;
    }
    
    foreach ($workOrders as $order) {
        $workOrderId = intval($order['workOrderId'] ?? 0);
        $partId      = mysqli_real_escape_string($conn, $order['partId'] ?? '');
        $machineId   = intval($order['machineId'] ?? 0);
        $tableId     = intval($order['tableId'] ?? 0);
        
        if (!$workOrderId || !$machineId || !$engineerId || !$actionType) {
            $errorCount++;
            continue;
        }
        
        // ✅ Check current state before inserting
        $checkSql = "SELECT action_type 
                     FROM machine_activity_log 
                     WHERE machine_id = $machineId 
                     AND table_id = $tableId 
                     ORDER BY created_at DESC 
                     LIMIT 1";
        
        $checkResult = mysqli_query($conn, $checkSql);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $currentState = mysqli_fetch_assoc($checkResult)['action_type'];
            
            // ✅ Skip if already in desired state
            // If trying to start but already started, skip
            // If trying to pause but already paused, skip
            if (($actionType === 'start' && $currentState === 'start') || 
                ($actionType === 'pause' && $currentState === 'pause')) {
                $skippedCount++;
                continue; // Skip this machine
            }
        }
        
        // ✅ Insert only if state needs to change
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, '$partId', $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        
        if (mysqli_query($conn, $sql)) {
            // ✅ Optional: Mark as finished if action_type = 'finish'
            if ($actionType === 'finish') {
                $updateSql = "UPDATE cnc_machine_table 
                             SET finished = 1 
                             WHERE work_order_id = $workOrderId 
                             AND part_id = '$partId'";
                mysqli_query($conn, $updateSql);
            }
            $successCount++;
        } else {
            $errorCount++;
        }
    }
    
    // ✅ Better response message
    $message = "Processed: $successCount changed";
    if ($skippedCount > 0) {
        $message .= ", $skippedCount already in desired state";
    }
    if ($errorCount > 0) {
        $message .= ", $errorCount failed";
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'changed' => $successCount,
        'skipped' => $skippedCount,
        'errors' => $errorCount
    ]);
    exit;
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_count_cnc') {

    $partId = intval($_REQUEST['part_id']);
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId = intval($_REQUEST['tableId']);
    $machineId  = intval($_SESSION['machine_id'] ?? 0);
    $engineerId = intval($_SESSION['engineer_id'] ?? 0);
    $type = $conn->real_escape_string($_REQUEST['type']); // ok, nok, or quarantine
    $quantity = intval($_REQUEST['quantity'] ?? 1);
    $createdOn  = date('Y-m-d H:i:s');

    // New parameters for part selection
    $partIds = isset($_REQUEST['part_ids']) ? $conn->real_escape_string($_REQUEST['part_ids']) : '';
    $reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;

    if (!$workOrderId || !$machineId || !$engineerId || !$type) {
        echo json_encode(["success"=>false,"message"=>"Missing parameters"]);
        exit;
    }

    // For OK counts - simple increment/decrement without part selection
    if ($type === 'ok') {
        $checkSql = "SELECT id, quantity FROM part_count_log 
                     WHERE work_order_id = $workOrderId 
                     AND machine_id = $machineId 
                     AND part_id = $partId 
                     AND engineer_id = $engineerId 
                     AND type = '$type'";
        
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            $row = $checkResult->fetch_assoc();
            $existingId = $row['id'];
            $newQuantity = $row['quantity'] + $quantity;
            
            if ($newQuantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                exit;
            }
            
            $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
            
            if (mysqli_query($conn, $updateSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } else {
            if ($quantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Cannot decrement non-existent record"]);
                exit;
            }

            // Insert OK with created_at
            $insertSql = "INSERT INTO part_count_log 
                (work_order_id, machine_id, table_id, part_id, engineer_id, type, quantity, created_at) 
                VALUES ($workOrderId, $machineId, $tableId, $partId, $engineerId, '$type', $quantity, '$createdOn')";

            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        }
    } 

    // NOK / Quarantine
    else {

        // Positive quantity (increment)
        if ($quantity > 0) {

            if (empty($partIds)) {
                echo json_encode(["success"=>false,"message"=>"No parts selected"]);
                exit;
            }
            if (empty($reasonId)) {
                echo json_encode(["success"=>false,"message"=>"No reason selected"]);
                exit;
            }

            // Insert NOK / QUARANTINE with created_at
            $insertSql = "INSERT INTO part_count_log 
                (work_order_id, machine_id, table_id, part_id, engineer_id, type, partIds, reason_id, quantity, created_at) 
                VALUES ($workOrderId, $machineId, $tableId, $partId, $engineerId, '$type', '$partIds', $reasonId, $quantity, '$createdOn')";

            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } 

        // Negative quantity (undo)
        else if ($quantity < 0) {

            if (!empty($partIds) && !empty($reasonId)) {
                $checkSql = "SELECT id, quantity FROM part_count_log 
                             WHERE work_order_id = $workOrderId 
                             AND machine_id = $machineId 
                             AND part_id = $partId 
                             AND engineer_id = $engineerId 
                             AND type = '$type'
                             AND partIds = '$partIds' 
                             AND reason_id = $reasonId
                             ORDER BY id DESC LIMIT 1";
            } else {
                $checkSql = "SELECT id, quantity FROM part_count_log 
                             WHERE work_order_id = $workOrderId 
                             AND machine_id = $machineId 
                             AND part_id = $partId 
                             AND engineer_id = $engineerId 
                             AND type = '$type'
                             ORDER BY id DESC LIMIT 1";
            }
            
            $checkResult = $conn->query($checkSql);

            if ($checkResult->num_rows > 0) {
                $row = $checkResult->fetch_assoc();
                $existingId = $row['id'];
                $newQuantity = $row['quantity'] + $quantity;

                if ($newQuantity < 0) {
                    echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                    exit;
                }

                if ($newQuantity == 0) {
                    $deleteSql = "DELETE FROM part_count_log WHERE id = $existingId";
                    if (mysqli_query($conn, $deleteSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                } else {
                    $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
                    if (mysqli_query($conn, $updateSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                }
            } else {
                echo json_encode(["success"=>false,"message"=>"No record found to decrement"]);
                exit;
            }
        }
    }

    exit;
}
// Schedule break for all tables
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'schedule_break_all_tables_cnc') {
    $tables = json_decode($_POST['tables'], true);
    $duration = floatval($_POST['duration']);
    $reason = mysqli_real_escape_string($conn, $_POST['reason']);
    
    // Validate
    if (empty($tables) || $duration < 0.5 || $duration > 10) {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit;
    }
    
    mysqli_autocommit($conn, false);
    $error = false;
    $errorMessage = '';
    
    foreach ($tables as $table) {
        $tableId = intval($table['table_id']);
        $workOrderId = intval($table['work_order_id']);
        $partId = intval($table['part_id']);
        $machineId = intval($table['machine_id']);
        
        // Get current task priority
        $priorityQuery = "SELECT id, priority FROM cnc_machine_table 
                         WHERE work_order_id = $workOrderId 
                         AND table_id = $tableId 
                         AND part_id = $partId 
                         LIMIT 1";
        
        $priorityResult = mysqli_query($conn, $priorityQuery);
        
        if ($priorityResult && mysqli_num_rows($priorityResult) > 0) {
            $priorityRow = mysqli_fetch_assoc($priorityResult);
            $afterTaskId = $priorityRow['id'];
            $afterPriority = $priorityRow['priority'];
            $breakPriority = $afterPriority + 1;
            
            // Shift all tasks after this priority
            $shiftQuery = "UPDATE cnc_machine_table 
                          SET priority = priority + 1 
                          WHERE machine_id = $machineId 
                          AND table_id = $tableId 
                          AND priority >= $breakPriority";
            
            if (!mysqli_query($conn, $shiftQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
                break;
            }
            
            // Get end date of current task
            $taskQuery = "SELECT end_date FROM cnc_machine_table WHERE id = $afterTaskId";
            $taskResult = mysqli_query($conn, $taskQuery);
            
            if ($taskResult && mysqli_num_rows($taskResult) > 0) {
                $taskRow = mysqli_fetch_assoc($taskResult);
                $startDate = $taskRow['end_date'];
                $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));
                
                // Insert break
                $insertBreakQuery = "INSERT INTO cnc_machine_table 
                                    (machine_id, table_id, start_date, end_date, 
                                     original_start_date, original_end_date, 
                                     total_hours, original_total_hours, 
                                     remaing_hours, original_remaing_hours,
                                     is_break, break_reason, priority, 
                                     work_order_id, part_id, quantity, product_name, finished)
                                    VALUES ($machineId, $tableId, '$startDate', '$endDate', 
                                            '$startDate', '$endDate', $duration, $duration, 
                                            $duration, $duration, 1, '$reason', 
                                            $breakPriority, 0, 0, 0, 'BREAK: $reason', 0)";
                
                if (!mysqli_query($conn, $insertBreakQuery)) {
                    $error = true;
                    $errorMessage = mysqli_error($conn);
                    break;
                }
                
                // Recalculate dates for this machine
               
            } else {
                $error = true;
                $errorMessage = "Task not found for table $tableId";
                break;
            }
        } else {
            $error = true;
            $errorMessage = "Task not found for table $tableId";
            break;
        }
    }
     recalculateMachineDates_fororiginal($conn, $machineId, 1);    
				recalculateMachineDates_fororiginal($conn, $machineId, 2);
                processMachineScheduling($machineId, $conn);
                recalculateMachineDates($conn, $machineId, 1);
				recalculateMachineDates($conn, $machineId, 2);
    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['success' => false, 'message' => $errorMessage]);
    } else {
        mysqli_commit($conn);
        echo json_encode(['success' => true, 'message' => 'Break scheduled for all tables']);
    }
    
    mysqli_autocommit($conn, true);
    exit;
}

// Stop all breaks
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'stop_all_breaks_cnc') {
    // Mark all active breaks as finished
    $updateQuery = "UPDATE cnc_machine_table 
                    SET finished = 1 
                    WHERE is_break = 1 
                    AND finished = 0";
    
    if (mysqli_query($conn, $updateQuery)) {
        echo json_encode(['success' => true, 'message' => 'All breaks stopped']);
    } else {
        echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
    }
    exit;
}

// Check if break is active
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'check_break_status_cnc') {
    $checkQuery = "SELECT COUNT(*) as break_count 
                   FROM cnc_machine_table 
                   WHERE is_break = 1 
                   AND finished = 0";
    
    $result = mysqli_query($conn, $checkQuery);
    $row = mysqli_fetch_assoc($result);
    
    echo json_encode([
        'success' => true,
        'is_break_active' => ($row['break_count'] > 0)
    ]);
    exit;
}

///////////////////////////////////////////////////////// for cnc end //////////////////////////////////////////////////////
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_pu') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId     = intval($_REQUEST['tableId']);
    $partId      = intval($_REQUEST['part_id']);
    $machineId   = intval($_REQUEST['machine_id']);
    $engineerId  = intval($_SESSION['engineer_id'] ?? 0);
    $actionType  = $conn->real_escape_string($_REQUEST['action_type']);
    $createdOn   = date('Y-m-d H:i:s'); // ✅ Added timestamp here
    // ✅ Handle Scheduler Break logging (start / stop)
    if (in_array($actionType, ['scheduler_break_start', 'scheduler_break_stop'])) {
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        if (mysqli_query($conn, $sql)) {
            echo json_encode(["success" => true, "message" => "Scheduler break logged successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
        }
        exit;
    }

    $sql = "INSERT INTO machine_activity_log 
            (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
            VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
    if ($actionType === 'finish') {
        $sqlFinish = "
            UPDATE pu_machine_table 
            SET finished = 1 
            WHERE work_order_id = $workOrderId 
              AND part_id = $partId
        ";
        mysqli_query($conn, $sqlFinish);
    }
    if (mysqli_query($conn, $sql)) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_bulk_action_pu') {
    include "config.php";
    session_start();
    
    $actionType = mysqli_real_escape_string($conn, $_POST['action_type']);
    $workOrders = json_decode($_POST['work_orders'], true);
    $engineerId = intval($_SESSION['user_id']);
    $createdOn  = date('Y-m-d H:i:s');
    
    $successCount = 0;
    $errorCount = 0;
    $skippedCount = 0;
    
    if (!is_array($workOrders) || empty($workOrders)) {
        echo json_encode(['success' => false, 'message' => 'No work orders provided.']);
        exit;
    }
    
    foreach ($workOrders as $order) {
        $workOrderId = intval($order['workOrderId'] ?? 0);
        $partId      = mysqli_real_escape_string($conn, $order['partId'] ?? '');
        $machineId   = intval($order['machineId'] ?? 0);
        $tableId     = intval($order['tableId'] ?? 0);
        
        if (!$workOrderId || !$machineId || !$engineerId || !$actionType) {
            $errorCount++;
            continue;
        }

        $checkSql = "SELECT action_type 
                     FROM machine_activity_log 
                     WHERE machine_id = $machineId 
                     AND table_id = $tableId 
                     ORDER BY created_at DESC 
                     LIMIT 1";
        
        $checkResult = mysqli_query($conn, $checkSql);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $currentState = mysqli_fetch_assoc($checkResult)['action_type'];
            
          
            if (($actionType === 'start' && $currentState === 'start') || 
                ($actionType === 'pause' && $currentState === 'pause')) {
                $skippedCount++;
                continue; 
            }
        }
        
      
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, '$partId', $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        
        if (mysqli_query($conn, $sql)) {
            if ($actionType === 'finish') {
                $updateSql = "UPDATE pu_machine_table 
                             SET finished = 1 
                             WHERE work_order_id = $workOrderId 
                             AND part_id = '$partId'";
                mysqli_query($conn, $updateSql);
            }
            $successCount++;
        } else {
            $errorCount++;
        }
    }
    
    $message = "Processed: $successCount changed";
    if ($skippedCount > 0) {
        $message .= ", $skippedCount already in desired state";
    }
    if ($errorCount > 0) {
        $message .= ", $errorCount failed";
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'changed' => $successCount,
        'skipped' => $skippedCount,
        'errors' => $errorCount
    ]);
    exit;
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_count_pu') {

    $partId = intval($_REQUEST['part_id']);
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId = intval($_REQUEST['tableId']);
    $machineId  = intval($_SESSION['machine_id'] ?? 0);
    $engineerId = intval($_SESSION['engineer_id'] ?? 0);
    $type = $conn->real_escape_string($_REQUEST['type']); // ok, nok, or quarantine
    $quantity = intval($_REQUEST['quantity'] ?? 1);
    $createdOn  = date('Y-m-d H:i:s');

    // New parameters for part selection
    $partIds = isset($_REQUEST['part_ids']) ? $conn->real_escape_string($_REQUEST['part_ids']) : '';
    $reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;

    if (!$workOrderId || !$machineId || !$engineerId || !$type) {
        echo json_encode(["success"=>false,"message"=>"Missing parameters"]);
        exit;
    }

    // For OK counts - simple increment/decrement without part selection
    if ($type === 'ok') {
        $checkSql = "SELECT id, quantity FROM part_count_log 
                     WHERE work_order_id = $workOrderId 
                     AND machine_id = $machineId 
                     AND part_id = $partId 
                     AND engineer_id = $engineerId 
                     AND type = '$type'";
        
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            $row = $checkResult->fetch_assoc();
            $existingId = $row['id'];
            $newQuantity = $row['quantity'] + $quantity;
            
            if ($newQuantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                exit;
            }
            
            $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
            
            if (mysqli_query($conn, $updateSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } else {
            if ($quantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Cannot decrement non-existent record"]);
                exit;
            }

            // Insert OK with created_at
            $insertSql = "INSERT INTO part_count_log 
                (work_order_id, machine_id, table_id, part_id, engineer_id, type, quantity, created_at) 
                VALUES ($workOrderId, $machineId, $tableId, $partId, $engineerId, '$type', $quantity, '$createdOn')";

            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        }
    } 

    // NOK / Quarantine
    else {

        // Positive quantity (increment)
        if ($quantity > 0) {

            if (empty($partIds)) {
                echo json_encode(["success"=>false,"message"=>"No parts selected"]);
                exit;
            }
            if (empty($reasonId)) {
                echo json_encode(["success"=>false,"message"=>"No reason selected"]);
                exit;
            }

            // Insert NOK / QUARANTINE with created_at
            $insertSql = "INSERT INTO part_count_log 
                (work_order_id, machine_id, table_id, part_id, engineer_id, type, partIds, reason_id, quantity, created_at) 
                VALUES ($workOrderId, $machineId, $tableId, $partId, $engineerId, '$type', '$partIds', $reasonId, $quantity, '$createdOn')";

            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } 

        // Negative quantity (undo)
        else if ($quantity < 0) {

            if (!empty($partIds) && !empty($reasonId)) {
                $checkSql = "SELECT id, quantity FROM part_count_log 
                             WHERE work_order_id = $workOrderId 
                             AND machine_id = $machineId 
                             AND part_id = $partId 
                             AND engineer_id = $engineerId 
                             AND type = '$type'
                             AND partIds = '$partIds' 
                             AND reason_id = $reasonId
                             ORDER BY id DESC LIMIT 1";
            } else {
                $checkSql = "SELECT id, quantity FROM part_count_log 
                             WHERE work_order_id = $workOrderId 
                             AND machine_id = $machineId 
                             AND part_id = $partId 
                             AND engineer_id = $engineerId 
                             AND type = '$type'
                             ORDER BY id DESC LIMIT 1";
            }
            
            $checkResult = $conn->query($checkSql);

            if ($checkResult->num_rows > 0) {
                $row = $checkResult->fetch_assoc();
                $existingId = $row['id'];
                $newQuantity = $row['quantity'] + $quantity;

                if ($newQuantity < 0) {
                    echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                    exit;
                }

                if ($newQuantity == 0) {
                    $deleteSql = "DELETE FROM part_count_log WHERE id = $existingId";
                    if (mysqli_query($conn, $deleteSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                } else {
                    $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
                    if (mysqli_query($conn, $updateSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                }
            } else {
                echo json_encode(["success"=>false,"message"=>"No record found to decrement"]);
                exit;
            }
        }
    }

    exit;
}
// Schedule break for all tables (PU)
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'schedule_break_all_tables_pu') {
    $tables = json_decode($_POST['tables'], true);
    $duration = floatval($_POST['duration']);
    $reason = mysqli_real_escape_string($conn, $_POST['reason']);
    
    // Validate
    if (empty($tables) || $duration < 0.5 || $duration > 10) {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
        exit;
    }
    
    mysqli_autocommit($conn, false);
    $error = false;
    $errorMessage = '';
    
    foreach ($tables as $table) {
        $tableId = intval($table['table_id']);
        $workOrderId = intval($table['work_order_id']);
        $partId = intval($table['part_id']);
        $machineId = intval($table['machine_id']);
        
        // Get current task priority
        $priorityQuery = "SELECT id, priority FROM pu_machine_table 
                         WHERE work_order_id = $workOrderId 
                         AND table_id = $tableId 
                         AND part_id = $partId 
                         LIMIT 1";
        
        $priorityResult = mysqli_query($conn, $priorityQuery);
        
        if ($priorityResult && mysqli_num_rows($priorityResult) > 0) {
            $priorityRow = mysqli_fetch_assoc($priorityResult);
            $afterTaskId = $priorityRow['id'];
            $afterPriority = $priorityRow['priority'];
            $breakPriority = $afterPriority + 1;
            
            // Shift all tasks after this priority
            $shiftQuery = "UPDATE pu_machine_table 
                          SET priority = priority + 1 
                          WHERE machine_id = $machineId 
                          AND table_id = $tableId 
                          AND priority >= $breakPriority";
            
            if (!mysqli_query($conn, $shiftQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
                break;
            }
            
            // Get end date of current task
            $taskQuery = "SELECT end_date FROM pu_machine_table WHERE id = $afterTaskId";
            $taskResult = mysqli_query($conn, $taskQuery);
            
            if ($taskResult && mysqli_num_rows($taskResult) > 0) {
                $taskRow = mysqli_fetch_assoc($taskResult);
                $startDate = $taskRow['end_date'];
                $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));
                
                // Insert break
                $insertBreakQuery = "INSERT INTO pu_machine_table 
                                    (machine_id, table_id, start_date, end_date, 
                                     original_start_date, original_end_date, 
                                     total_hours, original_total_hours, 
                                     remaing_hours, original_remaing_hours,
                                     is_break, break_reason, priority, 
                                     work_order_id, part_id, quantity, product_name, finished)
                                    VALUES ($machineId, $tableId, '$startDate', '$endDate', 
                                            '$startDate', '$endDate', $duration, $duration, 
                                            $duration, $duration, 1, '$reason', 
                                            $breakPriority, 0, 0, 0, 'BREAK: $reason', 0)";
                
                if (!mysqli_query($conn, $insertBreakQuery)) {
                    $error = true;
                    $errorMessage = mysqli_error($conn);
                    break;
                }
            } else {
                $error = true;
                $errorMessage = "Task not found for table $tableId";
                break;
            }
        } else {
            $error = true;
            $errorMessage = "Task not found for table $tableId";
            break;
        }
    }
    
    // Recalculate dates for all tables
    if (!$error && !empty($machineId)) {
        // Assuming you have similar recalculate functions for PU
        // Adjust table IDs based on your actual number of tables
        $machine_id_base = intval($_REQUEST['machine_id']);
        
        
        
        processMachineScheduling($machine_id_base, $conn);
        
       
    }
    
    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['success' => false, 'message' => $errorMessage]);
    } else {
        mysqli_commit($conn);
        echo json_encode(['success' => true, 'message' => 'Break scheduled for all tables']);
    }
    
    mysqli_autocommit($conn, true);
    exit;
}

// Stop all breaks (PU)
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'stop_all_breaks_pu') {
    // Mark all active breaks as finished
    $updateQuery = "UPDATE pu_machine_table 
                    SET finished = 1 
                    WHERE is_break = 1 
                    AND finished = 0";
    
    if (mysqli_query($conn, $updateQuery)) {
        echo json_encode(['success' => true, 'message' => 'All breaks stopped']);
    } else {
        echo json_encode(['success' => false, 'message' => mysqli_error($conn)]);
    }
    exit;
}

// Check if break is active (PU)
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'check_break_status_pu') {
    $checkQuery = "SELECT COUNT(*) as break_count 
                   FROM pu_machine_table 
                   WHERE is_break = 1 
                   AND finished = 0";
    
    $result = mysqli_query($conn, $checkQuery);
    $row = mysqli_fetch_assoc($result);
    
    echo json_encode([
        'success' => true,
        'is_break_active' => ($row['break_count'] > 0)
    ]);
    exit;
}
////////////////////////////////////////////// for pu ends /////////////////////////////////////
// Replace your existing log_action_vac with this enhanced version

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_vac') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId     = intval($_REQUEST['tableId'] ?? 0);
    $partId      = intval($_REQUEST['part_id'] ?? 0);
    $machineId   = intval($_SESSION['machine_id'] ?? 0);
    $engineerId  = intval($_SESSION['engineer_id'] ?? 0);
    $actionType  = $conn->real_escape_string($_REQUEST['action_type']);
    $breakdownReason = isset($_REQUEST['breakdown_reason']) ? intval($_REQUEST['breakdown_reason']) : null;
    $createdOn   = date('Y-m-d H:i:s');
    
    // Basic validation
    if (!$workOrderId || !$machineId || !$engineerId || !$actionType) {
        echo json_encode(["success" => false, "message" => "Missing parameters"]);
        exit;
    }

    // ============================================
    // SPECIAL HANDLING FOR "BREAK" ACTION TYPE
    // ============================================
    if ($actionType === 'break') {
        // Get break parameters (duration and reason) - set defaults if not provided
        $breakDuration = isset($_REQUEST['break_duration']) ? floatval($_REQUEST['break_duration']) : 1.0;
        $breakReason = isset($_REQUEST['break_reason']) ? mysqli_real_escape_string($conn, $_REQUEST['break_reason']) : 'Scheduled Break';
        
        // Validate break duration
        if ($breakDuration < 0.5 || $breakDuration > 10) {
            $breakDuration = 1.0; // Default to 1 hour if invalid
        }
        
        // Start transaction
        mysqli_autocommit($conn, false);
        $error = false;
        $errorMessage = '';
        
        // Get current task priority
        $priorityQuery = "SELECT id, priority FROM vac_machine_table 
                         WHERE work_order_id = $workOrderId 
                         AND machine_id = $machineId 
                         AND part_id = $partId 
                         LIMIT 1";
        
        $priorityResult = mysqli_query($conn, $priorityQuery);
        
        if ($priorityResult && mysqli_num_rows($priorityResult) > 0) {
            $priorityRow = mysqli_fetch_assoc($priorityResult);
            $afterTaskId = $priorityRow['id'];
            $afterPriority = $priorityRow['priority'];
            
            // Calculate new priority for the break (right after current task)
            $breakPriority = $afterPriority + 1;
            
            // Shift all tasks after this priority
            $shiftQuery = "UPDATE vac_machine_table 
                          SET priority = priority + 1 
                          WHERE machine_id = $machineId 
                          AND priority >= $breakPriority";
            
            if (!mysqli_query($conn, $shiftQuery)) {
                $error = true;
                $errorMessage = mysqli_error($conn);
            }
            
            if (!$error) {
                // Get end date of the current task to start break after it
                $taskQuery = "SELECT end_date FROM vac_machine_table WHERE id = $afterTaskId";
                $taskResult = mysqli_query($conn, $taskQuery);
                
                if ($taskResult && mysqli_num_rows($taskResult) > 0) {
                    $taskRow = mysqli_fetch_assoc($taskResult);
                    $startDate = $taskRow['end_date'];
                    $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($breakDuration * 3600));
                    
                    // Insert break as a special task in vac_machine_table
                    $insertBreakQuery = "INSERT INTO vac_machine_table 
                                        (machine_id, start_date, end_date, total_hours, remaing_hours,
                                         is_break, break_reason, priority, work_order_id, part_id, 
                                         quantity, product_name)
                                        VALUES ($machineId, '$startDate', '$endDate', 
                                                $breakDuration, $breakDuration, 1, '$breakReason', $breakPriority, 
                                                0, 0, 0, 'BREAK: $breakReason')";
                    
                    if (!mysqli_query($conn, $insertBreakQuery)) {
                        $error = true;
                        $errorMessage = mysqli_error($conn);
                    }
                } else {
                    $error = true;
                    $errorMessage = "Current task not found";
                }
            }
        } else {
            $error = true;
            $errorMessage = "Task not found for scheduling break";
        }
        
        // Commit or rollback transaction
        if ($error) {
            mysqli_rollback($conn);
            
            // Still log the action in machine_activity_log even if scheduling fails
            $sql = "INSERT INTO machine_activity_log 
                    (work_order_id, part_id, machine_id, engineer_id, action_type, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $engineerId, '$actionType', '$createdOn')";
            mysqli_query($conn, $sql);
            
            echo json_encode(["success" => false, "message" => "Break logged but scheduling failed: " . $errorMessage]);
        } else {
            mysqli_commit($conn);
            
            // Log the break action in machine_activity_log
            $sql = "INSERT INTO machine_activity_log 
                    (work_order_id, part_id, machine_id, engineer_id, action_type, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $engineerId, '$actionType', '$createdOn')";
            mysqli_query($conn, $sql);
            
            // Recalculate all dates for this machine
            recalculateMachineDatesforvac($conn, $machineId);
            
            echo json_encode(["success" => true, "message" => "Break scheduled and logged successfully"]);
        }
        
        mysqli_autocommit($conn, true);
        exit;
    }

    // ============================================
    // STANDARD ACTION HANDLING (pause, start, finish, breakdown)
    // ============================================
    
    // Insert Action Log
    if ($actionType === 'breakdown' && $breakdownReason) {
        $sql = "
            INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, breakdown_reason, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $breakdownReason, '$createdOn')
        ";
    } else {
        $sql = "
            INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', '$createdOn')
        ";
    }
    
    $result = mysqli_query($conn, $sql);
    
    if ($result) {
        // Mark record finished when action = 'finish'
        if ($actionType === 'finish') {
            $sqlFinish = "
                UPDATE vac_machine_table 
                SET finished = 1 
                WHERE work_order_id = $workOrderId 
                  AND part_id = $partId
            ";
            mysqli_query($conn, $sqlFinish);
        }
        
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    
    exit;
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_count_vac') {

    $workOrderId = intval($_REQUEST['work_order_id']);
    $machineId  = intval($_SESSION['machine_id'] ?? 0);
    $engineerId = intval($_SESSION['engineer_id'] ?? 0);
    $type = $conn->real_escape_string($_REQUEST['type']); // ok, nok, or quarantine
    $quantity = intval($_REQUEST['quantity'] ?? 1);
    
    // New parameters for part selection
    $partIds = isset($_REQUEST['part_ids']) ? $conn->real_escape_string($_REQUEST['part_ids']) : '';
    $reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;
    
    $partId = isset($_REQUEST['part_id']) ? intval($_REQUEST['part_id']) : 0;
    $createdOn = date('Y-m-d H:i:s');
    
    // If we have part_ids from a set but no specific part_id, use the first part from the set
    if ($partId == 0 && !empty($partIds)) {
        $partIdsArray = explode(",", $partIds);
        $partId = intval($partIdsArray[0]);
    }

    if (!$workOrderId || !$machineId || !$engineerId || !$type) {
        echo json_encode(["success"=>false,"message"=>"Missing parameters"]);
        exit;
    }

    // For OK counts - simple increment/decrement without part selection
    if ($type === 'ok') {
        $checkSql = "SELECT id, quantity FROM part_count_log 
                     WHERE work_order_id = $workOrderId 
                     AND machine_id = $machineId 
                     AND part_id = $partId 
                     AND engineer_id = $engineerId 
                     AND type = '$type'";
        
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            $row = $checkResult->fetch_assoc();
            $existingId = $row['id'];
            $newQuantity = $row['quantity'] + $quantity;
            
            if ($newQuantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                exit;
            }
            
            $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
            
            if (mysqli_query($conn, $updateSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } else {
            if ($quantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Cannot decrement non-existent record"]);
                exit;
            }
            
            $insertSql = "INSERT INTO part_count_log 
                    (work_order_id, machine_id, part_id, engineer_id, type, quantity, created_at) 
                    VALUES ($workOrderId, $machineId, $partId, $engineerId, '$type', $quantity, '$createdOn')";
            
            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        }
    } 
    // For NOK and Quarantine
    else {
        // For positive quantities (increment) - requires part selection and reason
        if ($quantity > 0) {
            if (empty($partIds)) {
                echo json_encode(["success"=>false,"message"=>"No parts selected"]);
                exit;
            }
            
            if (empty($reasonId)) {
                echo json_encode(["success"=>false,"message"=>"No reason selected"]);
                exit;
            }

            $insertSql = "INSERT INTO part_count_log 
                    (work_order_id, machine_id, part_id, engineer_id, type, partIds, reason_id, quantity, created_at) 
                    VALUES ($workOrderId, $machineId, $partId, $engineerId, '$type', '$partIds', $reasonId, $quantity, '$createdOn')";
            
            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } 
        // For negative quantities (decrement) - find MOST RECENT record and decrement it
        else if ($quantity < 0) {
            $checkSql = "SELECT id, quantity, partIds, reason_id FROM part_count_log 
                         WHERE work_order_id = $workOrderId 
                         AND machine_id = $machineId 
                         AND part_id = $partId 
                         AND engineer_id = $engineerId 
                         AND type = '$type'
                         ORDER BY id DESC 
                         LIMIT 1";
            
            $checkResult = $conn->query($checkSql);
            
            if ($checkResult->num_rows > 0) {
                $row = $checkResult->fetch_assoc();
                $existingId = $row['id'];
                $currentQuantity = $row['quantity'];
                
                $newQuantity = $currentQuantity + $quantity;
                
                if ($newQuantity < 0) {
                    echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                    exit;
                }
                
                if ($newQuantity == 0) {
                    $deleteSql = "DELETE FROM part_count_log WHERE id = $existingId";
                    if (mysqli_query($conn, $deleteSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                } else {
                    $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
                    if (mysqli_query($conn, $updateSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                }
            } else {
                echo json_encode(["success"=>false,"message"=>"No recent $type entry found to decrement"]);
                exit;
            }
        }
    }
    exit;
}
/////////////////////////////////////////////////////// end for vac ///////////////////////////////////////////////////



if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_assambly') {

    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId     = intval($_REQUEST['tableId'] ?? 0);
    $partId      = intval($_REQUEST['part_id'] ?? 0);
    $machineId   = intval($_SESSION['machine_id'] ?? 0);
    $engineerId  = intval($_SESSION['engineer_id'] ?? 0);
    $actionType  = $conn->real_escape_string($_REQUEST['action_type']);
    $breakdownReason = isset($_REQUEST['breakdown_reason']) ? intval($_REQUEST['breakdown_reason']) : null;
    $createdOn   = date('Y-m-d H:i:s');

    // Basic validation
    if (!$workOrderId || !$machineId || !$engineerId || !$actionType) {
        echo json_encode(["success" => false, "message" => "Missing parameters"]);
        exit;
    }

    // -------------------------------------
    // Insert Action Log (NO PREPARE, NO BIND)
    // -------------------------------------

    if ($actionType === 'breakdown' && $breakdownReason) {

        $sql = "
            INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, breakdown_reason, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $breakdownReason, '$createdOn')
        ";

    } else {

        $sql = "
            INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', '$createdOn')
        ";
    }

    $result = mysqli_query($conn, $sql);

    if ($result) {

        // Mark record finished when action = 'finish'
        if ($actionType === 'finish') {
            $sqlFinish = "
                UPDATE assbly_machine_table 
                SET finished = 1 
                WHERE work_order_id = $workOrderId 
                  AND part_id = $partId
            ";
            mysqli_query($conn, $sqlFinish);
        }

        echo json_encode(["success" => true]);

    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }

    exit;
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_count_assambly') {

    $workOrderId = intval($_REQUEST['work_order_id']);
    $machineId  = intval($_SESSION['machine_id'] ?? 0);
    $engineerId = intval($_SESSION['engineer_id'] ?? 0);
    $type = $conn->real_escape_string($_REQUEST['type']); // ok, nok, or quarantine
    $quantity = intval($_REQUEST['quantity'] ?? 1);
    
    // New parameters for part selection
    $partIds = isset($_REQUEST['part_ids']) ? $conn->real_escape_string($_REQUEST['part_ids']) : '';
    $reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;
    
    $partId = isset($_REQUEST['part_id']) ? intval($_REQUEST['part_id']) : 0;
    $createdOn = date('Y-m-d H:i:s');
    
    // If we have part_ids from a set but no specific part_id, use the first part from the set
    if ($partId == 0 && !empty($partIds)) {
        $partIdsArray = explode(",", $partIds);
        $partId = intval($partIdsArray[0]);
    }

    if (!$workOrderId || !$machineId || !$engineerId || !$type) {
        echo json_encode(["success"=>false,"message"=>"Missing parameters"]);
        exit;
    }

    // For OK counts - simple increment/decrement without part selection
    if ($type === 'ok') {
        $checkSql = "SELECT id, quantity FROM part_count_log 
                     WHERE work_order_id = $workOrderId 
                     AND machine_id = $machineId 
                     AND part_id = $partId 
                     AND engineer_id = $engineerId 
                     AND type = '$type'";
        
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            $row = $checkResult->fetch_assoc();
            $existingId = $row['id'];
            $newQuantity = $row['quantity'] + $quantity;
            
            if ($newQuantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                exit;
            }
            
            $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
            
            if (mysqli_query($conn, $updateSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } else {
            if ($quantity < 0) {
                echo json_encode(["success"=>false,"message"=>"Cannot decrement non-existent record"]);
                exit;
            }
            
            $insertSql = "INSERT INTO part_count_log 
                    (work_order_id, machine_id, part_id, engineer_id, type, quantity, created_at) 
                    VALUES ($workOrderId, $machineId, $partId, $engineerId, '$type', $quantity, '$createdOn')";
            
            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        }
    } 
    // For NOK and Quarantine
    else {
        // For positive quantities (increment) - requires part selection and reason
        if ($quantity > 0) {
            if (empty($partIds)) {
                echo json_encode(["success"=>false,"message"=>"No parts selected"]);
                exit;
            }
            
            if (empty($reasonId)) {
                echo json_encode(["success"=>false,"message"=>"No reason selected"]);
                exit;
            }

            $insertSql = "INSERT INTO part_count_log 
                    (work_order_id, machine_id, part_id, engineer_id, type, partIds, reason_id, quantity, created_at) 
                    VALUES ($workOrderId, $machineId, $partId, $engineerId, '$type', '$partIds', $reasonId, $quantity, '$createdOn')";
            
            if (mysqli_query($conn, $insertSql)) {
                echo json_encode(["success"=>true]);
            } else {
                echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            }
        } 
        // For negative quantities (decrement) - find MOST RECENT record and decrement it
        else if ($quantity < 0) {
            $checkSql = "SELECT id, quantity, partIds, reason_id FROM part_count_log 
                         WHERE work_order_id = $workOrderId 
                         AND machine_id = $machineId 
                         AND part_id = $partId 
                         AND engineer_id = $engineerId 
                         AND type = '$type'
                         ORDER BY id DESC 
                         LIMIT 1";
            
            $checkResult = $conn->query($checkSql);
            
            if ($checkResult->num_rows > 0) {
                $row = $checkResult->fetch_assoc();
                $existingId = $row['id'];
                $currentQuantity = $row['quantity'];
                
                $newQuantity = $currentQuantity + $quantity;
                
                if ($newQuantity < 0) {
                    echo json_encode(["success"=>false,"message"=>"Count cannot be negative"]);
                    exit;
                }
                
                if ($newQuantity == 0) {
                    $deleteSql = "DELETE FROM part_count_log WHERE id = $existingId";
                    if (mysqli_query($conn, $deleteSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                } else {
                    $updateSql = "UPDATE part_count_log SET quantity = $newQuantity WHERE id = $existingId";
                    if (mysqli_query($conn, $updateSql)) {
                        echo json_encode(["success"=>true]);
                    } else {
                        echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
                    }
                }
            } else {
                echo json_encode(["success"=>false,"message"=>"No recent $type entry found to decrement"]);
                exit;
            }
        }
    }
    exit;
}
//////////////////////////////////////////////// end assmbly
?>

