<?php
include("../../../include/startup.php"); 
 //recalculateMachineDates($conn, 7, 1);
function recalculateMachineDatesforassbly($conn, $machineId) {
    set_time_limit(300); // Avoid timeout

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

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

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

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

    // 👇 Start scheduling from now
    $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'];

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

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

                if ($availableHours <= 0) continue;

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

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

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

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

                // Update current pointer
                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

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

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

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

//echo $query . "<br>"; // For debugging

mysqli_query($conn, $query);



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

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

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

    // Get tasks
    $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;
    }

    // 👇 Start scheduling from now
    $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'];

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

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

                if ($availableHours <= 0) continue;

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

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

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

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

                // Update current pointer
                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

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

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

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

//echo $query . "<br>"; // For debugging

mysqli_query($conn, $query);



    }
}
//////////////////////////////////////////////////////////////////////////1234567////////////////////////
function recalculateMachineDates($conn, $machineId, $tableId) {
    // Get shift data
    $shifts = [];
    $shiftResult = mysqli_query($conn, "SELECT * FROM working_hours");
    while ($row = mysqli_fetch_assoc($shiftResult)) {
        $shifts[$row['shift_name']] = $row;
    }

    // Get tasks ordered by new priority
    $tasks = [];
   /* $taskResult = mysqli_query($conn,
        "SELECT id, total_hours FROM cnc_machine_table
         WHERE machine_id = $machineId AND table_id = $tableId
         ORDER BY priority"
    );*/
	$currentDateStr = date('Y-m-d');
	$taskResult = mysqli_query($conn,
    "SELECT id, 
            total_hours,
            CASE 
                WHEN start_date <= '$currentDateStr' AND end_date >= '$currentDateStr' THEN remaing_hours
                ELSE total_hours 
            END 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;
    }

    $currentDate = date('Y-m-d');
    $currentShift = null;
    $currentEndTime = null;

    foreach ($tasks as $task) {
        // Find next available shift
        if (!$currentShift) {
            foreach ($shifts as $shiftName => $shift) {
                if (date('w', strtotime($currentDate)) == $shift['day_shifts']) {
                    $currentShift = $shiftName;
                    $currentEndTime = strtotime($currentDate . ' ' . $shift['start_time']);
                    break;
                }
            }
            // If no shift found today, move to next day
            if (!$currentShift) {
                $currentDate = date('Y-m-d', strtotime($currentDate . ' +1 day'));
                continue;
            }
        }

        // Calculate new dates
        $startTime = date('Y-m-d H:i:s', $currentEndTime);
        $endTime = date('Y-m-d H:i:s', $currentEndTime + ($task['hours_to_schedule'] * 3600));

        // Update task
        mysqli_query($conn,
            "UPDATE cnc_machine_table SET
             start_date = '$startTime',
             end_date = '$endTime',
             shift_ids = '$currentShift'
             WHERE id = {$task['id']}"
        );

        // Move to next time slot
        $currentEndTime += $task['hours_to_schedule'] * 3600;
    }
}
if(isset($_REQUEST['action']) && $_REQUEST['action']=='selected_work_order_for_machine'){
	
$work_order_ids = $_REQUEST['work_orders'];


foreach ($work_order_ids as $work_order_id) {
    $work_order_id = intval($work_order_id);

    $sql_update = "UPDATE work_order_detail SET check_or_not = 1 WHERE work_order = '$work_order_id'";
    mysqli_query($conn, $sql_update);

     $query_p = "SELECT product_id, quantity, required_date, end_date, machine, shift_idss, parent_ids, set_id, set_part, product_name, absolute_quantity_if_set, total_time FROM work_order_detail 
                WHERE process_type = 6 AND work_order_id = $work_order_id";
    $result_p = $conn->query($query_p);

    if ($result_p && $result_p->num_rows > 0) {
        while ($row_p = $result_p->fetch_assoc()) {
            $product_id = $row_p['product_id'];
            $required_date = $row_p['required_date'];
            $end_date = $row_p['end_date'];
            $quantity = $row_p['quantity'];
            $machine_id = $row_p['machine'];
            $parent_ids = $row_p['parent_ids'];
            $product_name = $row_p['product_name'];
            $shift_ids = $row_p['shift_idss'];
			$set_id = $row_p['set_id'];
			$set_part = $row_p['set_part'];
			$absolute_quantity_if_set = $row_p['absolute_quantity_if_set'];
			$total_hours = $row_p['total_time'];

            $sql = "SELECT GROUP_CONCAT(shift_name) AS shift_names 
                    FROM working_hours 
                    WHERE FIND_IN_SET(id, '$shift_ids')";
            $result = $conn->query($sql);
            $row = $result->fetch_assoc();
            $shift_ids = $row['shift_names'];

             $query_insert = "INSERT INTO manufacture_machine_table (work_order_id, part_id, start_date, end_date, quantity, machine_id, shift_ids, parent_ids, product_name, set_id, set_part, absolute_quantity_if_set, total_hours)
                                 VALUES ('{$work_order_id}', '{$product_id}', '{$end_date}', '{$required_date}','{$quantity}', '{$machine_id}','{$shift_ids}', '{$parent_ids}','{$product_name}','{$set_id}','{$set_part}','{$absolute_quantity_if_set}','{$total_hours}')";
            $conn->query($query_insert);
        }
    }
}
   

    echo json_encode(['status' => 'success', 'message' => 'All selected work orders processed successfully']);
	
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_work_order_dates'){
	    $workOrderId = intval($_REQUEST['work_order_id']); 
		$part_id = intval($_REQUEST['part_id']); 

     $query = "SELECT MAX(required_date) AS end_date, MIN(required_date) AS start_date 
              FROM work_order_detail 
              WHERE work_order_id = $workOrderId And product_id = $part_id";

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

    if ($row = mysqli_fetch_assoc($result)) {
        echo json_encode([
            'status' => 'success',
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date']
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No records found']);
    }

   
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='updated_work_order'){
	 $workOrdernewdates = json_decode($_REQUEST['work_orders_new_dates'], true);
	 if (!is_array($workOrdernewdates)) {
        echo json_encode(["status" => "error", "message" => "Invalid JSON Data"]);
        exit;
    }

	 $color = $_REQUEST['color'];
	 $workOrderId = $_REQUEST['workOrderId']; 
	 
	 foreach ($workOrdernewdates as $entryy) {
    if (isset($entryy['shift'])) {
        $shift_id[] = $entryy['shift'];
    }
}

$shift_id = array_unique($shift_id);

// Re-index the array to ensure 0 index exists
$shift_id = array_values($shift_id);

// Store the first value in a separate variable
$first_shift_id = $shift_id[0];

// Convert the array to comma-separated string
$shift_idss = implode(",", $shift_id);
	 
      $partDates = [];
    foreach ($workOrdernewdates as $entry) {
        $part_id = $entry['part_id'] ?? '';
        $date = $entry['date'] ?? '';

        if (!$part_id || !$date) {
            echo json_encode(["status" => "error", "message" => "Missing part_id or date"]);
            exit;
        }

        if (!isset($partDates[$part_id])) {
            $partDates[$part_id] = ['min' => $date, 'max' => $date];
        } else {
            if ($date < $partDates[$part_id]['min']) {
                $partDates[$part_id]['min'] = $date;
            }
            if ($date > $partDates[$part_id]['max']) {
                $partDates[$part_id]['max'] = $date;
            }
        }
    }
	foreach ($partDates as $part_id => $dates) {
    $start = $dates['min'];
    $end = $dates['max'];
    
    //$sql = "UPDATE vac_machine_table SET start_date = '$start', end_date = '$end', shift_ids = '$shift_idss', color = '$color' WHERE part_id = '$part_id' AND work_order_id = '$workOrderId' "; 
	$sql = "UPDATE vac_machine_table SET start_date = '$start', end_date = '$end', start_shift = '$first_shift_id', color = '$color' WHERE part_id = '$part_id' AND work_order_id = '$workOrderId' ";
    $conn->query($sql);
}
     $query = "SELECT MAX(required_date) AS end_date, MIN(required_date) AS start_date 
              FROM work_order_detail 
              WHERE work_order_id = $workOrderId";

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

    if ($row = mysqli_fetch_assoc($result)) {
        echo json_encode([
            'status' => 'success',
            'start_date' => $row['start_date'],
            'end_date' => $row['end_date']
        ]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No records found']);
    }

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


	 $part_id = $_REQUEST['part_id'];
	 $work_order_id = $_REQUEST['work_order_id']; 
	 $new_date = $_REQUEST['new_date']; 
	 $new_start_time = $_REQUEST['new_start_time']; 
	 $start_date = $new_date . ' ' . $new_start_time;
	 
    $sql = "UPDATE cnc_machine_table SET start_date = '$start_date' WHERE part_id = '$part_id' AND work_order_id = '$work_order_id'";
$result = mysqli_query($conn, $sql);

if ($result) {
    // Now fetch the updated row
     echo json_encode([
            'status' => 'success'
        ]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Update failed']);
}


   
} else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_production_data'){
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => ''];
    
    if (!isset($_REQUEST['machine_id']) || !isset($_REQUEST['start_date']) || !isset($_REQUEST['end_date'])) {
        $response['message'] = 'Missing required parameters';
        echo json_encode($response);
        exit;
    }
    
    $machineId = (int)$_REQUEST['machine_id'];
    $startDate = mysqli_real_escape_string($conn, $_REQUEST['start_date']);
    $endDate = mysqli_real_escape_string($conn, $_REQUEST['end_date']);
    
    $query = "SELECT 
                m.work_order_id,
                m.part_id,
                m.table_id,
                DATE_FORMAT(m.end_date, '%Y-%m-%d') as end_date,
                m.quantity,
                m.total_hours,
                w.work_order_name
              FROM cnc_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_master_table s ON m.machine_id = s.id
              WHERE s.machine_type = 3
                AND m.machine_id = $machineId
                AND m.end_date BETWEEN '$startDate' AND '$endDate'
              ORDER BY m.end_date";
    
    $result = mysqli_query($conn, $query);
    
    if (!$result) {
        $response['message'] = 'Database error: ' . mysqli_error($conn);
        echo json_encode($response);
        exit;
    }
    
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);
    exit;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='fetch_production_data_vac'){
    header('Content-Type: application/json');
    
    $response = ['success' => false, 'message' => ''];
    
    if (!isset($_REQUEST['machine_id']) || !isset($_REQUEST['start_date']) || !isset($_REQUEST['end_date'])) {
        $response['message'] = 'Missing required parameters';
        echo json_encode($response);
        exit;
    }
    
    $machineId = (int)$_REQUEST['machine_id'];
    $startDate = mysqli_real_escape_string($conn, $_REQUEST['start_date']);
    $endDate = mysqli_real_escape_string($conn, $_REQUEST['end_date']);
    
     $query = "SELECT 
                m.work_order_id,
                m.part_id,
                DATE_FORMAT(m.end_date, '%Y-%m-%d') as end_date,
                m.quantity,
                m.total_hours,
                w.work_order_name
              FROM vac_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_master_table s ON m.machine_id = s.id
              WHERE s.machine_type = 3
                AND m.machine_id = $machineId
                AND m.end_date BETWEEN '$startDate' AND '$endDate'
              ORDER BY m.end_date";
			 
    
    $result = mysqli_query($conn, $query);
    
    if (!$result) {
        $response['message'] = 'Database error: ' . mysqli_error($conn);
        echo json_encode($response);
        exit;
    }
    
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $data
    ]);
    exit;
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='update_task_position'){
	    $workOrderId = $_REQUEST['work_order_id'];
$newTaskId = $_REQUEST['new_task_id'];
$partId = $_REQUEST['part_id'];

    $sql = "UPDATE vac_machine_table 
            SET machine_id = '$newTaskId'
            WHERE part_id = '$partId' AND work_order_id = '$workOrderId'";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["status" => "success", "message" => "Task updated successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to update task: " . mysqli_error($conn)]);
    }

 

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

    $machineId = intval($_REQUEST['machine_id']);
    $tableId = intval($_REQUEST['table_id']);
    $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 || $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;
    
    // Get current schedule for the machine/table
    $query = "SELECT MAX(end_date) as last_end_date FROM cnc_machine_table 
             WHERE machine_id = $machineId AND table_id = $tableId";
    $result = mysqli_query($conn, $query);
	
	$query_priority = "SELECT MAX(priority) AS priority FROM cnc_machine_table 
                   WHERE machine_id = $machineId AND table_id = $tableId";
$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 cnc_machine_table 
                       (machine_id, table_id, start_date, end_date, total_hours, remaing_hours, 
                        is_break, break_reason, priority, color)
                       VALUES ($machineId, $tableId, '$startDate', '$endDate', 
                               $duration, $remainingHours, 1, '$reason', $new_priority, 5)";
        
        if (!mysqli_query($conn, $insertQuery)) {
            $error = true;
        }
        
        // Update priorities of existing tasks if needed
        if ($highestPriorityTaskId && !$error) {
            $newPriority = $priority + 1;
            $updateQuery = "UPDATE cnc_machine_table 
                           SET priority = priority + 1 
                           WHERE machine_id = $machineId AND table_id = $tableId AND priority < $newPriority";
            
            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']=='add_assbly_break'){

    $machineId = intval($_REQUEST['machine_id']);
    //$tableId = intval($_REQUEST['table_id']);
    $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 assbly_machine_table 
             WHERE machine_id = $machineId";
    $result = mysqli_query($conn, $query);
	
	$query_priority = "SELECT MAX(priority) AS priority FROM assbly_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 assbly_machine_table 
                       (machine_id, start_date, end_date, total_hours, remaing_hours, 
                        is_break, break_reason, priority, color)
                       VALUES ($machineId, '$startDate', '$endDate', 
                               $duration, $remainingHours, 1, '$reason', $new_priority, 5)";
        
        if (!mysqli_query($conn, $insertQuery)) {
            $error = true;
        }
        
        // Update priorities of existing tasks if needed
        if ($highestPriorityTaskId && !$error) {
            $newPriority = $priority + 1;
            $updateQuery = "UPDATE assbly_machine_table 
                           SET priority = priority + 1 
                           WHERE machine_id = $machineId AND priority < $newPriority";
            
            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']=='add_vac_break'){

    $machineId = intval($_REQUEST['machine_id']);
    //$tableId = intval($_REQUEST['table_id']);
    $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 vac_machine_table 
             WHERE machine_id = $machineId";
    $result = mysqli_query($conn, $query);
	
	$query_priority = "SELECT MAX(priority) AS priority FROM vac_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 vac_machine_table 
                       (machine_id, start_date, end_date, total_hours, remaing_hours, 
                        is_break, break_reason, priority, color)
                       VALUES ($machineId, '$startDate', '$endDate', 
                               $duration, $remainingHours, 1, '$reason', $new_priority, 5)";
        
        if (!mysqli_query($conn, $insertQuery)) {
            $error = true;
        }
        
        // Update priorities of existing tasks if needed
        if ($highestPriorityTaskId && !$error) {
            $newPriority = $priority + 1;
            $updateQuery = "UPDATE vac_machine_table 
                           SET priority = priority + 1 
                           WHERE machine_id = $machineId AND priority < $newPriority";
            
            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'] == 'update_task_position_cnc') {
	
		 

			$work_order_id = $_REQUEST['work_order_id'];
            $part_id = $_REQUEST['part_id'];
            $machine_id = $_REQUEST['new_machine_id'];
            $table_id = $_REQUEST['new_table_id'];



             $query = "UPDATE cnc_machine_table 
                      SET machine_id = $machine_id, table_id = $table_id 
                      WHERE work_order_id = $work_order_id AND part_id = $part_id";
				
           
        

   if (mysqli_query($conn, $query)) {
        echo json_encode(["status" => "success", "message" => "Task updated successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Failed to update task: " . mysqli_error($conn)]);
    }
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update_cnc_task_priority') {
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//echo "hi";
    $taskId = intval($_REQUEST['task_id']);
    $newMachineId = intval($_REQUEST['new_machine_id']);
    $newTableId = intval($_REQUEST['new_table_id']);
    $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;

    // 1. Get the dragged task details
    $draggedTask = mysqli_fetch_assoc(mysqli_query($conn, 
        "SELECT * FROM cnc_machine_table WHERE id = $taskId"
    ));

    // 2. Get current tasks from original machine/table
    $originalTasks = [];
    $originalResult = mysqli_query($conn,
        "SELECT id, priority FROM cnc_machine_table 
         WHERE machine_id = {$draggedTask['machine_id']} 
         AND table_id = {$draggedTask['table_id']}
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($originalResult)) {
        $originalTasks[] = $row;
    }

    // 3. Get current tasks from new machine/table
    $newTasks = [];
    $newResult = mysqli_query($conn,
        "SELECT id, priority FROM cnc_machine_table 
         WHERE machine_id = $newMachineId 
         AND table_id = $newTableId
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($newResult)) {
        $newTasks[] = $row;
    }

   /* // 4. Update original machine/table (remove dragged task)
    $newPriority = 1;
    foreach ($originalTasks as $task) {
        if ($task['id'] != $taskId) {
            mysqli_query($conn,
                "UPDATE cnc_machine_table SET priority = $newPriority 
                 WHERE id = {$task['id']}"
            );
            $newPriority++;
        }
    }*/

    // 5. Calculate new priority for dragged task
    $insertPriority = 1; // Default to first position
    if ($leftNeighborPriority !== null) {
        $insertPriority = $leftNeighborPriority + 1;
        
        // Increment priorities after insertion point
        foreach ($newTasks as $task) {
            if ($task['priority'] >= $insertPriority) {
                mysqli_query($conn,
                    "UPDATE cnc_machine_table SET priority = priority + 1 
                     WHERE id = {$task['id']}"
                );
            }
        }
    }

    // 6. Update dragged task with new position
    mysqli_query($conn,
        "UPDATE cnc_machine_table SET 
         machine_id = $newMachineId,
         table_id = $newTableId,
         priority = $insertPriority
         WHERE id = $taskId"
    );

    // 7. Recalculate dates for both machines
    recalculateMachineDates($conn, $draggedTask['machine_id'], $draggedTask['table_id']);
    recalculateMachineDates($conn, $newMachineId, $newTableId);

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

// Helper function to recalculate dates for a machine/table

}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update_assmbly_task_priority') {
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//echo "hi";
    $taskId = intval($_REQUEST['task_id']);
    $newMachineId = intval($_REQUEST['new_machine_id']);
    $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;

    // 1. Get the dragged task details
    $draggedTask = mysqli_fetch_assoc(mysqli_query($conn, 
        "SELECT * FROM assbly_machine_table WHERE id = $taskId"
    ));

    // 2. Get current tasks from original machine/table
    $originalTasks = [];
    $originalResult = mysqli_query($conn,
        "SELECT id, priority FROM assbly_machine_table 
         WHERE machine_id = {$draggedTask['machine_id']} 
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($originalResult)) {
        $originalTasks[] = $row;
    }

    // 3. Get current tasks from new machine/table
    $newTasks = [];
    $newResult = mysqli_query($conn,
        "SELECT id, priority FROM assbly_machine_table 
         WHERE machine_id = $newMachineId
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($newResult)) {
        $newTasks[] = $row;
    }

   /* // 4. Update original machine/table (remove dragged task)
    $newPriority = 1;
    foreach ($originalTasks as $task) {
        if ($task['id'] != $taskId) {
            mysqli_query($conn,
                "UPDATE assbly_machine_table SET priority = $newPriority 
                 WHERE id = {$task['id']}"
            );
            $newPriority++;
        }
    }*/

    // 5. Calculate new priority for dragged task
    $insertPriority = 1; // Default to first position
    if ($leftNeighborPriority !== null) {
        $insertPriority = $leftNeighborPriority + 1;
        
        // Increment priorities after insertion point
        foreach ($newTasks as $task) {
            if ($task['priority'] >= $insertPriority) {
                mysqli_query($conn,
                    "UPDATE assbly_machine_table SET priority = priority + 1 
                     WHERE id = {$task['id']}"
                );
            }
        }
    }

    // 6. Update dragged task with new position
    mysqli_query($conn,
        "UPDATE assbly_machine_table SET 
         machine_id = $newMachineId,
         priority = $insertPriority
         WHERE id = $taskId"
    );

    // 7. Recalculate dates for both machines
    recalculateMachineDatesforassbly($conn, $draggedTask['machine_id']);
    recalculateMachineDatesforassbly($conn, $newMachineId);

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

// Helper function to recalculate dates for a machine/table

}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update_vac_task_priority') {
	//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//echo "hi";
    $taskId = intval($_REQUEST['task_id']);
    $newMachineId = intval($_REQUEST['new_machine_id']);
    $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;

    // 1. Get the dragged task details
    $draggedTask = mysqli_fetch_assoc(mysqli_query($conn, 
        "SELECT * FROM vac_machine_table WHERE id = $taskId"
    ));

    // 2. Get current tasks from original machine/table
    $originalTasks = [];
    $originalResult = mysqli_query($conn,
        "SELECT id, priority FROM vac_machine_table 
         WHERE machine_id = {$draggedTask['machine_id']} 
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($originalResult)) {
        $originalTasks[] = $row;
    }

    // 3. Get current tasks from new machine/table
    $newTasks = [];
    $newResult = mysqli_query($conn,
        "SELECT id, priority FROM vac_machine_table 
         WHERE machine_id = $newMachineId
         ORDER BY priority"
    );
    while ($row = mysqli_fetch_assoc($newResult)) {
        $newTasks[] = $row;
    }

   /* // 4. Update original machine/table (remove dragged task)
    $newPriority = 1;
    foreach ($originalTasks as $task) {
        if ($task['id'] != $taskId) {
            mysqli_query($conn,
                "UPDATE vac_machine_table SET priority = $newPriority 
                 WHERE id = {$task['id']}"
            );
            $newPriority++;
        }
    }*/

    // 5. Calculate new priority for dragged task
    $insertPriority = 1; // Default to first position
    if ($leftNeighborPriority !== null) {
        $insertPriority = $leftNeighborPriority + 1;
        
        // Increment priorities after insertion point
        foreach ($newTasks as $task) {
            if ($task['priority'] >= $insertPriority) {
                mysqli_query($conn,
                    "UPDATE vac_machine_table SET priority = priority + 1 
                     WHERE id = {$task['id']}"
                );
            }
        }
    }

    // 6. Update dragged task with new position
    mysqli_query($conn,
        "UPDATE vac_machine_table SET 
         machine_id = $newMachineId,
         priority = $insertPriority
         WHERE id = $taskId"
    );

    // 7. Recalculate dates for both machines
    recalculateMachineDatesforvac($conn, $draggedTask['machine_id']);
    recalculateMachineDatesforvac($conn, $newMachineId);

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

// Helper function to recalculate dates for a machine/table

}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'select_order') {
    
$json_data = $_REQUEST['work_orders'];
$work_orders = json_decode($json_data, true);

$inserted = false; 

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 = (int)$item['table_id'];

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

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();

        $parent_ids   = $row['parent_ids'];
        $end_date     = $row['end_date'];
        $start_date   = $row['start_date'];
        $quantity     = (int)$row['quantity'];
        $shift_ids    = $row['shift_ids'];
        $product_name = $row['product_name'];
        $color        = $row['color'];
        $total_hours  = $row['total_hours'];
		$set_id       = $row['set_id'];
		
		
        $absolute_quantity_if_set        = $row['absolute_quantity_if_set'];

if ($set_id > 0) {
    $query_route = "SELECT operation_time, parts_per_operation, machine_high_priority FROM set_route_details WHERE set_id = $set_id";
} else {
    $query_route = "SELECT operation_time, parts_per_operation, 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();
    $operation_time = !empty($row_route['operation_time']) ? (float)$row_route['operation_time'] : 1;
    $parts_per_operation = (!empty($row_route['parts_per_operation']) && $row_route['parts_per_operation'] > 0) 
        ? (float)$row_route['parts_per_operation'] 
        : 1;
    $cycle = ($operation_time / $parts_per_operation);
}

        $insertQuery = "
            INSERT INTO cnc_machine_table 
            (machine_id, table_id, work_order_id, part_id, parent_ids, end_date, start_date, quantity, shift_ids, product_name, color, total_hours, cycle, set_id, absolute_quantity_if_set)
            VALUES (
                $machine_id,
                $table_id,
                $work_order_id,
                $part_id,
                '$parent_ids',
                '$end_date',
                '$start_date',
                $quantity,
                '$shift_ids',
                '$product_name',
                '$color',
                '$total_hours',
                '$cycle',
                '$set_id',
                '$absolute_quantity_if_set'
            )";

        if ($conn->query($insertQuery)) {
            $inserted = true;

            $updateQuery = "UPDATE manufacture_machine_table SET in_scheduler_check = 1 WHERE id = $id";
            $conn->query($updateQuery);
        }

    } 
}

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

    
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'select_order_for_assmbly') {
    
$json_data = $_REQUEST['work_orders'];

$work_orders = json_decode($json_data, true);

$inserted = false; 

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'];

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

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();

        $parent_ids   = $row['parent_ids']; $child_ids   = $row['child_ids'];
        $end_date     = $row['end_date'];
        $start_date   = $row['start_date'];
        $quantity     = (int)$row['quantity'];
        $shift_ids    = $row['shift_ids'];
        $product_name = $row['product_name'];
        $color        = $row['color'];
        $total_hours  = $row['total_hours'];
		$set_id       = $row['set_id'];
		
		
        $absolute_quantity_if_set        = $row['absolute_quantity_if_set'];

if ($set_id > 0) {
    $query_route = "SELECT operation_time, parts_per_operation, machine_high_priority FROM set_route_details WHERE set_id = $set_id";
} else {
    $query_route = "SELECT operation_time, parts_per_operation, 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();
    $operation_time = !empty($row_route['operation_time']) ? (float)$row_route['operation_time'] : 1;
    $parts_per_operation = (!empty($row_route['parts_per_operation']) && $row_route['parts_per_operation'] > 0) 
        ? (float)$row_route['parts_per_operation'] 
        : 1;
    $cycle = ($operation_time / $parts_per_operation);
}

        $insertQuery = "
            INSERT INTO assbly_machine_table 
            (machine_id, work_order_id, part_id, parent_ids, child_ids, end_date, start_date, quantity, shift_ids, product_name, color, total_hours, cycle, set_id, absolute_quantity_if_set)
            VALUES (
                $machine_id,
                $work_order_id,
                $part_id,
                '$parent_ids',
				'$child_ids',
                '$end_date',
                '$start_date',
                $quantity,
                '$shift_ids',
                '$product_name',
                '$color',
                '$total_hours',
                '$cycle',
                '$set_id',
                '$absolute_quantity_if_set'
            )";

        if ($conn->query($insertQuery)) {
            $inserted = true;

            $updateQuery = "UPDATE manufacture_machine_table SET in_scheduler_check = 1 WHERE id = $id";
            $conn->query($updateQuery);
        }

    } 
}

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


    
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'select_order_for_vac') {
    
$json_data = $_REQUEST['work_orders'];
$work_orders = json_decode($json_data, true);

$inserted = false; 

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'];

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

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();

        $parent_ids   = $row['parent_ids'];
		$child_ids    = $row['child_ids'];
        $end_date     = $row['end_date'];
        $start_date   = $row['start_date'];
        $quantity     = (int)$row['quantity'];
        $shift_ids    = $row['shift_ids'];
        $product_name = $row['product_name'];
        $color        = $row['color'];
        $total_hours  = $row['total_hours'];
		$set_id       = $row['set_id'];
		
		
        $absolute_quantity_if_set        = $row['absolute_quantity_if_set'];


if ($set_id > 0) {
    $query_route = "SELECT operation_time, parts_per_operation, machine_high_priority FROM set_route_details WHERE set_id = $set_id";
} else {
    $query_route = "SELECT operation_time, parts_per_operation, 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();
    $operation_time = !empty($row_route['operation_time']) ? (float)$row_route['operation_time'] : 1;
    $parts_per_operation = (!empty($row_route['parts_per_operation']) && $row_route['parts_per_operation'] > 0) 
        ? (float)$row_route['parts_per_operation'] 
        : 1;
    $cycle = ($operation_time / $parts_per_operation);
}

	
	$query_priority = "SELECT MAX(priority) AS priority FROM vac_machine_table 
                   WHERE machine_id = $machine_id";
$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;
}

        $insertQuery = "
            INSERT INTO vac_machine_table 
            (machine_id, work_order_id, part_id, parent_ids, child_ids, end_date, start_date, quantity, shift_ids, product_name, color, total_hours, cycle, set_id, priority, absolute_quantity_if_set)
            VALUES (
                $machine_id,
                $work_order_id,
                $part_id,
                '$parent_ids',
				'$child_ids',
                '$end_date',
                '$start_date',
                $quantity,
                '$shift_ids',
                '$product_name',
                '$color',
                '$total_hours',
                '$cycle',
                '$set_id', '$new_priority',
                '$absolute_quantity_if_set'
            )";

        if ($conn->query($insertQuery)) {
            $inserted = true;

            $updateQuery = "UPDATE manufacture_machine_table SET in_scheduler_check = 1 WHERE id = $id";
            $conn->query($updateQuery);
        }

    } 
}

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

    
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'new_hours_for_workorder') {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    date_default_timezone_set('Asia/Kolkata');

   $output = '';
$todayStart = strtotime(date('Y-m-d') . ' 00:00:00');
$todayEnd = strtotime(date('Y-m-d') . ' 23:59:59');

function getFreshOrdersData($conn, $todayStart, $todayEnd) {
    $orders = [];
    $query = "SELECT TIME(start_date) AS start_time, DATE(start_date) AS start_date, part_id, work_order_id, cycle, table_id, total_hours 
              FROM cnc_machine_table 
              WHERE machine_id = 7";
    $result = mysqli_query($conn, $query);

    while ($row = mysqli_fetch_assoc($result)) {
        $startTimestamp = strtotime($row['start_date'] . ' ' . $row['start_time']);
        $hours = floor($row['total_hours']);
        $minutes = ($row['total_hours'] - $hours) * 60;
        $endTimestamp = strtotime("+$hours hours +$minutes minutes", $startTimestamp);

        if ($endTimestamp > $todayEnd) $endTimestamp = $todayEnd;

        if ($endTimestamp >= $todayStart && $startTimestamp <= $todayEnd) {
            $orders[$row['part_id']] = [
                'start' => date('H:i', max($startTimestamp, $todayStart)),
                'end' => date('H:i', $endTimestamp),
                'cycle' => (int)$row['cycle'],
                'table' => (int)$row['table_id'],
                'work_order_id' => $row['work_order_id']
            ];
        }
    }
    return $orders;
}

function toMinutes($time) {
    [$h, $m] = explode(':', $time);
    return $h * 60 + $m;
}

function processOrders($orders) {
    $table1 = [];
    $table2 = [];
    $orderDurations = [];

    foreach ($orders as $key => $order) {
        $startMin = toMinutes($order['start']);
        $endMin = toMinutes($order['end']);
        $durationMin = $endMin - $startMin;
        $durationHours = $durationMin / 60;
        $cycles = $order['cycle'] > 0 ? floor($durationMin / $order['cycle']) : 0;

        $orderDurations[$key] = [
            'hours' => $durationHours,
            'cycles' => $cycles,
            'durationMin' => $durationMin,
            'cycleTime' => $order['cycle'],
            'work_order_id' => $order['work_order_id']
        ];

        $order['startMin'] = $startMin;
        $order['endMin'] = $endMin;

        if ($order['table'] == 1) $table1[$key] = $order;
        else $table2[$key] = $order;
    }

    return ['table1' => $table1, 'table2' => $table2, 'orderDurations' => $orderDurations];
}

function findOverlaps($table1, $table2) {
    $overlaps = [];
    foreach ($table1 as $key1 => $o1) {
        foreach ($table2 as $key2 => $o2) {
            $start = max($o1['startMin'], $o2['startMin']);
            $end = min($o1['endMin'], $o2['endMin']);
            if ($start < $end) {
                $overlaps[] = [
                    'order1' => $key1,
                    'order2' => $key2,
                    'start' => sprintf("%02d:%02d", intdiv($start, 60), $start % 60),
                    'end' => sprintf("%02d:%02d", intdiv($end, 60), $end % 60),
                    'duration' => ($end - $start) / 60,
                    'work_order_id1' => $o1['work_order_id'],
                    'work_order_id2' => $o2['work_order_id']
                ];
            }
        }
    }
    return $overlaps;
}

function calculateAlternatingSchedule($conn, $order1Key, $order1_cycles, $order1_duration,
                                    $order2Key, $order2_cycles, $order2_duration, &$output) {

    $output .= "🔧 Input:<br>";
    $output .= "Order {$order1Key}: {$order1_cycles} cycles × {$order1_duration} min<br>";
    $output .= "Order {$order2Key}: {$order2_cycles} cycles × {$order2_duration} min<br><br>";

    $alternating_cycles = min($order1_cycles, $order2_cycles);
    $time_1_in_alt = $alternating_cycles * $order1_duration;
    $time_2_in_alt = $alternating_cycles * $order2_duration;
    $total_alt_time = $time_1_in_alt + $time_2_in_alt;

    $finished_order = ($order1_cycles < $order2_cycles) ? $order1Key : $order2Key;

    $output .= "Step 1: Alternate until Order {$finished_order} finishes:<br>";
    $output .= "- {$alternating_cycles} cycles of {$order1Key} = {$time_1_in_alt} min<br>";
    $output .= "- {$alternating_cycles} cycles of {$order2Key} = {$time_2_in_alt} min<br>";
    $output .= "→ Total alternating time = {$total_alt_time} min (" . round($total_alt_time / 60, 2) . " hr)<br>";

    // Update total_hours for finished order
    $updateQuery = "UPDATE cnc_machine_table 
                    SET total_hours = " . round($total_alt_time / 60, 2) . " 
                    WHERE part_id = '$finished_order' AND machine_id = 8";
    $output .= $updateQuery . "<br>";
    mysqli_query($conn, $updateQuery);

    // Process remaining cycles
    $remaining1 = $order1_cycles - $alternating_cycles;
    $remaining2 = $order2_cycles - $alternating_cycles;

    $time_remaining1 = $remaining1 * $order1_duration;
    $time_remaining2 = $remaining2 * $order2_duration;

    $total_time = $total_alt_time + $time_remaining1 + $time_remaining2;

    if ($remaining1 > 0) {
        $updateQuery = "UPDATE cnc_machine_table 
                        SET total_hours = " . round($total_time / 60, 2) . " 
                        WHERE part_id = '$order1Key' AND machine_id = 8";
        $output .= "Remaining {$order1Key}: {$remaining1} × {$order1_duration} = {$time_remaining1} min (" . round($time_remaining1 / 60, 2) . " hr)<br>";
        $output .= $updateQuery . "<br>";
        mysqli_query($conn, $updateQuery);
    }

    if ($remaining2 > 0) {
        $updateQuery = "UPDATE cnc_machine_table 
                        SET total_hours = " . round($total_time / 60, 2) . " 
                        WHERE part_id = '$order2Key' AND machine_id = 8";
        $output .= "Remaining {$order2Key}: {$remaining2} × {$order2_duration} = {$time_remaining2} min (" . round($time_remaining2 / 60, 2) . " hr)<br>";
        $output .= $updateQuery . "<br>";
        mysqli_query($conn, $updateQuery);
    }

    $output .= "✅ Final makespan: {$total_alt_time} + {$time_remaining1} + {$time_remaining2} = {$total_time} min<br>";
    $output .= "Updated total hours for remaining orders: " . round($total_time / 60, 2) . " hr<br><br>";

    return [
        'alternating_cycles' => $alternating_cycles,
        'total_time' => $total_time,
        'remaining1' => $remaining1,
        'remaining2' => $remaining2
    ];
}

// === MAIN EXECUTION START ===
$orders = getFreshOrdersData($conn, $todayStart, $todayEnd);
$processedData = processOrders($orders);
$orderDurations = $processedData['orderDurations'];

$output .= "📊 Order Durations and Number of Cycles:<br>";
foreach ($orderDurations as $key => $data) {
    $output .= "🔹 Order $key (Work Order: {$data['work_order_id']}): {$data['hours']} hours, {$data['cycles']} cycles<br>";
}

$output .= "<br>⚠️ Overlapping Periods (Table 1 vs Table 2):<br>";
$overlaps = findOverlaps($processedData['table1'], $processedData['table2']);

foreach ($overlaps as $overlap) {
    $freshOrders = getFreshOrdersData($conn, $todayStart, $todayEnd);
    $freshProcessedData = processOrders($freshOrders);
    $freshOrderDurations = $freshProcessedData['orderDurations'];

    $order1Key = $overlap['order1'];
    $order2Key = $overlap['order2'];

    $output .= "⚙️ Order {$order1Key} (Work Order: {$overlap['work_order_id1']}, Table 1) overlaps with Order {$order2Key} (Work Order: {$overlap['work_order_id2']}, Table 2) from {$overlap['start']} to {$overlap['end']} ({$overlap['duration']} hours)<br>";

    $checkQuery = "SELECT * FROM processed_overlaps 
                   WHERE order1_id = '$order1Key' 
                   AND order2_id = '$order2Key' 
                   AND date = CURDATE()";
    $checkResult = mysqli_query($conn, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        $output .= "<i>⏩ This overlap was already processed earlier today.</i><br><br>";
        continue;
    }

    $order1_cycles = $freshOrderDurations[$order1Key]['cycles'];
    $order1_duration = $freshOrderDurations[$order1Key]['cycleTime'];
    $order2_cycles = $freshOrderDurations[$order2Key]['cycles'];
    $order2_duration = $freshOrderDurations[$order2Key]['cycleTime'];

    $output .= "<br><b>🔄 Alternating Schedule:</b><br>";

    $result = calculateAlternatingSchedule(
        $conn,
        $order1Key, $order1_cycles, $order1_duration,
        $order2Key, $order2_cycles, $order2_duration,
        $output
    );

    $insertQuery = "INSERT INTO processed_overlaps 
                    (order1_id, order2_id, date, alternating_cycles, total_time_minutes) 
                    VALUES 
                    ('$order1Key', '$order2Key', CURDATE(), {$result['alternating_cycles']}, {$result['total_time']})";
    mysqli_query($conn, $insertQuery);
}



// ... [keep all the previous code exactly the same until the merged code part] ...

// Merged code from the second part - now using part_id and work_order_id from above
$output .= "<br><br>📦 Processing manufacture machine table entries for today's orders:<br>";

// Get all unique part_id and work_order_id combinations from today's orders
$orderDetails = [];
foreach ($orderDurations as $part_id => $data) {
    $work_order_id = $data['work_order_id'];
    if (!isset($orderDetails[$part_id])) {
        $orderDetails[$part_id] = $work_order_id;
    }
}

// Process each order in manufacture_machine_table
foreach ($orderDetails as $part_id => $work_order_id) {
    $output .= "🔍 Looking for manufacture entries for Part ID: {$part_id}, Work Order: {$work_order_id}<br>";
    
    $res = mysqli_query($conn, "SELECT id, start_date, total_hours, shift_ids 
                               FROM manufacture_machine_table 
                               WHERE part_id = '{$part_id}' AND work_order_id = '{$work_order_id}'");

    if (mysqli_num_rows($res) > 0) {
        while ($row = mysqli_fetch_assoc($res)) {
            $id = $row['id'];
            $startDateTime = new DateTime($row['start_date']);
            $totalHours = floatval($row['total_hours']);
            $shiftIdList = explode(',', $row['shift_ids']); // comma-separated shift ids

            // Prepare shift schedule for the week
            $shifts = [];
            $resultShift = mysqli_query($conn, "SELECT * FROM working_hours WHERE shift_id IN (" . implode(',', $shiftIdList) . ")");
            while ($shift = mysqli_fetch_assoc($resultShift)) {
                $day = intval($shift['day_shifts']); // 1 = Monday, 7 = Sunday
                $shifts[$day][] = [
                    'start' => $shift['start_time'],
                    'end' => $shift['end_time'],
                    'duration' => floatval($shift['hours']),
                ];
            }

            // Add working hours across days
            $remainingHours = $totalHours;
            $current = clone $startDateTime;

            while ($remainingHours > 0) {
                $dayOfWeek = (int)$current->format('N'); // 1 (Monday) to 7 (Sunday)

                if (isset($shifts[$dayOfWeek])) {
                    foreach ($shifts[$dayOfWeek] as $shift) {
                        // Calculate actual shift DateTime
                        $shiftStart = DateTime::createFromFormat('Y-m-d H:i:s', $current->format('Y-m-d') . ' ' . $shift['start']);
                        $shiftEnd = DateTime::createFromFormat('Y-m-d H:i:s', $current->format('Y-m-d') . ' ' . $shift['end']);

                        // Handle overnight shifts
                        if ($shiftEnd < $shiftStart) {
                            $shiftEnd->modify('+1 day');
                        }

                        $shiftDuration = $shift['duration'];

                        if ($remainingHours <= $shiftDuration) {
                            $intervalSeconds = $remainingHours * 3600;
                            $endDate = clone $shiftStart;
                            $endDate->modify("+$intervalSeconds seconds");

                            // Update the end_date
                            $formattedEnd = $endDate->format('Y-m-d H:i:s');
                            mysqli_query($conn, "UPDATE manufacture_machine_table SET end_date = '$formattedEnd' WHERE id = $id");
                            $output .= "✅ Updated end_date for ID {$id} (Part {$part_id}, WO {$work_order_id}) to {$formattedEnd}<br>";
                            $remainingHours = 0;
                            break 2;
                        } else {
                            $remainingHours -= $shiftDuration;
                        }
                    }
                }

                // Move to next day
                $current->modify('+1 day');
            }
        }
    } else {
        $output .= "ℹ️ No manufacture entries found for Part ID: {$part_id}, Work Order: {$work_order_id}<br>";
    }
}

$output .= "<br>Manufacture machine table processing complete.<br>";
echo $output;
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_purchase_list') {
    // assume $conn is your mysqli connection
    $item_id = (int)$_REQUEST['item_id'];

    // Fetch purchase_list rows
    $sql    = "SELECT * FROM purchase_list WHERE item_id = $item_id";
    $result = mysqli_query($conn, $sql);

    if (!$result || mysqli_num_rows($result) === 0) {
        echo "<p>No records found.</p>";
        exit;
    }

    // Build table
    echo '<table class="table table-bordered">';
    echo '<thead>
            <tr>
              <th>Qty</th>
              <th>Sales Item</th>
              <th>Ordered</th>
            </tr>
          </thead>
          <tbody>';

    while ($r = mysqli_fetch_assoc($result)) {
        // disable checked boxes for already-ordered items
        $disabled = $r['ordered'] ? 'checked disabled' : '';
        echo '<tr>
                <td>' . $r['quantity_requested'] . '</td>
                <td>' . $r['main_item_id']    . '</td>
                <td>
                  <input type="checkbox" class="order-checkbox"
                         data-pl-id="'   . $r['id']                   . '"
                         data-item-id="' . $item_id                   . '"
                         data-qty="'     . $r['quantity_requested']   . '"
                         ' . $disabled . '>
                </td>
              </tr>';
    }

    echo '  </tbody>
          </table>';

    // show the modal
    echo "<script>$('#purchaseListModal').modal('show');</script>";
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'mark_ordered') {
    // assume $conn is your mysqli connection
$pl_id  = (int)$_REQUEST['purchase_list_id'];
$item_id = (int)$_REQUEST['item_id'];
$qty     = (int)$_REQUEST['quantity'];

// Update purchase_list ordered = 1
mysqli_query($conn, "UPDATE purchase_list SET ordered = 1 WHERE id = $pl_id");

// Update quantity_requested (with GREATEST logic)
mysqli_query($conn, "
  UPDATE purchase_item_qunatity_mapping
  SET quantity_requested = GREATEST(quantity_requested - $qty, 0)
  WHERE item_id = $item_id
");

// Fetch the updated quantity
$result = mysqli_query($conn, "SELECT quantity_requested FROM purchase_item_qunatity_mapping WHERE item_id = $item_id");

if ($row = mysqli_fetch_assoc($result)) {
    echo json_encode([
        'success' => true,
        'new_remaining' => (int)$row['quantity_requested']
    ]);
} else {
    echo json_encode([
        'success' => false,
        'error' => 'Item not found'
    ]);
}
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'process_bulk_order') {
  
    
    try {
        // Validate input
        if (!isset($_POST['order_data'])) {
            throw new Exception('No order data received');
        }
        
        $orderData = json_decode($_POST['order_data'], true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON data');
        }
        
        // Validate required fields
        if (empty($orderData['orders'])) {
            throw new Exception('No items to order');
        }
        
        $response = ['success' => false];
        $conn->autocommit(false); // Start transaction
        
        foreach ($orderData['orders'] as $supplierOrder) {
            // Get supplier ID
            $supplierId = 15; 
			//$supplierId = getSupplierIdByName($supplierOrder['supplier']);
            if (!$supplierId) {
                throw new Exception("Supplier not found: " . $supplierOrder['supplier']);
            }
            
            // Create purchase order
            $poRef = generateNextPoRef();
            $notes = !empty($orderData['notes']) ? $conn->real_escape_string($orderData['notes']) : '';
            
            $poQuery = "INSERT INTO purchase_order 
                       (order_ref, order_status, supplier_id, deliver_to, order_notes, created_by, created_on) 
                       VALUES 
                       ('$poRef', 1, '$supplierId', 'Default Delivery Address', '$notes', '1', NOW())";
            
            if (!$conn->query($poQuery)) {
                throw new Exception("PO creation failed: " . $conn->error);
            }
            
            $poId = $conn->insert_id;
            $ordering = 1;
            
            foreach ($supplierOrder['items'] as $item) {
                $itemId = getItemIdByPartNumber($item['partNumber']);
                if (!$itemId) {
                    throw new Exception("Part not found: " . $item['partNumber']);
                }
                
                // Convert weekDate to proper MySQL date format
                $expectedDate = !empty($item['weekDate']) ? 
                    date('Y-m-d', strtotime($item['weekDate'])) : 
                    date('Y-m-d', strtotime('+1 week'));
                
                $qty = (int)$item['qty'];
                $unitPrice = (float)$item['unitPrice'];
                $total = $qty * $unitPrice;
                
                $insertQuery = "INSERT INTO purchase_order_items_mapping 
                               (po_id, ordering, item_type, part_number, description, quantity, 
                                unit_price, total, expected_date, created_on)
                               VALUES 
                               ('$poId', '$ordering', '1', '$itemId', '{$conn->real_escape_string($item['partNumber'])}', 
                                '$qty', '$unitPrice', '$total', '$expectedDate', NOW())";
                
                if (!$conn->query($insertQuery)) {
                    throw new Exception("Item insertion failed: " . $conn->error);
                }
                
                $ordering++;
            }
        }
        
        $conn->commit();
        $response = ['success' => true, 'message' => 'Orders processed successfully'];
        
    } catch (Exception $e) {
        $conn->rollback();
        $response = ['success' => false, 'message' => $e->getMessage()];
    }
    
    echo json_encode($response);
    exit;
}

// Helper functions
function getSupplierIdByName($name) {
    global $conn;
    $name = $conn->real_escape_string($name);
    $query = "SELECT id FROM suppliers WHERE name = '$name' LIMIT 1";
    $result = $conn->query($query);
    return $result && $result->num_rows ? $result->fetch_assoc()['id'] : 0;
}

function getItemIdByPartNumber($partNumber) {
    global $conn;
    $partNumber = $conn->real_escape_string($partNumber);
    $query = "SELECT id FROM item_management WHERE part_number = '$partNumber' LIMIT 1";
    $result = $conn->query($query);
    return $result && $result->num_rows ? $result->fetch_assoc()['id'] : 0;
}

function generateNextPoRef() {
    global $conn;
    $query = "SELECT MAX(order_ref) as max_ref FROM purchase_order";
    $result = $conn->query($query);
    $row = $result->fetch_assoc();
    return $row['max_ref'] ? $row['max_ref'] + 1 : 1000;
}



?>







