<?php
include("../../../include/startup.php");

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
$todays = date('Y-m-d');
function recalculateMachineDatesforpu($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 pu_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;

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

                // Update current pointer
                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

            if ($hoursRemaining > 0) {
                $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 pu_machine_table SET
            start_date = '$startStr',
            end_date = '$endStr',
            shift_ids = '$firstShiftUsed',
            remaing_hours = '$remainingHoursStr'
            WHERE id = {$task['id']}";

        mysqli_query($conn, $query);
    }
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'select_order_for_pu') {
    
    $json_data   = $_REQUEST['work_orders'];
    $work_orders = json_decode($json_data, true);

    $inserted           = false; 
    $processed_machines = []; // store unique machine IDs

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

    foreach ($work_orders as $item) {
        $id            = (int)$item['id'];
        $work_order_id = (int)$item['work_order_id'];
        $part_id       = (int)$item['part_id'];
        $machine_id = (int)$item['machine_id'];
        $table_id = $machine_id % 10; // Get last digit
        $v_machine_id = intval($machine_id / 10);

        if (!isset($processed_machines[$machine_id])) {
            $processed_machines[$machine_id] = true;
        }

        $selectQuery = "
            SELECT part_id, id, parent_ids, end_date, quantity, product_name, total_hours, set_id 
            FROM manufacture_machine_table 
            WHERE id = $id";
        $result = $conn->query($selectQuery);

        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $quantity     = (int)$row['quantity'];
            $product_name = $row['product_name'];
            $total_hoursss  = $row['total_hours'];
            $set_id       = $row['set_id']; 
			$manuf_id       = $row['id'];

            // Get route info
            if ($set_id > 0) {
                $query_route = "SELECT operation_time, parts_per_operation, set_time, machine_high_priority FROM set_route_details WHERE set_id = $set_id";
            } else {
                $query_route = "SELECT operation_time, parts_per_operation, set_time, machine_high_priority FROM route_details WHERE item_id = $part_id";
            }

            $result_route = $conn->query($query_route);
            if ($result_route && $result_route->num_rows > 0) {
                $row_route = $result_route->fetch_assoc();
				$set_time = $row_route['set_time']; // e.g. "01:00:00" or "00:30:00"

				list($hours, $minutes, $seconds) = explode(':', $set_time);
				$setup_hours = $hours + ($minutes / 60) + ($seconds / 3600);
                // Convert operation_time (HH:MM:SS) into total minutes
                if (!empty($row_route['operation_time'])) {
                    list($h, $m, $s) = explode(":", $row_route['operation_time']);
                    $operation_time = ($h * 60) + $m + ($s / 60); // total minutes
                } else {
                    $operation_time = 1; // fallback 1 minute
                }

                $parts_per_operation = (!empty($row_route['parts_per_operation']) && $row_route['parts_per_operation'] > 0) 
                    ? (float)$row_route['parts_per_operation'] 
                    : 1;

                // Cycle time per part in whole minutes
                $cycle = (int) round($operation_time / $parts_per_operation);

            } else {
                $cycle = 1; // fallback
            }
			 $total_hours = $total_hoursss + $setup_hours; 

            // Get next priority
            $query_priority = "SELECT MAX(priority) AS priority FROM pu_machine_table WHERE machine_id = $machine_id";
            $result_priority = mysqli_query($conn, $query_priority);
            if ($result_priority && mysqli_num_rows($result_priority) > 0) {
                $rowp = mysqli_fetch_assoc($result_priority);
                $currentPriority = $rowp['priority'] ?? 0;
                $new_priority = $currentPriority + 1;
            } else {
                $new_priority = 1;
            }

            // ---------------------------
            // Scheduling calculation before insert
            // ---------------------------
            $hoursRemaining = floatval($total_hours);
            $dateHoursMap = [];
            $taskStartTime = null;
            $taskEndTime = null;
            $firstShiftUsed = null;
            $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

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

            // ---------------------------
            // Insert directly with scheduling data
            // ---------------------------
			
            $insertQuery = "
                INSERT INTO pu_machine_table 
                (machine_id, manuf_id, v_machine_id, table_id, work_order_id, part_id, end_date, start_date, quantity, shift_ids, product_name, total_hours, total_hours_update, setup_hours, cycle, set_id, priority, remaing_hours)
                VALUES (
                    $machine_id, 
					$manuf_id,
					$v_machine_id, 
					$table_id,
                    $work_order_id,
                    $part_id,
                    '$endStr',
                    '$startStr',
                    $quantity,
                    '$firstShiftUsed',
                    '$product_name',
                    '$total_hours',
					'$total_hoursss',
					'$setup_hours',
                    '$cycle',
                    '$set_id',
                    '$new_priority',
                    '$remainingHoursStr'
                )";

            if ($conn->query($insertQuery)) {
                $inserted = true;
               $updateQuery = "UPDATE manufacture_machine_table SET in_scheduler_check = 1 WHERE id = $id";
               $conn->query($updateQuery);
            }
        } 
    }

    // Recalculate for other tasks on affected machines
    foreach (array_keys($processed_machines) as $machine_id) {
        recalculateMachineDatesforpu($conn, $machine_id);
    }

    if ($inserted) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'failed', 'message' => 'No rows inserted']);
    }
}

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

    $taskId = intval($_REQUEST['task_id']);
    $newMachineId = intval($_REQUEST['new_machine_id']);

    // Existing logic
    $table_id = $newMachineId % 10;

    // ✅ NEW: extract only machine (without table)
    $v_machine_id = intval($newMachineId / 10);

    $partId = intval($_REQUEST['part_id']);
    $workOrderId = intval($_REQUEST['work_order_id']);

    $leftNeighborPriority = isset($_REQUEST['left_neighbor_priority']) ? ($_REQUEST['left_neighbor_priority']) : null;
    $leftNeighborTaskId = isset($_REQUEST['left_neighbor_task_id']) ? ($_REQUEST['left_neighbor_task_id']) : null;

    $draggedTask = $conn->query("SELECT * FROM pu_machine_table WHERE id = $taskId")->fetch_assoc();

    $originalTasks = [];
    $originalResult = mysqli_query($conn,
        "SELECT id, priority 
         FROM pu_machine_table 
         WHERE machine_id = {$draggedTask['machine_id']}
           AND end_date >= '$todays'
         ORDER BY priority"
    );

    while ($row = mysqli_fetch_assoc($originalResult)) {
        $originalTasks[] = $row;
    }

    $newTasks = [];
    $newResult = mysqli_query($conn,
        "SELECT id, priority 
         FROM pu_machine_table 
         WHERE machine_id = $newMachineId
           AND end_date >= '$todays'
         ORDER BY priority"
    );

    while ($row = mysqli_fetch_assoc($newResult)) {
        $newTasks[] = $row;
    }

    // Reorder original machine
    $newPriority = 1;
    foreach ($originalTasks as $task) {
        if ($task['id'] != $taskId) {
            mysqli_query($conn,
                "UPDATE pu_machine_table SET priority = $newPriority 
                 WHERE id = {$task['id']}"
            );
            $newPriority++;
        }
    }

    // Determine insert position
    $insertPriority = 1;

    if ($leftNeighborPriority !== null) {
        $insertPriority = (int)$leftNeighborPriority + 1;

        // Shift priorities in new machine
        foreach ($newTasks as $task) {
            if ($task['priority'] >= $insertPriority) {
                mysqli_query($conn,
                    "UPDATE pu_machine_table SET priority = priority + 1 
                     WHERE id = {$task['id']}"
                );
            }
        }
    }

    // ✅ FINAL UPDATE (only addition is v_machine_id)
    mysqli_query($conn,
        "UPDATE pu_machine_table SET 
         machine_id = $newMachineId,
         table_id = $table_id,
         v_machine_id = $v_machine_id,
         priority = $insertPriority
         WHERE id = $taskId"
    );

    // Recalculate schedules
    recalculateMachineDatesforpu($conn, $draggedTask['machine_id']);
    recalculateMachineDatesforpu($conn, $newMachineId);

    echo json_encode([
        'status' => 'success', 
        'message' => 'Task and related priorities updated successfully'
    ]);
}

else if(isset($_REQUEST['action']) && $_REQUEST['action']=='add_pu_break'){
    $machineId = intval($_REQUEST['machine_id']);
	$table_id = $machineId % 10;
    $duration = floatval($_REQUEST['duration']);
    $reason = mysqli_real_escape_string($conn, $_REQUEST['reason']);
    $highestPriorityTaskId = isset($_REQUEST['highest_priority_task_id']) ? intval($_REQUEST['highest_priority_task_id']) : 0;
    $highestPriority = isset($_REQUEST['highest_priority']) ? intval($_REQUEST['highest_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;
    
    // Get current schedule for the machine/table
    $query = "SELECT MAX(end_date) as last_end_date FROM pu_machine_table 
             WHERE machine_id = $machineId";
    $result = mysqli_query($conn, $query);
	
	$query_priority = "SELECT MAX(priority) AS priority FROM pu_machine_table 
                   WHERE machine_id = $machineId";
    $result_priority = mysqli_query($conn, $query_priority);

    if ($result_priority && mysqli_num_rows($result_priority) > 0) {
        $row = mysqli_fetch_assoc($result_priority);
        $currentPriority = $row['priority'] ?? 0;
        $new_priority = $currentPriority + 1;
    } else {
        // No rows found, start from 1
        $new_priority = 1;
    }
    
    if (!$result) {
        $error = true;
    } else {
        $row = mysqli_fetch_assoc($result);
        $startDate = $row['last_end_date'] ? $row['last_end_date'] : date('Y-m-d H:i:s');
        $endDate = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));
        
        // If break spans multiple days, calculate remaining hours
        $startDay = date('Y-m-d', strtotime($startDate));
        $endDay = date('Y-m-d', strtotime($endDate));
        
        $remainingHours = $duration;
        if ($startDay != $endDay) {
            // Break spans multiple days
            $endOfFirstDay = date('Y-m-d 23:59:59', strtotime($startDate));
            $firstDayHours = (strtotime($endOfFirstDay) - strtotime($startDate)) / 3600;
            $remainingHours = $duration - $firstDayHours;
        }
        
        // Insert break as a special task
        $priority = $highestPriority ? $highestPriority - 1 : 1; // Set higher priority than existing tasks
        $insertQuery = "INSERT INTO pu_machine_table 
                       (machine_id, table_id, start_date, end_date, total_hours, remaing_hours, 
                        is_break, break_reason, priority)
                       VALUES ($machineId, $table_id, '$startDate', '$endDate', 
                               $duration, $remainingHours, 1, '$reason', $new_priority)";
        
        if (!mysqli_query($conn, $insertQuery)) {
            $error = true;
        }
        
        // Update priorities of existing tasks if needed
        if ($highestPriorityTaskId && !$error) {
            $newPriority = $priority + 1;
            $updateQuery = "UPDATE pu_machine_table 
                           SET priority = priority + 1 
                           WHERE machine_id = $machineId ";
            
            if (!mysqli_query($conn, $updateQuery)) {
                $error = true;
            }
        }
    }
    
    // Commit or rollback transaction
    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]);
    } else {
        mysqli_commit($conn);
        echo json_encode(['status' => 'success']);
    }
    
    mysqli_autocommit($conn, true);
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start_machine_breakdown') {
    $machine_id = intval($_REQUEST['machine_id']);
    $breakdown_reason_id = mysqli_real_escape_string($conn, $_REQUEST['breakdown_reason']);
    $now = date('Y-m-d H:i:s');
    $reason_query = "SELECT code FROM keycode_table WHERE id = '$breakdown_reason_id'";
    $reason_result = mysqli_query($conn, $reason_query);
    
    if ($reason_result && mysqli_num_rows($reason_result) > 0) {
        $reason_data = mysqli_fetch_assoc($reason_result);
        $reason_text = $reason_data['code'];
    } else {
        $reason_text = 'Unknown Reason';
    }
    // Stop any ongoing breakdowns before starting a new one
    mysqli_query($conn, "UPDATE machine_breakdown 
                         SET is_active = 0, breakdown_end = '$now', 
                             breakdown_hours = TIMESTAMPDIFF(MINUTE, breakdown_start, '$now') / 60,
                             updated_at = '$now' 
                         WHERE machine_id = $machine_id AND is_active = 1");

    // Start new breakdown
    $sql = "INSERT INTO machine_breakdown (machine_id, breakdown_start, breakdown_reason, is_active, created_at, updated_at)
            VALUES ($machine_id, '$now', '$reason_text', 1, '$now', '$now')";
    mysqli_query($conn, $sql);

    // Mark affected work orders
    markBreakdownAffectedWorkOrders($conn, $machine_id, $now, null);

    echo json_encode(['status' => 'success']);
    exit;
    
} else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'stop_machine_breakdown') {
    $machine_id = intval($_POST['machine_id']);
    $now = date('Y-m-d H:i:s');

    // Stop the breakdown
    $sql = "UPDATE machine_breakdown 
            SET is_active = 0, breakdown_end = '$now',
                breakdown_hours = TIMESTAMPDIFF(MINUTE, breakdown_start, '$now') / 60,
                updated_at = '$now'
            WHERE machine_id = $machine_id AND is_active = 1";
    mysqli_query($conn, $sql);

    // Reset breakdown_affected status for all work orders of this machine
    mysqli_query($conn, "
        UPDATE pu_machine_table 
        SET is_breakdown_affected = 0 
        WHERE machine_id = $machine_id AND is_breakdown_affected = 1
    ");

    echo json_encode(['status' => 'success']);
    exit;
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_machine_breakdown_status') {
   $sql = "SELECT mb.*, sd.resource_code AS machine_name
            FROM machine_breakdown mb
            LEFT JOIN station_detail_table sd ON mb.machine_id = sd.id
            ORDER BY mb.created_at DESC LIMIT 10";
    $res = mysqli_query($conn, $sql);

    $data = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $data[] = $row;
    }

    echo json_encode(['status' => 'success', 'data' => $data]);
    exit;
    
}

else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_tables_by_machine') {
    $machineId = mysqli_real_escape_string($conn, $_POST['machine_id'] ?? '');
    $tables = [];
    
    if (!empty($machineId)) {
        $query = "SELECT no_of_table, virtual_id FROM pu_mapping_tables WHERE machine_id = '$machineId' ORDER BY virtual_id ASC";
        $result = mysqli_query($conn, $query);
        
        if ($result) {
            while ($row = mysqli_fetch_assoc($result)) {
                $tables[$row['virtual_id']] = stripslashes($row['no_of_table']);
            }
            echo json_encode(['success' => true, 'tables' => $tables]);
        } else {
            echo json_encode(['success' => false, 'error' => mysqli_error($conn)]);
        }
    } else {
        echo json_encode(['success' => false, 'error' => 'Missing machine_id']);
    }
    exit;
}

else if (isset($_GET['action']) && $_GET['action'] === 'get_work_orders') {
    try {
        $workOrders = [];
        
        $query = "
        SELECT 
            m.work_order_id,
            m.part_id,
            m.end_date,
            m.machine_id,
            m.quantity,
            m.total_hours,
            m.id,
            w.work_order_name
        FROM 
            manufacture_machine_table m
        LEFT JOIN 
            work_order_name w 
            ON m.work_order_id = w.work_order_id 
            AND m.part_id = w.part_id
        JOIN 
            station_detail_table s 
            ON m.machine_id = s.id
        WHERE 
            s.machine_type = 4
            AND m.in_scheduler_check = 0
        ORDER BY 
            m.end_date ASC";

        $result = mysqli_query($conn, $query);
        
        if (!$result) {
            throw new Exception("Query failed: " . mysqli_error($conn));
        }

        while ($row = mysqli_fetch_assoc($result)) {
            // Get part details
            $partNumber = utility::getTableFieldById("item_management", "part_number", "id", $row['part_id']);
            $partDescription = utility::getTableFieldById("item_management", "product_description", "id", $row['part_id']);
            
            // Generate machine dropdown HTML
            $machineDropdown = $gsi->getpuStationList(
                "machinee_id_" . $row['id'], 
                $row['machine_id'], 
                "100%", 
                false, 
                "form-control select2 machine-select", 
                ""
            );
            
            // Generate table dropdown HTML
            $tableDropdown = $gsi->getPutableList(
                "machine_table_id_" . $row['id'], 
                $row['machine_id'], 
                "100%", 
                false, 
                "form-control select2 table-select", 
                ""
            );
            
            $workOrders[] = [
                'id' => $row['id'],
                'work_order_id' => $row['work_order_id'],
                'work_order_name' => $row['work_order_name'],
                'part_id' => $row['part_id'],
                'part_number' => $partNumber,
                'part_description' => $partDescription,
                'end_date' => $row['end_date'],
                'quantity' => $row['quantity'],
                'total_hours' => $row['total_hours'],
                'machine_id' => $row['machine_id'],
                'machine_dropdown' => $machineDropdown,
                'table_dropdown' => $tableDropdown
            ];
        }

        echo json_encode([
            'success' => true,
            'data' => $workOrders,
            'count' => count($workOrders)
        ]);
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage(),
            'data' => []
        ]);
    }
    exit;
}
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_pu_task_details') {

    $task_id = mysqli_real_escape_string($conn, $_REQUEST['task_id']);
    $work_order_id = mysqli_real_escape_string($conn, $_REQUEST['work_order_id']);
    $part_id = mysqli_real_escape_string($conn, $_REQUEST['part_id']);
    $machine_id = mysqli_real_escape_string($conn, $_REQUEST['machine_id']);
    

    $query = "SELECT 
    mmt.machine_id AS task, 
    mmt.id as task_id, 
    wo.work_order_no, 
    mmt.part_id,
    mmt.setup_hours, 
    mmt.priority,
    mmt.total_hours AS hours_to_schedule,
    mmt.total_hours, 
    mmt.work_order_id,
    mmt.product_name,
    mmt.quantity,
    mmt.set_id, 
    won.work_order_name, 
    mmt.shift_ids AS shift_name, 
    DATE(mmt.start_date) AS start_date, 
    DATE(mmt.end_date) AS end_date,
    TIME(mmt.start_date) AS start_time,
    mmt.is_break,
    mmt.break_reason,
    mmt.is_breakdown_affected,
    mmt.breakdown_hours,
    mb.id as breakdown_id,
    mb.breakdown_reason as machine_breakdown_reason,
    m.end_date as manufacture_end_date,
    m.description as manufacture_description,
    im.part_number as parent_part_number,
    GROUP_CONCAT(DISTINCT wocr.work_order_no ORDER BY wocr.work_order_no SEPARATOR ', ') as customer_order_nos
FROM 
    pu_machine_table mmt
LEFT JOIN 
    work_order wo ON mmt.work_order_id = wo.id
LEFT JOIN 
    work_order_name won ON mmt.work_order_id = won.work_order_id AND mmt.part_id = won.part_id
LEFT JOIN 
    machine_breakdown mb ON mmt.machine_id = mb.machine_id AND mb.is_active = 1
LEFT JOIN (
    SELECT 
        m1.part_id, 
        m1.work_order_id, 
        m1.end_date, 
        m1.description, 
        m1.parent_ids
    FROM manufacture_machine_table m1
    INNER JOIN (
        SELECT 
            part_id, 
            work_order_id, 
            MAX(end_date) as max_end_date
        FROM manufacture_machine_table
        GROUP BY part_id, work_order_id
    ) m2 ON m1.part_id = m2.part_id 
        AND m1.work_order_id = m2.work_order_id 
        AND m1.end_date = m2.max_end_date
) m ON mmt.part_id = m.part_id 
    AND mmt.work_order_id = m.work_order_id
LEFT JOIN 
    item_management im ON m.parent_ids = im.id
LEFT JOIN 
    work_order_customer_ref_mapping wocr ON mmt.work_order_id = wocr.work_order_id
WHERE mmt.id = '$task_id'
    LIMIT 1
";
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $data = mysqli_fetch_assoc($result);
        

        if ($data['set_id'] != 0) {
            $route_query = "SELECT route_desc FROM set_route_details WHERE set_id = '{$data['set_id']}' LIMIT 1";
        } else {
            $route_query = "SELECT route_desc FROM route_details WHERE item_id = '{$data['part_id']}' LIMIT 1";
        }
        $route_result = mysqli_query($conn, $route_query);
        if ($route_result && mysqli_num_rows($route_result) > 0) {
            $route_data = mysqli_fetch_assoc($route_result);
            $data['route_desc'] = $route_data['route_desc'];
        } else {
            $data['route_desc'] = '-';
        } 
         
      
		$data['is_late'] = false;
    if (!empty($row['manufacture_end_date']) && $row['end_date'] > $row['manufacture_end_date']) {
        $data['is_late'] = true;
    }
	$query = "
    SELECT 
        customer_reff,
        GROUP_CONCAT(DISTINCT RefSalesCode ORDER BY RefSalesCode SEPARATOR ', ') AS RefSalesCode
    FROM production_planning
    WHERE work_order_id = $work_order_id
";

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

$row = mysqli_fetch_assoc($result);
$customer_reff = $row['customer_reff'] ?? '';

$data['customer_code'] = utility::getTableFieldById("client_management", "customer_code", "id", $customer_reff);
$data['RefSalesCode'] = $row['RefSalesCode'] ?? '';

    

        
        echo json_encode([
            'success' => true,
            'data' => $data
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Task not found'
        ]);
    }
    exit;
}

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

    $task_id = mysqli_real_escape_string($conn, $_POST['task_id']);
    $priority = mysqli_real_escape_string($conn, $_POST['priority']);
    $machine_id = mysqli_real_escape_string($conn, $_POST['machine_id']);
    $setup_hours = mysqli_real_escape_string($conn, $_POST['setup_hours']);
    $total_hours = mysqli_real_escape_string($conn, $_POST['total_hours']);
    $setting_instruction = mysqli_real_escape_string($conn, $_POST['setting_instruction']);
    $start_date = mysqli_real_escape_string($conn, $_POST['start_date']);
    $quantity = mysqli_real_escape_string($conn, $_POST['quantity']);
    
    // Update query
    $update_query = "UPDATE pu_machine_table SET 
        priority = '$priority',
        machine_id = '$machine_id',
        setup_hours = '$setup_hours',
        total_hours = '$total_hours',
        setting_instruction = '$setting_instruction',
        start_date = '$start_date',
        quantity = '$quantity',
        updated_at = NOW()
    WHERE id = '$task_id'";
    
    if (mysqli_query($conn, $update_query)) {
        // Recalculate priorities if machine changed
        $recalculate_query = "SELECT id, priority FROM pu_machine_table 
                             WHERE machine_id = '$machine_id' AND finished = 0 
                             ORDER BY priority";
        $result = mysqli_query($conn, $recalculate_query);
        
        $new_priority = 1;
        while ($row = mysqli_fetch_assoc($result)) {
            mysqli_query($conn, "UPDATE pu_machine_table SET priority = $new_priority WHERE id = {$row['id']}");
            $new_priority++;
        }
        
        echo json_encode([
            'success' => true,
            'message' => 'Work order updated successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to update work order: ' . mysqli_error($conn)
        ]);
    }
    exit;
}
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete_pu_task') {

    $task_id = mysqli_real_escape_string($conn, $_REQUEST['task_id']);
    $work_order_id = mysqli_real_escape_string($conn, $_REQUEST['work_order_id']);
    $part_id = mysqli_real_escape_string($conn, $_REQUEST['part_id']);
    
    // Get machine_id before deletion for priority recalculation
    $machine_query = "SELECT machine_id FROM pu_machine_table WHERE id = '$task_id' LIMIT 1";
    $machine_result = mysqli_query($conn, $machine_query);
    $machine_data = mysqli_fetch_assoc($machine_result);
    $machine_id = $machine_data['machine_id'];
    
    // Delete the task
    $delete_query = "DELETE FROM pu_machine_table WHERE id = '$task_id'";
    
    if (mysqli_query($conn, $delete_query)) {
		$updateQuery = "
			UPDATE manufacture_machine_table 
			SET in_scheduler_check = 0 
			WHERE work_order_id = '$work_order_id'
			  AND part_id = '$part_id'
		";

		$conn->query($updateQuery);
        recalculateMachineDatesforpu($conn, $machine_id);
        
        echo json_encode([
            'success' => true,
            'message' => 'Work order deleted successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to delete work order: ' . mysqli_error($conn)
        ]);
    }
    exit;
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_gantt_rows') {

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

    $query = "SELECT 
        mmt.machine_id AS task, mmt.id as task_id, wo.work_order_no, mmt.part_id,
        mmt.setup_hours, mmt.table_id, mmt.priority, mmt.total_hours AS hours_to_schedule,
        mmt.total_hours, mmt.work_order_id, mmt.product_name, mmt.quantity, mmt.set_id,
        won.work_order_name, mmt.shift_ids AS shift_name,
        DATE(mmt.start_date) AS start_date, DATE(mmt.end_date) AS end_date,
        TIME(mmt.start_date) AS start_time,
        mmt.is_break, mmt.break_reason, mmt.is_breakdown_affected, mmt.breakdown_hours,
        mb.id as breakdown_id, mb.breakdown_reason as machine_breakdown_reason,
        m.end_date as manufacture_end_date, m.description as manufacture_description,
        m.parent_ids, im.part_number as parent_part_number,
        GROUP_CONCAT(DISTINCT wocr.work_order_no ORDER BY wocr.work_order_no SEPARATOR ', ') as customer_order_nos
    FROM pu_machine_table mmt
    LEFT JOIN work_order wo ON mmt.work_order_id = wo.id
    LEFT JOIN work_order_name won ON mmt.work_order_id = won.work_order_id AND mmt.part_id = won.part_id
    LEFT JOIN machine_breakdown mb ON mmt.machine_id = mb.machine_id AND mb.is_active = 1
    LEFT JOIN (
        SELECT m1.part_id, m1.work_order_id, m1.end_date, m1.description, m1.parent_ids
        FROM manufacture_machine_table m1
        INNER JOIN (
            SELECT part_id, work_order_id, MAX(end_date) as max_end_date
            FROM manufacture_machine_table GROUP BY part_id, work_order_id
        ) m2 ON m1.part_id = m2.part_id AND m1.work_order_id = m2.work_order_id AND m1.end_date = m2.max_end_date
    ) m ON mmt.part_id = m.part_id AND mmt.work_order_id = m.work_order_id
    LEFT JOIN item_management im ON m.parent_ids = im.id
    LEFT JOIN work_order_customer_ref_mapping wocr ON mmt.work_order_id = wocr.work_order_id
    WHERE mmt.end_date >= '$currentDateStr'
    GROUP BY mmt.id, mmt.machine_id, wo.work_order_no, mmt.part_id, mmt.setup_hours,
        mmt.table_id, mmt.priority, mmt.total_hours, mmt.work_order_id, mmt.product_name,
        mmt.quantity, mmt.set_id, won.work_order_name, mmt.shift_ids, mmt.start_date,
        mmt.end_date, mmt.is_break, mmt.break_reason, mmt.is_breakdown_affected,
        mmt.breakdown_hours, mb.id, mb.breakdown_reason, m.end_date, m.description, im.part_number
    ORDER BY mmt.priority, mmt.machine_id";

    $tasks = [];
    $result = mysqli_query($conn, $query);
    while ($row = mysqli_fetch_assoc($result)) {
        $row['is_late'] = (!empty($row['manufacture_end_date']) && $row['end_date'] > $row['manufacture_end_date']);
        $tasks[] = $row;
    }

    $activeBreakdowns = [];
    $bdResult = mysqli_query($conn, "SELECT machine_id, breakdown_reason FROM machine_breakdown WHERE is_active = 1");
    while ($bd = mysqli_fetch_assoc($bdResult)) {
        $activeBreakdowns[$bd['machine_id']] = $bd['breakdown_reason'];
    }

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

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

    // Group tasks
    $machineAllocations = [];
    foreach ($tasks as $task) {
        $machineId = $task['task'];
        if (!isset($machineAllocations[$machineId])) {
            $machineAllocations[$machineId] = ['current_time' => 0, 'tasks' => []];
        }
        $task['has_breakdown'] = isset($activeBreakdowns[$machineId]);
        $task['breakdown_reason'] = $task['has_breakdown'] ? $activeBreakdowns[$machineId] : '';
        $task['position'] = $machineAllocations[$machineId]['current_time'];
        $machineAllocations[$machineId]['tasks'][] = $task;
        $machineAllocations[$machineId]['current_time'] += $task['hours_to_schedule'];
    }

    $groupedTasks = [];
    foreach ($machineAllocations as $machineId => $data) {
        $groupedTasks[$machineId] = $data['tasks'];
    }

    // Build HTML
    $rowsHtml = '';
    foreach ($taskNames as $machineId => $taskName):
        $rowColor = $machineColors[$machineId];
        $rowsHtml .= '<div class="gantt-row" data-machine-id="' . $machineId . '" style="background-color:' . $rowColor . ';">';

        if (!empty($groupedTasks[$machineId])):
            $cumulativePosition = 0;
            foreach ($groupedTasks[$machineId] as $task):
                $taskWidth    = $task['hours_to_schedule'] * 80;
                $leftPosition = $cumulativePosition;
                $cumulativePosition += $taskWidth;

                $part_id            = (int)$task['part_id'];
                $work_order_id      = $task['work_order_id'];
                $parent_ids         = $task['parent_ids'];
                $parent_part_number = $task['parent_part_number'];
                $setup_hours        = $task['setup_hours'];
                $part_name          = $task['product_name'];
                $quantity           = $task['quantity'];
                $manufacture_end_date = $task['manufacture_end_date'];
                $route_detail       = $task['manufacture_description'];
                $comma_customer_order_nos = $task['customer_order_nos'];

                // Inventory dot
                $dotClass = 'red-dot-indicator';
                $allInStock = true;
                $invQuery = "SELECT im.part_number, COALESCE(i.quantity_in_stock, 0) AS quantity_in_stock
                             FROM bom b
                             LEFT JOIN inventory i ON b.sub_part_id = i.item_id
                             LEFT JOIN item_management im ON b.sub_part_id = im.id
                             WHERE b.main_product_id = $part_id";
                $invResult = $conn->query($invQuery);
                $tooltipLines = [];
                if ($invResult && $invResult->num_rows > 0) {
                    while ($invRow = $invResult->fetch_assoc()) {
                        $pn  = $invRow['part_number'] ?: 'Unknown';
                        $qty = (int)$invRow['quantity_in_stock'];
                        $tooltipLines[] = $pn . ': ' . ($qty > 0 ? 'In Stock' : 'Out of Stock') . ' (Qty: ' . $qty . ')';
                        if ($qty <= 0) $allInStock = false;
                    }
                    $dotClass = $allInStock ? 'green-dot-indicator' : 'red-dot-indicator';
                } else {
                    $tooltipLines[] = 'No BOM child parts linked.';
                }
                $tooltipContent = "Inventory Status:\n" . implode("\n", $tooltipLines);

                $taskClasses = 'gantt-task';
                if ($task['is_break'])      $taskClasses .= ' break-task';
                elseif ($task['is_late'])   $taskClasses .= ' late-task';
                else                        $taskClasses .= ' on-time-task';

                $rowsHtml .= '<div class="' . $taskClasses . '"'
                    . ' draggable="true"'
                    . ' data-task-id="' . htmlspecialchars($task['task_id']) . '"'
                    . ' data-priority="' . htmlspecialchars($task['priority']) . '"'
                    . ' data-part="' . htmlspecialchars($task['product_name'] ?? '') . '"'
                    . ' data-wo="' . htmlspecialchars($task['work_order_name'] ?? '') . '"'
                    . ' data-work-order="' . htmlspecialchars($task['work_order_no'] ?? '') . '"'
                    . ' data-part-id="' . $part_id . '"'
                    . ' data-work-order-id="' . $work_order_id . '"'
                    . ' data-hours="' . $task['hours_to_schedule'] . '"'
                    . ' data-current-machine="' . $machineId . '"'
                    . ' style="left:' . $leftPosition . 'px; width:' . $taskWidth . 'px;">';

                if ($task['is_break']):
                    $rowsHtml .= '<div class="task-content"><strong>BREAK</strong><br/>'
                        . htmlspecialchars($task['break_reason'] ?? '') . '<br/>'
                        . 'Duration: ' . $task['hours_to_schedule'] . 'h</div>';
                else:
                    $rowsHtml .= '<div class="dot-indicator ' . $dotClass . '" title="' . htmlspecialchars($tooltipContent) . '"></div>';
                    $rowsHtml .= '<div class="task-content" style="font-size:12px;line-height:1.4;">';
                    $rowsHtml .= '<div>' . ($parent_ids == 0 ? htmlspecialchars($comma_customer_order_nos ?? '') : htmlspecialchars($parent_part_number ?? '')) . '</div>';
                    $rowsHtml .= '<div>' . htmlspecialchars($task['work_order_name'] ?? '') . '</div>';
                    $rowsHtml .= '<div><strong>Item:</strong> ' . htmlspecialchars($part_name) . ' &nbsp;|&nbsp; <strong>Qty:</strong> ' . htmlspecialchars($quantity) . '</div>';
                    $rowsHtml .= '<div><strong>Set Hours:</strong> ' . htmlspecialchars($setup_hours ?? '') . '</div>';
                    if ($task['is_breakdown_affected']):
                        $rowsHtml .= '<div style="color:#ff0000;"><strong>Breakdown Delay: +' . $task['breakdown_hours'] . 'h</strong></div>';
                    endif;
                    $rowsHtml .= '<div><strong>Desc:</strong> ' . htmlspecialchars($route_detail ?? '') . '</div>';
                    $rowsHtml .= '<div><strong>Due Date:</strong> ' . (!empty($manufacture_end_date) ? date('d-M-Y', strtotime($manufacture_end_date)) : 'N/A') . '</div>';
                    $rowsHtml .= '</div>';
                endif;

                $rowsHtml .= '<div class="hour-indicator">' . $task['hours_to_schedule'] . 'h';
                if ($task['is_breakdown_affected']):
                    $rowsHtml .= '<br><small>+' . $task['breakdown_hours'] . 'h delay</small>';
                endif;
                $rowsHtml .= '</div></div>';
            endforeach;
        else:
            $rowsHtml .= '<div class="no-tasks">No tasks scheduled</div>';
        endif;

        $rowsHtml .= '</div>';
    endforeach;

    echo json_encode(['success' => true, 'html' => $rowsHtml]);
    exit;
}

else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'split_pu_work_order') {
    $taskId    = intval($_REQUEST['task_id']);
    $splitQty  = floatval($_REQUEST['split_quantity']);

    if ($taskId <= 0 || $splitQty <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid input parameters']); exit;
    }

    $query  = "SELECT * FROM pu_machine_table WHERE id = $taskId";
    $result = mysqli_query($conn, $query);
    if (!$result || mysqli_num_rows($result) == 0) {
        echo json_encode(['success' => false, 'message' => 'Work order not found']); exit;
    }

    $originalWO      = mysqli_fetch_assoc($result);
    $originalQty     = floatval($originalWO['quantity']);
    $machineId       = intval($originalWO['machine_id']);
    $workOrderId     = intval($originalWO['work_order_id']);
    $partId          = intval($originalWO['part_id']);
    $setupHours      = floatval($originalWO['setup_hours']);
    $totalHours      = floatval($originalWO['total_hours']);
    $priority        = intval($originalWO['priority']);
    $manufId         = intval($originalWO['manuf_id']);

    if ($splitQty >= $originalQty || $splitQty < 1) {
        echo json_encode(['success' => false, 'message' => 'Split quantity must be between 1 and ' . ($originalQty - 1)]); exit;
    }

    $hoursPerUnit    = ($totalHours - $setupHours) / $originalQty;
    $remainingQty    = $originalQty - $splitQty;
    $remainingHours  = ($remainingQty * $hoursPerUnit) + $setupHours;
    $splitHours      = ($splitQty * $hoursPerUnit) + $setupHours;

    mysqli_begin_transaction($conn);
    try {
        // ---------------------------------------------------------
        // 1. Split the linked manufacture_machine_table row too
        // ---------------------------------------------------------
        $newManufId = null;

        if ($manufId > 0) {

            $manufResult = mysqli_query($conn, "SELECT * FROM manufacture_machine_table WHERE id = $manufId");
            if (!$manufResult || mysqli_num_rows($manufResult) == 0) {
                throw new Exception('Linked manufacture record not found for manuf_id ' . $manufId);
            }
            $originalManuf = mysqli_fetch_assoc($manufResult);

            $manufOriginalQuantity = floatval($originalManuf['quantity']);
            $manufTotalHours = floatval($originalManuf['total_hours']);
            $manufHoursPerUnit = $manufOriginalQuantity > 0 ? ($manufTotalHours / $manufOriginalQuantity) : 0;

            $manufRemainingQuantity = $manufOriginalQuantity - $splitQty;
            $manufRemainingHours = $manufRemainingQuantity * $manufHoursPerUnit;
            $manufSplitHours = $splitQty * $manufHoursPerUnit;

            // Update the original manufacture record with the remaining qty/hours
            $updateManufQuery = "UPDATE manufacture_machine_table 
                                 SET quantity = $manufRemainingQuantity,
                                     total_hours = $manufRemainingHours
                                 WHERE id = $manufId";

            if (!mysqli_query($conn, $updateManufQuery)) {
                throw new Exception('Failed to update original manufacture record: ' . mysqli_error($conn));
            }

            // Copy every column from the original manufacture row except
            // id/quantity/total_hours, which get the split values.
            $manufColumns = [];
            $manufValues  = [];

            foreach ($originalManuf as $col => $val) {
                if ($col === 'id') continue;

                $manufColumns[] = "`$col`";

                if ($col === 'quantity') {
                    $manufValues[] = $splitQty;
                } elseif ($col === 'total_hours') {
                    $manufValues[] = $manufSplitHours;
                } elseif (is_null($val)) {
                    $manufValues[] = 'NULL';
                } else {
                    $manufValues[] = "'" . mysqli_real_escape_string($conn, $val) . "'";
                }
            }

            $insertManufQuery = "INSERT INTO manufacture_machine_table (" . implode(', ', $manufColumns) . ") 
                                 VALUES (" . implode(', ', $manufValues) . ")";

            if (!mysqli_query($conn, $insertManufQuery)) {
                throw new Exception('Failed to create new manufacture record: ' . mysqli_error($conn));
            }

            $newManufId = $conn->insert_id;
        }

        // ---------------------------------------------------------
        // 2. Update original PU work order with remaining quantity
        // ---------------------------------------------------------
        if (!mysqli_query($conn, "UPDATE pu_machine_table 
                                   SET quantity=$remainingQty, 
                                       total_hours=$remainingHours, 
                                       total_hours_update=" . ($remainingHours - $setupHours) . " 
                                   WHERE id=$taskId")) {
            throw new Exception('Failed to update original work order: ' . mysqli_error($conn));
        }

        mysqli_query($conn, "UPDATE pu_machine_table 
                              SET priority=priority+1 
                              WHERE machine_id=$machineId AND priority>$priority AND id!=$taskId");

        $newPriority = $priority + 1;

        // ---------------------------------------------------------
        // 3. Insert new PU work order, linked to the NEW manuf row
        // ---------------------------------------------------------
        $manufIdForInsert = $newManufId !== null ? $newManufId : ($manufId > 0 ? $manufId : null);

        $insertQuery = "INSERT INTO pu_machine_table (
                           machine_id, manuf_id, v_machine_id, table_id, work_order_id, part_id, 
                           quantity, product_name, total_hours, total_hours_update, setup_hours, 
                           priority, set_id, cycle, shift_ids, start_date, end_date, is_break, finished
                       ) VALUES (
                           $machineId,
                           " . ($manufIdForInsert !== null ? intval($manufIdForInsert) : 'NULL') . ",
                           {$originalWO['v_machine_id']},
                           {$originalWO['table_id']},
                           $workOrderId,
                           $partId,
                           $splitQty,
                           '" . mysqli_real_escape_string($conn, $originalWO['product_name']) . "',
                           $splitHours,
                           " . ($splitHours - $setupHours) . ",
                           $setupHours,
                           $newPriority,
                           " . intval($originalWO['set_id']) . ",
                           " . intval($originalWO['cycle']) . ",
                           '" . mysqli_real_escape_string($conn, $originalWO['shift_ids']) . "',
                           '" . mysqli_real_escape_string($conn, $originalWO['start_date']) . "',
                           '" . mysqli_real_escape_string($conn, $originalWO['end_date']) . "',
                           0,
                           0
                       )";

        if (!mysqli_query($conn, $insertQuery)) {
            throw new Exception('Failed to create new work order: ' . mysqli_error($conn));
        }

        mysqli_commit($conn);
        recalculateMachineDatesforpu($conn, $machineId);

        echo json_encode([
            'success' => true,
            'message' => 'Work order split successfully',
            'original_quantity' => $remainingQty,
            'split_quantity' => $splitQty,
            'original_hours' => round($remainingHours, 2),
            'split_hours' => round($splitHours, 2),
            'new_manuf_id' => $newManufId
        ]);

    } catch (Exception $e) {
        mysqli_rollback($conn);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}
function markBreakdownAffectedWorkOrders($conn, $machineId, $breakdownStart, $breakdownEnd = null) {
    $endCondition = $breakdownEnd ? "'$breakdownEnd'" : "NOW()";
    
    $overlapQuery = "
        SELECT id, start_date, end_date
        FROM pu_machine_table
        WHERE machine_id = $machineId
          AND is_break = 0
          AND start_date < '$breakdownStart'
          AND end_date > '$breakdownStart'
    ";

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

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

    // Optional: Log this for debugging
    error_log("Marked $affectedCount overlapping work orders as breakdown-affected for Machine #$machineId");
    
    return $affectedCount;
}


?>







