<?php
include("../../../include/startup.php"); 
header('Content-Type: application/json');
// ========================================
// GET CURRENT TASK PRIORITY FOR VAC MACHINE
// ========================================
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_current_task_priority_vac') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $machineId = intval($_REQUEST['machine_id']);
    $partId = intval($_REQUEST['part_id']);
    
    $query = "SELECT id, priority FROM vac_machine_table 
              WHERE work_order_id = $workOrderId 
              AND machine_id = $machineId 
              AND part_id = $partId 
              LIMIT 1";
    
    $result = mysqli_query($conn, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        echo json_encode([
            'success' => true,
            'task_id' => $row['id'],
            'priority' => $row['priority']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Task not found'
        ]);
    }
    exit;
}

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

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

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

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

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

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

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

    foreach ($tasks as $task) {
        $hoursRemaining = floatval($task['hours_to_schedule']);
        $dateHoursMap = [];
        $taskStartTime = null;
        $taskEndTime = null;
        $firstShiftUsed = null;

        while ($hoursRemaining > 0) {
            $currentDate = date('Y-m-d', $currentDateTime);
            $dayOfWeek = date('w', $currentDateTime);

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

            foreach ($shiftsByDay[$dayOfWeek] as $shift) {
                $shiftStart = strtotime($currentDate . ' ' . $shift['start_time']);
                $shiftEnd   = strtotime($currentDate . ' ' . $shift['end_time']);
                $shiftName  = $shift['shift_name'];

                if ($shiftEnd <= $currentDateTime) continue;

                $actualStart = max($currentDateTime, $shiftStart);
                $availableSeconds = max(0, $shiftEnd - $actualStart);
                $availableHours = $availableSeconds / 3600;

                if ($availableHours <= 0) continue;

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

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

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

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

                $currentDateTime = $taskEndTime;

                if ($hoursRemaining <= 0) break;
            }

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

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

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

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

        mysqli_query($conn, $query);
    }
}









////////////////////////////////////////////// for pu ends /////////////////////////////////////
// Replace your existing log_action_vac with this enhanced version

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

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

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


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']) : '';
$reasonId = isset($_REQUEST['reason_id']) ? intval($_REQUEST['reason_id']) : null;

$partId = isset($_REQUEST['part_id']) ? intval($_REQUEST['part_id']) : 0;
$createdOn = date('Y-m-d H:i:s');
$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);
}

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

                // Check rows for each mapped part
                $checkSql = "
                    SELECT id, quantity, final_quantity, date_wise_quantity 
                    FROM vac_part_count_log 
                    WHERE work_order_id = $workOrderId 
                    AND machine_id = $machineId 
                    AND partIds = $mappedPartId 
                    AND engineer_id = $engineerId 
                    AND type = '$type'
                ";

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

                if ($checkResult->num_rows > 0) {
                    // UPDATE
                    $row = $checkResult->fetch_assoc();
                    $existingId = $row['id'];
                    
                    // Calculate actual change based on quantity direction (increment/decrement)
                    $actualChange = $mapQty * $quantity; // This applies ratio AND direction
                    $setChange = $quantity; // For final_quantity (set count)
                    
                    $newQuantity = $row['quantity'] + $actualChange;
                    $newSetQuantity = $row['final_quantity'] + $setChange;

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

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

                    $updateSql = "
                        UPDATE vac_part_count_log 
                        SET quantity = $newQuantity, 
                            final_quantity = $newSetQuantity,
                            date_wise_quantity = '$newDateWiseQty'
                        WHERE id = $existingId
                    ";
                    // ✅ Update inventory for mapped part
updateInventoryStock($conn, $mappedPartId, $actualChange);

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

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

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

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

                    if (!mysqli_query($conn, $insertSql)) {
                        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
                        exit;
                    }
					// ✅ Update inventory for mapped part
updateInventoryStock($conn, $mappedPartId, $actualChange);

                }
            }

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


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

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

    if ($checkResult->num_rows > 0) {

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

        $newQuantity = $row['quantity'] + $quantity;
        $newSetQuantity = $row['final_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,
                final_quantity = $newSetQuantity,
                date_wise_quantity = '$newDateWiseQty'
            WHERE work_order_id = $workOrderId
              AND part_id = $partId 
              AND type = '$type'
        ";
         // ✅ Update inventory
updateInventoryStock($conn, $partId, $quantity);

        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, final_quantity, date_wise_quantity, created_at) 
            VALUES ($workOrderId, $machineId, $partId, $partId, $engineerId, '$type', $quantity, $quantity, '$initialDateWiseQty', '$createdOn')
        ";
		// ✅ Update inventory
updateInventoryStock($conn, $partId, $quantity);


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

            // Initialize date-wise quantity for NOK/Quarantine
            $initialDateWiseQty = "$currentDate:$quantity";

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


?>

