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

if (isset($_REQUEST['action'])) {
    while (ob_get_level()) {
        ob_end_clean(); 
    }
    header('Content-Type: application/json');
    header('Cache-Control: no-cache, must-revalidate');
}

if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_current_task_priority_vac') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $machineId = intval($_REQUEST['machine_id']);
    $partId = intval($_REQUEST['part_id']);
    
    $query = "SELECT id, priority FROM vac_machine_table 
              WHERE work_order_id = $workOrderId 
              AND machine_id = $machineId 
              AND part_id = $partId 
              LIMIT 1";
    
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        echo json_encode([
            'success' => true,
            'task_id' => $row['id'],
            'priority' => $row['priority']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Task not found'
        ]);
    }
    exit;
}

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

// RECALCULATE MACHINE DATES FOR VAC
function recalculateMachineDatesforvac($conn, $machineId) {

    set_time_limit(300);

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

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

    // ------------------------------------------------
    // Load machine tasks
    // ------------------------------------------------
    $taskResult = mysqli_query($conn,
        "SELECT 
            v.id,
            v.work_order_id,
            v.part_id,
            v.is_break,
            v.is_breakdown_affected,
            v.breakdown_hours,
            v.start_date,
            v.total_hours_update AS hours_to_schedule,
            v.total_hours AS hours,
            v.setting_instruction
        FROM vac_machine_table v
        LEFT JOIN manufacture_machine_table m
            ON v.work_order_id = m.work_order_id
            AND v.part_id = m.part_id
        WHERE v.machine_id = $machineId
        AND (v.finished = 0 OR v.is_breakdown_affected = 1)
        ORDER BY v.priority"
    );

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

    // Start scheduling from today
    $currentDateTime = strtotime(date('Y-m-d') . ' 00:00:00');

    $previous_setting_instruction = null;

    foreach ($tasks as $task) {

        $taskId = $task['id'];

        // ------------------------------------------------
        // Check if production already started
        // ------------------------------------------------
        $checkResult = mysqli_query($conn, "
            SELECT 1 
            FROM vac_part_count_log 
            WHERE vac_machine_table_id = $taskId 
            LIMIT 1
        ");

        $productionStarted = mysqli_num_rows($checkResult) > 0;

        $total_hours = (float)$task['hours_to_schedule'];
        $setting_instruction = $task['setting_instruction'];
        $start_date = $task['start_date'];
        $is_break = (int)$task['is_break'];
        $breakdown_hours = (float)$task['breakdown_hours'];

        $setup_hours = 0.00;

        if ($is_break === 1) {

            $total_hours = (float)$task['hours'];
            $setup_hours = 0.00;

        } else {

            // If production already started → no setup
            if ($productionStarted) {

                $setup_hours = 0.00;

            } else {

                if ($previous_setting_instruction !== null) {

                    if (strcasecmp($previous_setting_instruction, $setting_instruction) === 0) {
                        $setup_hours = 1.00;
                    } else {
                        $setup_hours = 2.00;
                    }

                } else {
                    $setup_hours = 2.00;
                }

            }

            $total_hours = (float)($total_hours + $setup_hours + $breakdown_hours);
        }

        $hoursRemaining = $total_hours;

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

        while ($hoursRemaining > 0) {

            $currentDate = date('Y-m-d', $currentDateTime);
            $dayOfWeek = date('w', $currentDateTime);

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

            foreach ($shiftsByDay[$dayOfWeek] as $shift) {

                $shiftStart = strtotime($currentDate . ' ' . $shift['start_time']);
                $shiftEnd   = strtotime($currentDate . ' ' . $shift['end_time']);
                $shiftName  = $shift['shift_name'];

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

        // Format remaining hours string
        $remainingHoursStr = '';

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

        $remainingHoursStr = rtrim($remainingHoursStr, ',');

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

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

        mysqli_query($conn, $query);

        $previous_setting_instruction = $setting_instruction;
    }
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

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

    // ============================================
    // ENHANCED BREAKDOWN HANDLING WITH WORK ORDER SPLITTING
    // ============================================
    if ($actionType === 'breakdown') {
        // Get breakdown duration from request
        $breakdownDuration = isset($_REQUEST['breakdown_duration']) ? floatval($_REQUEST['breakdown_duration']) : 1.0;
        
        // Validate breakdown duration
        if ($breakdownDuration < 0.5 || $breakdownDuration > 24) {
            echo json_encode(["success" => false, "message" => "Invalid breakdown duration. Must be between 0.5 and 24 hours."]);
            exit;
        }
        
        // Start transaction
        mysqli_autocommit($conn, false);
        $error = false;
        $errorMessage = '';
        
        // Get current work order details
        $workOrderQuery = "SELECT id, work_order_id, part_id, quantity, priority, total_hours, 
                                  product_name, set_id, end_date
                          FROM vac_machine_table 
                          WHERE id = $vacMachineTableId 
                          AND machine_id = $machineId 
                          LIMIT 1";
        
        $workOrderResult = mysqli_query($conn, $workOrderQuery);
        
        if ($workOrderResult && mysqli_num_rows($workOrderResult) > 0) {
            $currentWorkOrder = mysqli_fetch_assoc($workOrderResult);
            $currentId = $currentWorkOrder['id'];
            $currentPriority = intval($currentWorkOrder['priority']);
            $totalQuantity = intval($currentWorkOrder['quantity']);
            $totalHours = floatval($currentWorkOrder['total_hours']);
            $productName = $currentWorkOrder['product_name'];
            $setId = intval($currentWorkOrder['set_id']);
            $endDate = $currentWorkOrder['end_date'];
            
            // Get OK count (completed quantity)
            $okCountQuery = "SELECT SUM(quantity) AS ok_count
                            FROM vac_part_count_log
                            WHERE work_order_id = $workOrderId
                            AND vac_machine_table_id = $vacMachineTableId
                            AND part_id = $partId
                            AND type = 'ok'";
            
            $okCountResult = mysqli_query($conn, $okCountQuery);
            $okCount = 0;
            
            if ($okCountResult && mysqli_num_rows($okCountResult) > 0) {
                $okRow = mysqli_fetch_assoc($okCountResult);
                $okCount = intval($okRow['ok_count'] ?? 0);
            }
            
            // Calculate remaining quantity
            $remainingQuantity = $totalQuantity - $okCount;
            
            // Only split if there's actual progress (OK count > 0) and remaining work
            if ($okCount > 0 && $remainingQuantity > 0) {
                // Calculate hours for completed and remaining portions
                $completedHours = ($okCount / $totalQuantity) * $totalHours;
                $remainingHours = ($remainingQuantity / $totalQuantity) * $totalHours;
                
                // Step 1: Update current work order with completed quantity and mark as finished
                $updateCurrentQuery = "UPDATE vac_machine_table 
                                     SET quantity = $okCount,
                                         total_hours = $completedHours,
                                         finished = 1
                                     WHERE id = $currentId";
                
                if (!mysqli_query($conn, $updateCurrentQuery)) {
                    $error = true;
                    $errorMessage = "Failed to update current work order: " . mysqli_error($conn);
                }
                
                if (!$error) {
                    // Step 2: Shift all subsequent work orders by +2 (for breakdown task + remaining work order)
                    $shiftQuery = "UPDATE vac_machine_table 
                                 SET priority = priority + 2 
                                 WHERE machine_id = $machineId 
                                 AND priority > $currentPriority";
                    
                    if (!mysqli_query($conn, $shiftQuery)) {
                        $error = true;
                        $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
                    }
                }
                
                if (!$error) {
                    // Step 3: Insert breakdown task
                    $breakdownPriority = $currentPriority + 1;
                    $breakdownStartDate = $endDate; // Breakdown starts when current work order ends
                    $breakdownEndDate = date('Y-m-d H:i:s', strtotime($breakdownStartDate) + ($breakdownDuration * 3600));
                    
                    // Get breakdown reason text
                    $reasonQuery = "SELECT code FROM breakdown_reason WHERE id = $breakdownReason LIMIT 1";
                    $reasonResult = mysqli_query($conn, $reasonQuery);
                    $reasonText = "Unknown";
                    if ($reasonResult && mysqli_num_rows($reasonResult) > 0) {
                        $reasonRow = mysqli_fetch_assoc($reasonResult);
                        $reasonText = mysqli_real_escape_string($conn, $reasonRow['code']);
                    }
                    
                    $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                            (machine_id, start_date, end_date, total_hours, remaing_hours,
                                             is_break, break_reason, priority, work_order_id, part_id, 
                                             quantity, product_name)
                                            VALUES ($machineId, '$breakdownStartDate', '$breakdownEndDate', 
                                                    $breakdownDuration, $breakdownDuration, 1, 
                                                    'BREAKDOWN: $reasonText', $breakdownPriority, 
                                                    0, 0, 0, 'BREAKDOWN: $reasonText')";
                    
                    if (!mysqli_query($conn, $insertBreakdownQuery)) {
                        $error = true;
                        $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
                    }
                }
                
                if (!$error) {
                    // Step 4: Insert new work order for remaining quantity
                    $remainingPriority = $currentPriority + 2;
                    
                    $insertRemainingQuery = "INSERT INTO vac_machine_table 
                                            (machine_id, work_order_id, part_id, quantity, total_hours,
                                             priority, product_name, set_id, finished, is_break,
                                             start_date, end_date, remaing_hours)
                                            SELECT machine_id, work_order_id, part_id, $remainingQuantity, 
                                                   $remainingHours, $remainingPriority, product_name, 
                                                   set_id, 0, 0, start_date, end_date, remaing_hours
                                            FROM vac_machine_table
                                            WHERE id = $currentId";
                    
                    if (!mysqli_query($conn, $insertRemainingQuery)) {
                        $error = true;
                        $errorMessage = "Failed to insert remaining work order: " . mysqli_error($conn);
                    }
                }
                
            } else if ($okCount == 0) {
                // No progress yet - just insert breakdown task after current work order
                $breakdownPriority = $currentPriority + 1;
                
                // Shift all subsequent work orders by +1
                $shiftQuery = "UPDATE vac_machine_table 
                             SET priority = priority + 1 
                             WHERE machine_id = $machineId 
                             AND priority > $currentPriority";
                
                if (!mysqli_query($conn, $shiftQuery)) {
                    $error = true;
                    $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
                }
                
                if (!$error) {
                    // Insert breakdown task
                    $breakdownStartDate = $endDate;
                    $breakdownEndDate = date('Y-m-d H:i:s', strtotime($breakdownStartDate) + ($breakdownDuration * 3600));
                    
                    // Get breakdown reason text
                    $reasonQuery = "SELECT code FROM breakdown_reason WHERE id = $breakdownReason LIMIT 1";
                    $reasonResult = mysqli_query($conn, $reasonQuery);
                    $reasonText = "Unknown";
                    if ($reasonResult && mysqli_num_rows($reasonResult) > 0) {
                        $reasonRow = mysqli_fetch_assoc($reasonResult);
                        $reasonText = mysqli_real_escape_string($conn, $reasonRow['code']);
                    }
                    
                    $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                            (machine_id, start_date, end_date, total_hours, remaing_hours,
                                             is_break, break_reason, priority, work_order_id, part_id, 
                                             quantity, product_name)
                                            VALUES ($machineId, '$breakdownStartDate', '$breakdownEndDate', 
                                                    $breakdownDuration, $breakdownDuration, 1, 
                                                    'BREAKDOWN: $reasonText', $breakdownPriority, 
                                                    0, 0, 0, 'BREAKDOWN: $reasonText')";
                    
                    if (!mysqli_query($conn, $insertBreakdownQuery)) {
                        $error = true;
                        $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
                    }
                }
            } else {
                // OK count >= total quantity (100% complete) - just insert breakdown
                $breakdownPriority = $currentPriority + 1;
                
                // Shift all subsequent work orders by +1
                $shiftQuery = "UPDATE vac_machine_table 
                             SET priority = priority + 1 
                             WHERE machine_id = $machineId 
                             AND priority > $currentPriority";
                
                if (!mysqli_query($conn, $shiftQuery)) {
                    $error = true;
                    $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
                }
                
                if (!$error) {
                    $breakdownStartDate = $endDate;
                    $breakdownEndDate = date('Y-m-d H:i:s', strtotime($breakdownStartDate) + ($breakdownDuration * 3600));
                    
                    // Get breakdown reason text
                    $reasonQuery = "SELECT code FROM breakdown_reason WHERE id = $breakdownReason LIMIT 1";
                    $reasonResult = mysqli_query($conn, $reasonQuery);
                    $reasonText = "Unknown";
                    if ($reasonResult && mysqli_num_rows($reasonResult) > 0) {
                        $reasonRow = mysqli_fetch_assoc($reasonResult);
                        $reasonText = mysqli_real_escape_string($conn, $reasonRow['code']);
                    }
                    
                    $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                            (machine_id, start_date, end_date, total_hours, remaing_hours,
                                             is_break, break_reason, priority, work_order_id, part_id, 
                                             quantity, product_name)
                                            VALUES ($machineId, '$breakdownStartDate', '$breakdownEndDate', 
                                                    $breakdownDuration, $breakdownDuration, 1, 
                                                    'BREAKDOWN: $reasonText', $breakdownPriority, 
                                                    0, 0, 0, 'BREAKDOWN: $reasonText')";
                    
                    if (!mysqli_query($conn, $insertBreakdownQuery)) {
                        $error = true;
                        $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
                    }
                }
            }
            
        } else {
            $error = true;
            $errorMessage = "Current work order not found";
        }
        
        // Commit or rollback transaction
        if ($error) {
            mysqli_rollback($conn);
            
            // Still log the breakdown action even if scheduling fails
            $sql = "INSERT INTO vac_machine_activity_log 
                    (work_order_id, part_id, machine_id, engineer_id, action_type, breakdown_reason, vac_machine_table_id, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $breakdownReason, $vacMachineTableId, '$createdOn')";
            mysqli_query($conn, $sql);
            
            echo json_encode(["success" => false, "message" => "Breakdown logged but scheduling failed: " . $errorMessage]);
        } else {
            mysqli_commit($conn);
            
            // Log the breakdown action
            $sql = "INSERT INTO vac_machine_activity_log 
                    (work_order_id, part_id, machine_id, engineer_id, action_type, breakdown_reason, vac_machine_table_id, created_at) 
                    VALUES ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $breakdownReason, $vacMachineTableId, '$createdOn')";
            mysqli_query($conn, $sql);
            
            // Recalculate all dates for this machine
            recalculateMachineDatesforvac($conn, $machineId);
            
            $successMessage = "Breakdown logged successfully!";
            if ($okCount > 0 && $remainingQuantity > 0) {
                $successMessage .= " Work order split: $okCount completed, $remainingQuantity remaining.";
            }
            
            echo json_encode(["success" => true, "message" => $successMessage]);
        }
        
        mysqli_autocommit($conn, true);
        exit;
    }
    
    // ============================================
    // STANDARD ACTION HANDLING (pause, start, finish)
    // ============================================
    
    // Insert Action Log
    if ($actionType === 'breakdown' && $breakdownReason) {
        $sql = "
            INSERT INTO vac_machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, breakdown_reason, vac_machine_table_id, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $breakdownReason, $vacMachineTableId, '$createdOn')
        ";
    } else {
        $sql = "
            INSERT INTO vac_machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, vac_machine_table_id, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $vacMachineTableId, '$createdOn')
        ";
    }
    
    $result = mysqli_query($conn, $sql);
    
    if ($result) {
        // Mark record finished when action = 'finish'
        if ($actionType === 'finish') {
            $sqlFinish = "
                UPDATE vac_machine_table 
                SET finished = 1 
                WHERE work_order_id = $workOrderId 
                  AND part_id = $partId
            ";
            mysqli_query($conn, $sqlFinish);
        }
        
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    
    exit;
}*/
// ============================================
// SEPARATE BREAKDOWN HANDLER
// ============================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_breakdown_vac') {

    $workOrderId       = intval($_REQUEST['work_order_id']);
    $partId            = intval($_REQUEST['part_id']);
    $machineId         = intval($_SESSION['machine_id']);
    $engineerId        = intval($_SESSION['engineer_id']);
    $vacMachineTableId = intval($_REQUEST['vac_machine_table_id']);
    $breakdownReason   = isset($_REQUEST['breakdown_reason']) ? intval($_REQUEST['breakdown_reason']) : null;
    $breakdownDuration = isset($_REQUEST['breakdown_duration']) ? floatval($_REQUEST['breakdown_duration']) : 1.0;
    $createdOn         = date('Y-m-d H:i:s');

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

    if ($breakdownDuration < 0.5 || $breakdownDuration > 24) {
        echo json_encode(["success" => false, "message" => "Invalid breakdown duration. Must be between 0.5 and 24 hours."]);
        exit;
    }

    if (!$breakdownReason) {
        echo json_encode(["success" => false, "message" => "Breakdown reason is required."]);
        exit;
    }

    mysqli_autocommit($conn, false);
    $error             = false;
    $errorMessage      = '';
    $okCount           = 0;
    $remainingQuantity = 0;

    // Get current work order details — including setup_hours
    $workOrderQuery = "SELECT id, work_order_id, part_id, quantity, priority, total_hours, 
                              setup_hours, product_name, set_id, end_date
                       FROM vac_machine_table 
                       WHERE id = $vacMachineTableId 
                       AND machine_id = $machineId 
                       LIMIT 1";

    $workOrderResult = mysqli_query($conn, $workOrderQuery);

    if (!$workOrderResult || mysqli_num_rows($workOrderResult) == 0) {
        mysqli_rollback($conn);
        mysqli_autocommit($conn, true);
        echo json_encode(["success" => false, "message" => "Work order not found"]);
        exit;
    }

    $currentWorkOrder = mysqli_fetch_assoc($workOrderResult);
    $currentId        = $currentWorkOrder['id'];
    $currentPriority  = intval($currentWorkOrder['priority']);
    $totalQuantity    = intval($currentWorkOrder['quantity']);
    $totalHours       = floatval($currentWorkOrder['total_hours']);
    $setupHours       = floatval($currentWorkOrder['setup_hours']);
    $productName      = $currentWorkOrder['product_name'];
    $setId            = intval($currentWorkOrder['set_id']);
    $endDate          = $currentWorkOrder['end_date'];

    // Get OK count
    $okCountQuery  = "SELECT SUM(quantity) AS ok_count
                      FROM vac_part_count_log
                      WHERE work_order_id = $workOrderId
                      AND vac_machine_table_id = $vacMachineTableId
                      AND part_id = $partId
                      AND type = 'ok'";
    $okCountResult = mysqli_query($conn, $okCountQuery);

    if ($okCountResult && mysqli_num_rows($okCountResult) > 0) {
        $okRow   = mysqli_fetch_assoc($okCountResult);
        $okCount = intval($okRow['ok_count'] ?? 0);
    }

    $remainingQuantity = $totalQuantity - $okCount;

    // Get breakdown reason text
    $reasonText = "Unknown";

    // -----------------------------------------------
    // CASE 1: Production started, remaining work exists
    // -----------------------------------------------
    if ($okCount > 0 && $remainingQuantity > 0) {

        // ✅ Setup hours stay with completed WO only — remaining WO has no setup
        $runHoursPerUnit = ($totalHours - $setupHours) / $totalQuantity;
        $completedHours  = ($okCount * $runHoursPerUnit) + $setupHours;
        $remainingHours  = ($remainingQuantity * $runHoursPerUnit);

        // Mark current WO as finished with completed qty and correct hours
        $updateCurrentQuery = "UPDATE vac_machine_table 
                               SET quantity    = $okCount,
                                   total_hours = $completedHours,
                                   finished    = 1
                               WHERE id = $currentId";
        if (!mysqli_query($conn, $updateCurrentQuery)) {
            $error        = true;
            $errorMessage = "Failed to update current work order: " . mysqli_error($conn);
        }

        if (!$error) {
            // Shift subsequent WOs by +2 to make room for breakdown + remaining
            $shiftQuery = "UPDATE vac_machine_table 
                           SET priority = priority + 2 
                           WHERE machine_id = $machineId 
                           AND priority > $currentPriority";
            if (!mysqli_query($conn, $shiftQuery)) {
                $error        = true;
                $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
            }
        }

        if (!$error) {
            // Insert breakdown task at priority + 1
            $breakdownPriority = $currentPriority + 1;
            $bdStartDate       = $endDate;
            $bdEndDate         = date('Y-m-d H:i:s', strtotime($bdStartDate) + ($breakdownDuration * 3600));

            $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                    (machine_id, start_date, end_date, total_hours, remaing_hours,
                                     is_break, break_reason, priority, work_order_id, part_id, 
                                     quantity, product_name, setup_hours)
                                    VALUES ($machineId, '$bdStartDate', '$bdEndDate', 
                                            $breakdownDuration, $breakdownDuration, 1, 
                                            'BREAKDOWN: $reasonText', $breakdownPriority, 
                                            0, 0, 0, 'BREAKDOWN: $reasonText', 0)";
            if (!mysqli_query($conn, $insertBreakdownQuery)) {
                $error        = true;
                $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
            }
        }

        if (!$error) {
            // Insert remaining work order at priority + 2
            // ✅ setup_hours = 0 (already incurred), NULL dates for recalculation
            $remainingPriority = $currentPriority + 2;

            $insertRemainingQuery = "INSERT INTO vac_machine_table 
                                    (machine_id, work_order_id, part_id, quantity, total_hours,
                                     priority, product_name, set_id, finished, is_break,
                                     start_date, end_date, remaing_hours, setup_hours)
                                    SELECT machine_id, work_order_id, part_id, $remainingQuantity, 
                                           $remainingHours, $remainingPriority, product_name, 
                                           set_id, 0, 0, NULL, NULL, $remainingHours, 0
                                    FROM vac_machine_table
                                    WHERE id = $currentId";
            if (!mysqli_query($conn, $insertRemainingQuery)) {
                $error        = true;
                $errorMessage = "Failed to insert remaining work order: " . mysqli_error($conn);
            }
        }

    // -----------------------------------------------
    // CASE 2: No production started yet
    // -----------------------------------------------
    } else if ($okCount == 0) {

        $breakdownPriority = $currentPriority + 1;

        // Shift all subsequent WOs by +1
        $shiftQuery = "UPDATE vac_machine_table 
                       SET priority = priority + 1 
                       WHERE machine_id = $machineId 
                       AND priority > $currentPriority";
        if (!mysqli_query($conn, $shiftQuery)) {
            $error        = true;
            $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
        }

        if (!$error) {
            $bdStartDate = $endDate;
            $bdEndDate   = date('Y-m-d H:i:s', strtotime($bdStartDate) + ($breakdownDuration * 3600));

            $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                    (machine_id, start_date, end_date, total_hours, remaing_hours,
                                     is_break, break_reason, priority, work_order_id, part_id, 
                                     quantity, product_name, setup_hours)
                                    VALUES ($machineId, '$bdStartDate', '$bdEndDate', 
                                            $breakdownDuration, $breakdownDuration, 1, 
                                            'BREAKDOWN: $reasonText', $breakdownPriority, 
                                            0, 0, 0, 'BREAKDOWN: $reasonText', 0)";
            if (!mysqli_query($conn, $insertBreakdownQuery)) {
                $error        = true;
                $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
            }
        }

    // -----------------------------------------------
    // CASE 3: 100% complete — just insert breakdown after
    // -----------------------------------------------
    } else {

        $breakdownPriority = $currentPriority + 1;

        // Shift all subsequent WOs by +1
        $shiftQuery = "UPDATE vac_machine_table 
                       SET priority = priority + 1 
                       WHERE machine_id = $machineId 
                       AND priority > $currentPriority";
        if (!mysqli_query($conn, $shiftQuery)) {
            $error        = true;
            $errorMessage = "Failed to shift priorities: " . mysqli_error($conn);
        }

        if (!$error) {
            $bdStartDate = $endDate;
            $bdEndDate   = date('Y-m-d H:i:s', strtotime($bdStartDate) + ($breakdownDuration * 3600));

            $insertBreakdownQuery = "INSERT INTO vac_machine_table 
                                    (machine_id, start_date, end_date, total_hours, remaing_hours,
                                     is_break, break_reason, priority, work_order_id, part_id, 
                                     quantity, product_name, setup_hours)
                                    VALUES ($machineId, '$bdStartDate', '$bdEndDate', 
                                            $breakdownDuration, $breakdownDuration, 1, 
                                            'BREAKDOWN: $reasonText', $breakdownPriority, 
                                            0, 0, 0, 'BREAKDOWN: $reasonText', 0)";
            if (!mysqli_query($conn, $insertBreakdownQuery)) {
                $error        = true;
                $errorMessage = "Failed to insert breakdown task: " . mysqli_error($conn);
            }
        }
    }

    // -----------------------------------------------
    // Log into vac_machine_breakdown_log
    // -----------------------------------------------
    $breakdownLogSql = "INSERT INTO vac_machine_breakdown_log 
                        (work_order_id, part_id, machine_id, engineer_id, vac_machine_table_id, 
                         breakdown_reason, breakdown_duration, ok_count_at_breakdown, 
                         remaining_quantity, status, created_at) 
                        VALUES ($workOrderId, $partId, $machineId, $engineerId, $vacMachineTableId, 
                                $breakdownReason, $breakdownDuration, $okCount, 
                                $remainingQuantity, 'active', '$createdOn')";
    mysqli_query($conn, $breakdownLogSql);

    if ($error) {
        mysqli_rollback($conn);
        mysqli_autocommit($conn, true);
        echo json_encode(["success" => false, "message" => "Breakdown logged but scheduling failed: " . $errorMessage]);
    } else {
        mysqli_commit($conn);
        mysqli_autocommit($conn, true);
        recalculateMachineDatesforvac($conn, $machineId);

        $successMessage = "Breakdown logged successfully!";
        if ($okCount > 0 && $remainingQuantity > 0) {
            $successMessage .= " Work order split: $okCount completed, $remainingQuantity remaining.";
        }

        echo json_encode(["success" => true, "message" => $successMessage]);
    }

    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_vac') {
    $workOrderId       = intval($_REQUEST['work_order_id']); 
    $vac_machine_table_id = intval($_REQUEST['vac_machine_table_id']);
    $partId            = intval($_REQUEST['part_id'] ?? 0);
    $machineId         = intval($_SESSION['machine_id'] ?? 0);
    $engineerId        = intval($_SESSION['engineer_id'] ?? 0);
    $actionType        = $conn->real_escape_string($_REQUEST['action_type']);
    $vacMachineTableId = intval($_REQUEST['vac_machine_table_id'] ?? 0);
    $createdOn         = date('Y-m-d H:i:s');

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

    // ============================================
    // SPECIAL HANDLING FOR "BREAK" ACTION TYPE
    // ============================================
    if ($actionType === 'break') {
        $breakDuration = isset($_REQUEST['break_duration']) ? floatval($_REQUEST['break_duration']) : 1.0;
        $breakReason   = isset($_REQUEST['break_reason']) ? mysqli_real_escape_string($conn, $_REQUEST['break_reason']) : 'Scheduled Break';

        if ($breakDuration < 0.5 || $breakDuration > 10) {
            $breakDuration = 1.0;
        }

        mysqli_autocommit($conn, false);
        $error        = false;
        $errorMessage = '';

        $priorityQuery = "SELECT id, priority FROM vac_machine_table 
                          WHERE id = $vac_machine_table_id LIMIT 1";
        $priorityResult = mysqli_query($conn, $priorityQuery);

        if ($priorityResult && mysqli_num_rows($priorityResult) > 0) {
            $priorityRow   = mysqli_fetch_assoc($priorityResult);
            $afterTaskId   = $priorityRow['id'];
            $afterPriority = $priorityRow['priority'];
            $breakPriority = $afterPriority + 1;

            $shiftQuery = "UPDATE vac_machine_table 
                           SET priority = priority + 1 
                           WHERE machine_id = $machineId 
                           AND priority >= $breakPriority";

            if (!mysqli_query($conn, $shiftQuery)) {
                $error        = true;
                $errorMessage = mysqli_error($conn);
            }

            if (!$error) {
                $taskQuery  = "SELECT end_date FROM vac_machine_table WHERE id = $afterTaskId";
                $taskResult = mysqli_query($conn, $taskQuery);

                if ($taskResult && mysqli_num_rows($taskResult) > 0) {
                    $taskRow   = mysqli_fetch_assoc($taskResult);
                    $startDate = $taskRow['end_date'];
                    $endDate   = date('Y-m-d H:i:s', strtotime($startDate) + ($breakDuration * 3600));

                    $insertBreakQuery = "INSERT INTO vac_machine_table 
                                        (machine_id, start_date, end_date, total_hours, remaing_hours,
                                         is_break, break_reason, priority, work_order_id, part_id, 
                                         quantity, product_name)
                                        VALUES ($machineId, '$startDate', '$endDate', 
                                                $breakDuration, $breakDuration, 1, '$breakReason', 
                                                $breakPriority, 0, 0, 0, 'BREAK: $breakReason')";

                    if (!mysqli_query($conn, $insertBreakQuery)) {
                        $error        = true;
                        $errorMessage = mysqli_error($conn);
                    }
                } else {
                    $error        = true;
                    $errorMessage = "Current task not found";
                }
            }
        } else {
            $error        = true;
            $errorMessage = "Task not found for scheduling break";
        }

        // Log the break action regardless
        $logSql = "INSERT INTO vac_machine_activity_log 
                   (work_order_id, part_id, machine_id, engineer_id, action_type, vac_machine_table_id, created_at) 
                   VALUES ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $vacMachineTableId, '$createdOn')";
        mysqli_query($conn, $logSql);

        if ($error) {
            mysqli_rollback($conn);
            mysqli_autocommit($conn, true);
            echo json_encode(["success" => false, "message" => "Break logged but scheduling failed: " . $errorMessage]);
        } else {
            mysqli_commit($conn);
            mysqli_autocommit($conn, true);
            recalculateMachineDatesforvac($conn, $machineId);
            echo json_encode(["success" => true, "message" => "Break scheduled and logged successfully"]);
        }

        exit;
    }

    // ============================================
    // STANDARD ACTIONS: start, pause, finish
    // ============================================
    $sql = "INSERT INTO vac_machine_activity_log 
                (work_order_id, part_id, machine_id, engineer_id, action_type, vac_machine_table_id, created_at) 
            VALUES 
                ($workOrderId, $partId, $machineId, $engineerId, '$actionType', $vacMachineTableId, '$createdOn')";

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

    if ($result) {
        if ($actionType === 'finish') {
            $sqlFinish = "UPDATE vac_machine_table 
                          SET finished = 1 
                          WHERE work_order_id = $workOrderId 
                            AND part_id = $partId";
            mysqli_query($conn, $sqlFinish);
        }

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

    exit;
}

function reduceBomChildInventory($conn, $mainProductId, $countQty, $workOrderId, $setId = 0) {
//echo "hii";
    if ($setId > 0) {

        // Get all parts in the set
        $setSql = "SELECT part_id 
                   FROM set_mangmnt_mapping
                   WHERE set_id = $setId";

        $setResult = mysqli_query($conn, $setSql);

        if (!$setResult || mysqli_num_rows($setResult) == 0) {
            return;
        }

        $childTotals = [];

        while ($setRow = mysqli_fetch_assoc($setResult)) {

            $setPartId = intval($setRow['part_id']);

            // Find BOM children of this set part
            $bomSql = "SELECT sub_part_id, quantity_required
                       FROM bom
                       WHERE main_product_id = $setPartId";

            $bomResult = mysqli_query($conn, $bomSql);

            if (!$bomResult) continue;

            while ($bomRow = mysqli_fetch_assoc($bomResult)) {

                $childId  = intval($bomRow['sub_part_id']);
                $qtyReq   = floatval($bomRow['quantity_required']);

                // Sum quantities if same child appears multiple times
                if (!isset($childTotals[$childId])) {
                    $childTotals[$childId] = 0;
                }

                $childTotals[$childId] += $qtyReq;
            }
        }

        // Now process total child quantities
        foreach ($childTotals as $childId => $sumQty) {

            $rawDeduct = $sumQty * $countQty;

            $ceiledDeduct = ($countQty >= 0)
                ? ceil($rawDeduct)
                : -ceil(abs($rawDeduct));

          

            //updateInventoryStock($conn, $childId, -$ceiledDeduct, $workOrderId, $setId);
			updateInventoryStock($conn, $childId, -$ceiledDeduct, $workOrderId, $setId);

reduceWorkOrderRawMaterial($conn, $childId, $ceiledDeduct, $workOrderId, $setId);
        }

    } else {

        // NORMAL BOM (non-set)
        $mainProductId = intval($mainProductId);

        $bomSql = "SELECT sub_part_id, quantity_required
                   FROM bom
                   WHERE main_product_id = $mainProductId";

        $bomResult = mysqli_query($conn, $bomSql);

        while ($bomRow = mysqli_fetch_assoc($bomResult)) {

            $subPartId   = intval($bomRow['sub_part_id']);
            $qtyRequired = floatval($bomRow['quantity_required']);

            $deductQty = -1 * $qtyRequired * $countQty;

           // updateInventoryStock($conn, $subPartId, $deductQty, $workOrderId, $setId);
		   updateInventoryStock($conn, $childId, -$ceiledDeduct, $workOrderId, $setId);

reduceWorkOrderRawMaterial($conn, $childId, $ceiledDeduct, $workOrderId, $setId);
        }
    }
}




function updateInventoryStock($conn, $itemId, $qtyChange, $workOrderId, $set_id) {
    $itemId    = intval($itemId);
    $qtyChange = floatval($qtyChange);

    $checkSql  = "SELECT quantity_in_stock FROM inventory WHERE item_id = $itemId";
    $result    = mysqli_query($conn, $checkSql);

    if ($result && mysqli_num_rows($result) > 0) {

        $updateSql = "UPDATE inventory
                      SET quantity_in_stock = quantity_in_stock + ($qtyChange)
                      WHERE item_id = $itemId";

        if (!mysqli_query($conn, $updateSql)) {
            echo json_encode([
                "success" => false,
                "message" => "Inventory update failed: " . mysqli_error($conn)
            ]);
            exit;
        }

    } else {

        if ($qtyChange < 0) {
            echo json_encode([
                "success" => false,
                "message" => "Cannot create inventory with negative stock (Item ID: $itemId)"
            ]);
            exit;
        }

        $insertSql = "INSERT INTO inventory (item_id, quantity_in_stock)
                      VALUES ($itemId, $qtyChange)";

        if (!mysqli_query($conn, $insertSql)) {
            echo json_encode([
                "success" => false,
                "message" => "Inventory insert failed: " . mysqli_error($conn)
            ]);
            exit;
        }
    }
}

function reduceWorkOrderRawMaterial($conn, $itemId, $qtyUsed, $workOrderId, $setId = 0) {
    $itemId = intval($itemId);
    $qtyUsed = floatval($qtyUsed);
    $workOrderId = intval($workOrderId);
    $setId = intval($setId);

    $sql = "UPDATE work_order_raw_matrial
            SET quantity = quantity - ($qtyUsed)
            WHERE work_order_id = $workOrderId
            AND product_id = $itemId
            AND set_id = $setId";

    mysqli_query($conn, $sql);
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_count_vac') {

$workOrderId = intval($_REQUEST['work_order_id']);
$machineId  = intval($_SESSION['machine_id'] ?? 0);
$engineerId = intval($_SESSION['engineer_id'] ?? 0);
$type = $conn->real_escape_string($_REQUEST['type']); 
$quantity = intval($_REQUEST['quantity'] ?? 1);

$partIds = isset($_REQUEST['part_ids']) ? $conn->real_escape_string($_REQUEST['part_ids']) : '';
$nok_q_scrap_part_ids_part_ids = isset($_REQUEST['nok_q_scrap_part_ids_part_ids']) ? $conn->real_escape_string($_REQUEST['nok_q_scrap_part_ids_part_ids']) : '';
$reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;

$partId = isset($_REQUEST['part_id']) ? intval($_REQUEST['part_id']) : 0;
$vacMachineTableId = intval($_REQUEST['vac_machine_table_id'] ?? 0);
$createdOn = date('Y-m-d H:i:s');
$currentDate = date('Y-m-d'); // Current date for tracking

$set_id = intval($_REQUEST['set_id'] ?? 0);

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

// Helper function to update date_wise_quantity field
function updateDateWiseQuantity($existingDateWise, $date, $quantityChange) {
    $dateArray = [];
    
    // Parse existing date-wise data
    if (!empty($existingDateWise)) {
        $entries = explode(',', $existingDateWise);
        foreach ($entries as $entry) {
            if (strpos($entry, ':') !== false) {
                list($d, $q) = explode(':', $entry);
                $dateArray[$d] = floatval($q);
            }
        }
    }
    
    // Update quantity for current date
    if (isset($dateArray[$date])) {
        $dateArray[$date] += $quantityChange;
    } else {
        $dateArray[$date] = $quantityChange;
    }
    
    // Remove dates with zero or negative quantities
    $dateArray = array_filter($dateArray, function($qty) {
        return $qty > 0;
    });
    
    // Convert back to comma-separated string
    $result = [];
    foreach ($dateArray as $d => $q) {
        $result[] = "$d:$q";
    }
    
    return implode(',', $result);
}
$checkFirstOff = "SELECT id FROM vac_first_off_signoff
                  WHERE work_order_id = $workOrderId
                  AND vac_machine_table_id = $vacMachineTableId
                  LIMIT 1";

$firstOffRes = mysqli_query($conn, $checkFirstOff);

if ($type === 'ok') {
    if ($set_id > 0) {
        $mapSql = "SELECT part_id, ratio FROM set_mangmnt_mapping WHERE set_id = $set_id";
        $mapResult = $conn->query($mapSql);

        if ($mapResult->num_rows > 0) {
            while ($map = $mapResult->fetch_assoc()) {
                $mappedPartId = intval($map['part_id']);
                $mapQty = floatval($map['ratio']);

                // Store in DIFFERENT TABLE for set mappings
                $checkSetSql = "
                    SELECT id, quantity, date_wise_quantity 
                    FROM vac_set_part_count_log 
                    WHERE work_order_id = $workOrderId 
                    AND machine_id = $machineId 
                    AND engineer_id = $engineerId
                    AND partIds = $mappedPartId 
					AND vac_machine_table_id = $vacMachineTableId 
                    AND type = '$type'
                ";

                $checkSetResult = $conn->query($checkSetSql);

                if ($checkSetResult->num_rows > 0) {
                    // UPDATE in vac_set_part_count_log
                    $row = $checkSetResult->fetch_assoc();
                    $existingId = $row['id'];
                    
                    $actualChange = $mapQty * $quantity;
                    
                    $newQuantity = $row['quantity'] + $actualChange;

                    if ($newQuantity < 0) {
                        echo json_encode(["success" => false, "message" => "Can't Decrease"]);
                        exit;
                    }

                    $newDateWiseQty = updateDateWiseQuantity($row['date_wise_quantity'], $currentDate, $actualChange);

                    $updateSetSql = "
                        UPDATE vac_set_part_count_log 
                        SET quantity = $newQuantity, 
                            date_wise_quantity = '$newDateWiseQty'
                        WHERE id = $existingId
                    ";

                    if (!mysqli_query($conn, $updateSetSql)) {
                        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
                        exit;
                    }

                } else {
                    // INSERT into vac_set_part_count_log
                    $actualChange = $mapQty * $quantity;
                    
                    if ($actualChange < 0) {
                        echo json_encode(["success" => false, "message" => "Cannot decrement non-existent record for part ID: $mappedPartId"]);
                        exit;
                    }

                    $initialDateWiseQty = "$currentDate:$actualChange";

                    $insertSetSql = "
                        INSERT INTO vac_set_part_count_log 
                        (work_order_id, machine_id, part_id, partIds, engineer_id, setId, type, quantity, date_wise_quantity, vac_machine_table_id, created_at) 
                        VALUES ($workOrderId, $machineId, $partId, $mappedPartId, $engineerId, $set_id, '$type', $actualChange, '$initialDateWiseQty', $vacMachineTableId, '$createdOn')
                    ";

                    if (!mysqli_query($conn, $insertSetSql)) {
                        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
                        exit;
                    }
                }
                
                // Update inventory for mapped part
               // updateInventoryStock($conn, $mappedPartId, $actualChange);
				
            }
        }
        
        $checkSql = "
            SELECT id, quantity, date_wise_quantity 
            FROM vac_part_count_log 
            WHERE work_order_id = $workOrderId 
            AND machine_id = $machineId 
            AND engineer_id = $engineerId
            AND part_id = $partId 
			AND vac_machine_table_id = $vacMachineTableId 
            AND type = '$type'
        ";
        
        $checkResult = $conn->query($checkSql);
        
        if ($checkResult->num_rows > 0) {
            // UPDATE vac_part_count_log
            $row = $checkResult->fetch_assoc();
            $existingId = $row['id'];
            
            $newQuantity = $row['quantity'] + $quantity;
            
            if ($newQuantity < 0) {
                echo json_encode(["success" => false, "message" => "Count cannot be negative for set ID: $set_id"]);
                exit;
            }
            
            $newDateWiseQty = updateDateWiseQuantity($row['date_wise_quantity'], $currentDate, $quantity);
            
            $updateSql = "
                UPDATE vac_part_count_log 
                SET quantity = $newQuantity,
                    date_wise_quantity = '$newDateWiseQty'
                WHERE id = $existingId
            ";
            
            if (!mysqli_query($conn, $updateSql)) {
                echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
                exit;
            }
            
        } else {
            // INSERT into vac_part_count_log
            if ($quantity < 0) {
                echo json_encode(["success" => false, "message" => "Cannot decrement non-existent set record"]);
                exit;
            }
            
            $initialDateWiseQty = "$currentDate:$quantity";
            
            $insertSql = "
                INSERT INTO vac_part_count_log 
                (work_order_id, machine_id, part_id, partIds, engineer_id, setId, type, quantity, date_wise_quantity, vac_machine_table_id, created_at) 
                VALUES ($workOrderId, $machineId, $partId, $mappedPartId, $engineerId, $set_id, '$type', $quantity, '$initialDateWiseQty', $vacMachineTableId, '$createdOn')
            ";
            
            if (!mysqli_query($conn, $insertSql)) {
                echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
                exit;
            }
        }
		
		
		
		
		
		
		
		updateInventoryStock($conn, $mappedPartId, $actualChange, $workOrderId, $set_id);

                    // *** Deduct BOM children for this mapped part ***
                    reduceBomChildInventory($conn, $mappedPartId, $quantity * $mapQty, $workOrderId, $set_id);
	
        
        echo json_encode(["success" => true]);
        exit;
    }
    


    /* ============================================
            2. NORMAL OK INSERT/UPDATE
    ============================================= */
    $checkSql = "
        SELECT id, quantity, date_wise_quantity 
        FROM vac_part_count_log 
        WHERE work_order_id = $workOrderId 
        AND machine_id = $machineId 
		AND engineer_id = $engineerId
        AND part_id = $partId 
		AND vac_machine_table_id = $vacMachineTableId 
        AND type = '$type'
    ";

    $checkResult = $conn->query($checkSql);

    if ($checkResult->num_rows > 0) {

        // UPDATE
        $row = $checkResult->fetch_assoc();
        $existingId = $row['id'];

        $newQuantity = $row['quantity'] + $quantity;

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

        // Update date-wise quantity
        $newDateWiseQty = updateDateWiseQuantity($row['date_wise_quantity'], $currentDate, $quantity);

        $updateSql = "
            UPDATE vac_part_count_log 
            SET quantity = $newQuantity,
                date_wise_quantity = '$newDateWiseQty'
            WHERE work_order_id = $workOrderId
              AND part_id = $partId
			  AND vac_machine_table_id = $vacMachineTableId 
              AND type = '$type'
        ";
         // Update inventory
//updateInventoryStock($conn, $partId, $quantity);
 updateInventoryStock($conn, $partId, $quantity, $workOrderId, $set_id);
        reduceBomChildInventory($conn, $partId, $quantity, $workOrderId, $set_id);

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

    } else {

        // INSERT
        if ($quantity < 0) {
            echo json_encode(["success" => false, "message" => "Cannot decrement non-existent record"]);
            exit;
        }

        // Initialize date-wise quantity for new record
        $initialDateWiseQty = "$currentDate:$quantity";

        $insertSql = "
            INSERT INTO vac_part_count_log 
            (work_order_id, machine_id, part_id, partIds, engineer_id, type, quantity, date_wise_quantity, vac_machine_table_id, created_at) 
            VALUES ($workOrderId, $machineId, $partId, $partId, $engineerId, '$type', $quantity, '$initialDateWiseQty', $vacMachineTableId, '$createdOn')
        ";
		// ✅ Update inventory
//updateInventoryStock($conn, $partId, $quantity);
updateInventoryStock($conn, $singlePartId, $qty, $workOrderId, $set_id);


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


    // For NOK and Quarantine
    else {
        // For positive quantities (increment) - requires part selection and reason
         if ($quantity > 0) {

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

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

        mysqli_autocommit($conn, false);
        $success = true;

        // --------------------------------------------
        // 1️⃣ INSERT MAIN NOK / QUARANTINE ENTRY
        // --------------------------------------------
        $initialDateWiseQty = "$currentDate:$quantity";

        $insertMain = "INSERT INTO vac_part_count_log 
                (work_order_id, machine_id, part_id, engineer_id, type, setId, partIds, reason_id, quantity, date_wise_quantity, vac_machine_table_id, created_at) 
                VALUES ($workOrderId, $machineId, $partId, $engineerId, '$type', '$set_id', '$partIds', $reasonId, $quantity, '$initialDateWiseQty', $vacMachineTableId, '$createdOn')";

        if (!mysqli_query($conn, $insertMain)) {
            mysqli_rollback($conn);
            echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
            exit;
        }

        $vacPartCountLogId = mysqli_insert_id($conn);

        // --------------------------------------------
        // PREPARE SELECTED & UNSELECTED ARRAYS
        // --------------------------------------------
        $selectedParts = array_filter(array_map('trim', explode(',', $nok_q_scrap_part_ids_part_ids)));

        $allParts = [];

        if ($set_id > 0) {
            $mapSql = "SELECT part_id FROM set_mangmnt_mapping WHERE set_id = $set_id";
            $mapRes = mysqli_query($conn, $mapSql);
            while ($row = mysqli_fetch_assoc($mapRes)) {
                $allParts[] = $row['part_id'];
            }
        } else {
            $allParts[] = $partId;
        }

        $unselectedParts = array_diff($allParts, $selectedParts);

        // --------------------------------------------
        // 3️⃣ HANDLE SELECTED PARTS
        // --------------------------------------------
        foreach ($selectedParts as $singlePartId) {

            $singlePartId = intval($singlePartId);
            if ($singlePartId <= 0) continue;

            $qty = 1;

            if ($set_id > 0) {
                $ratioSql = "SELECT ratio FROM set_mangmnt_mapping 
                             WHERE set_id = $set_id AND part_id = $singlePartId LIMIT 1";
                $ratioRes = mysqli_query($conn, $ratioSql);
                if ($ratioRes && mysqli_num_rows($ratioRes) > 0) {
                    $ratioRow = mysqli_fetch_assoc($ratioRes);
                    $qty = floatval($ratioRow['ratio']);
                }
            }

            $sql = "INSERT INTO vac_selected_ok_parts
                    (quantity, vac_machine_table_id, vac_part_count_log_id, created_at)
                    VALUES
                    ($qty, $vacMachineTableId, $vacPartCountLogId, '$createdOn')";

            if (!mysqli_query($conn, $sql)) {
                $success = false;
                break;
            }

           // updateInventoryStock($conn, $singlePartId, $qty);
			updateInventoryStock($conn, $singlePartId, $qty, $workOrderId, $set_id);
        }

        // --------------------------------------------
        // HANDLE UNSELECTED PARTS
        // --------------------------------------------
        foreach ($unselectedParts as $singlePartId) {

            $singlePartId = intval($singlePartId);
            if ($singlePartId <= 0) continue;

            $qty = 1;

            if ($set_id > 0) {
                $ratioSql = "SELECT ratio FROM set_mangmnt_mapping 
                             WHERE set_id = $set_id AND part_id = $singlePartId LIMIT 1";
                $ratioRes = mysqli_query($conn, $ratioSql);
                if ($ratioRes && mysqli_num_rows($ratioRes) > 0) {
                    $ratioRow = mysqli_fetch_assoc($ratioRes);
                    $qty = floatval($ratioRow['ratio']);
                }
            }

            $sql = "INSERT INTO vac_unselected_ok_parts
                    (quantity, vac_machine_table_id, vac_part_count_log_id, created_at)
                    VALUES
                    ($qty, $vacMachineTableId, $vacPartCountLogId, '$createdOn')";

            if (!mysqli_query($conn, $sql)) {
                $success = false;
                break;
            }

           // updateInventoryStock($conn, $singlePartId, $qty);
			updateInventoryStock($conn, $singlePartId, $qty, $workOrderId, $set_id);
        }

        // --------------------------------------------
        // COMMIT OR ROLLBACK
        // --------------------------------------------
        if ($success) {
            mysqli_commit($conn);
            echo json_encode(["success"=>true]);
        } else {
            mysqli_rollback($conn);
            echo json_encode(["success"=>false,"message"=>mysqli_error($conn)]);
        }

        mysqli_autocommit($conn, true);
        exit;
    }
        // For negative quantities (decrement) - find MOST RECENT record and decrement it
else if ($quantity < 0) {

    mysqli_autocommit($conn, false);
    $success = true;

    $checkSql = "SELECT id, quantity, date_wise_quantity 
                 FROM vac_part_count_log 
                 WHERE work_order_id = $workOrderId 
                 AND machine_id = $machineId 
                 AND part_id = $partId
                 AND vac_machine_table_id = $vacMachineTableId 				 
                 AND type = '$type'
                 ORDER BY id DESC 
                 LIMIT 1";

    $checkResult = $conn->query($checkSql);

    if ($checkResult->num_rows > 0) {

        $row = $checkResult->fetch_assoc();
        $existingId = $row['id'];
        $currentQuantity = $row['quantity'];

        $newQuantity = $currentQuantity + $quantity;

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

        // If quantity becomes ZERO → delete everything
        if ($newQuantity == 0) {

            // Delete selected parts
            $del1 = "DELETE FROM vac_selected_ok_parts 
                     WHERE vac_part_count_log_id = $existingId";
            if (!mysqli_query($conn, $del1)) {
                $success = false;
            }

            // Delete unselected parts
            $del2 = "DELETE FROM vac_unselected_ok_parts 
                     WHERE vac_part_count_log_id = $existingId";
            if (!mysqli_query($conn, $del2)) {
                $success = false;
            }

            // Delete main log entry
            $delMain = "DELETE FROM vac_part_count_log 
                        WHERE id = $existingId";
            if (!mysqli_query($conn, $delMain)) {
                $success = false;
            }

        } else {

            // Update date-wise quantity
            $newDateWiseQty = updateDateWiseQuantity(
                $row['date_wise_quantity'],
                $currentDate,
                $quantity
            );

            $updateSql = "UPDATE vac_part_count_log 
                          SET quantity = $newQuantity,
                              date_wise_quantity = '$newDateWiseQty'
                          WHERE id = $existingId";

            if (!mysqli_query($conn, $updateSql)) {
                $success = false;
            }
        }

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

        mysqli_autocommit($conn, true);
    } else {
        echo json_encode(["success"=>false,"message"=>"No recent $type entry found to decrement"]);
    }

    exit;
}
    }
    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start_changeover') {

    $machineId         = intval($_REQUEST['machine_id']);
    $clockNo           = mysqli_real_escape_string($conn, $_REQUEST['clock_no'] ?? '');
    $workOrderTableId  = intval($_REQUEST['work_order_table_id'] ?? 0);
    $startTime         = date('Y-m-d H:i:s');

    if (empty($clockNo)) {
        echo json_encode(["success" => false, "message" => "Clock number required"]);
        exit;
    }

    $checkUser = "SELECT id FROM admin WHERE clock_no = '$clockNo' LIMIT 1";
    $userRes   = mysqli_query($conn, $checkUser);
    if (!$userRes || mysqli_num_rows($userRes) == 0) {
        echo json_encode(["success" => false, "message" => "Invalid Clock Number"]);
        exit;
    }
    $employeeId = intval(mysqli_fetch_assoc($userRes)['id']);

    // Use the specific row passed from the front end
    if ($workOrderTableId <= 0) {
        echo json_encode(["success" => false, "message" => "No work order selected"]);
        exit;
    }

    $sql = "INSERT INTO vac_machine_changeover
            (machine_id, employee_id, work_order_table_id, start_time, status)
            VALUES ($machineId, $employeeId, $workOrderTableId, '$startTime', 'running')";

    if (mysqli_query($conn, $sql)) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'end_changeover') {

    $machineId = intval($_REQUEST['machine_id']);
    $endTime = date('Y-m-d H:i:s');

    $sql = "SELECT id, start_time 
            FROM vac_machine_changeover
            WHERE machine_id = $machineId 
            AND status = 'running'
            ORDER BY id DESC LIMIT 1";

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

    if ($result && mysqli_num_rows($result) > 0) {

        $row = mysqli_fetch_assoc($result);
        $startTime = strtotime($row['start_time']);
        $duration = time() - $startTime;

        $update = "UPDATE vac_machine_changeover
                   SET end_time = '$endTime',
                       duration_seconds = $duration,
                       status = 'completed'
                   WHERE id = {$row['id']}";

        mysqli_query($conn, $update);

        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false]);
    }

    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'first_off_signoff') {

    $workOrderId = intval($_REQUEST['work_order_id']);
    $partId = intval($_REQUEST['part_id']);
    $machineId = intval($_REQUEST['machine_id']);
    $vacMachineTableId = intval($_REQUEST['vac_machine_table_id']);
    $signedAt = date('Y-m-d H:i:s');
    $qcComment = mysqli_real_escape_string($conn, $_REQUEST['qc_comment'] ?? '');
    $qcClockNo = mysqli_real_escape_string($conn, $_REQUEST['qc_clock_no'] ?? '');

    if (empty($qcClockNo)) {
        echo json_encode(["success"=>false, "message"=>"Clock number required"]);
        exit;
    }

    $checkUser = "SELECT id FROM admin WHERE clock_no = '$qcClockNo' LIMIT 1";
    $userRes = mysqli_query($conn, $checkUser);

    if (!$userRes || mysqli_num_rows($userRes) == 0) {
        echo json_encode(["success"=>false, "message"=>"Invalid Clock Number"]);
        exit;
    }

    $userRow = mysqli_fetch_assoc($userRes);
    $qcEmployeeId = intval($userRow['id']);

    $check = "SELECT id FROM vac_first_off_signoff
              WHERE work_order_id = $workOrderId
              AND vac_machine_table_id = $vacMachineTableId
              LIMIT 1";

    $res = mysqli_query($conn, $check);

   /* if ($res && mysqli_num_rows($res) > 0) {
        echo json_encode(["success"=>false, "message"=>"Already signed off"]);
        exit;
    }*/

    $insert = "INSERT INTO vac_first_off_signoff
          (work_order_id, part_id, vac_machine_table_id, machine_id, qc_employee_id, qc_comment, signed_at)
          VALUES
          ($workOrderId, $partId, $vacMachineTableId, $machineId, $qcEmployeeId, '$qcComment', '$signedAt')";

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

    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'end_breakdown_vac') {

    $machineId  = intval($_SESSION['machine_id'] ?? 0);
    $engineerId = intval($_SESSION['engineer_id'] ?? 0);
    $createdOn  = date('Y-m-d H:i:s');

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

    // 👉 Get LAST active breakdown
    $getLast = "SELECT * FROM vac_machine_breakdown_log
                WHERE machine_id = $machineId
                AND status = 'active'
                ORDER BY id DESC LIMIT 1";

    $res = mysqli_query($conn, $getLast);

    if (!$res || mysqli_num_rows($res) == 0) {
        echo json_encode(["success" => false, "message" => "No active breakdown found"]);
        exit;
    }

    $row = mysqli_fetch_assoc($res);

    // 👉 Insert NEW record = breakdown_over
    $insert = "INSERT INTO vac_machine_breakdown_log
        (work_order_id, part_id, machine_id, engineer_id, vac_machine_table_id,
         breakdown_reason, breakdown_duration, ok_count_at_breakdown,
         remaining_quantity, status, created_at)
    VALUES (
        {$row['work_order_id']},
        {$row['part_id']},
        $machineId,
        $engineerId,
        {$row['vac_machine_table_id']},
        {$row['breakdown_reason']},
        {$row['breakdown_duration']},
        {$row['ok_count_at_breakdown']},
        {$row['remaining_quantity']},
        'completed',
        '$createdOn'
    )";

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

    exit;
}

?>

