<?php
include("../../../include/startup.php"); 
// Add these two new actions to your ajax_actions.php file

// Action 1: Get current task priority
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_current_task_priority') {
    $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;
}

// Action 2: Insert schedule break after current work order
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert_schedule_break') {
    $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;
    
    // 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));
            
            // Insert break as a special task
            $insertQuery = "INSERT INTO vac_machine_table 
                           (machine_id, start_date, end_date, total_hours, 
                            is_break, break_reason, priority, work_order_id, part_id, quantity, product_name)
                           VALUES ($machineId, '$startDate', '$endDate', 
                                   $duration, 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 ?? 'Unknown error']);
    } else {
        mysqli_commit($conn);
        
        // Recalculate all dates for this machine
        recalculateMachineDatesforassmpu($conn, $machineId);
        
        echo json_encode(['status' => 'success', 'message' => 'Break scheduled successfully']);
    }
    
    mysqli_autocommit($conn, true);
    exit;
}

// Note: The recalculateMachineDatesforassmpu() function should already exist in your code
// Make sure it's available in this file or included properly
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_action_cnc') {
    $workOrderId = intval($_REQUEST['work_order_id']);
    $tableId     = intval($_REQUEST['tableId']);
    $partId      = intval($_REQUEST['part_id']);
    $machineId   = intval($_REQUEST['machine_id']);
    $engineerId  = intval($_SESSION['engineer_id'] ?? 0);
    $actionType  = $conn->real_escape_string($_REQUEST['action_type']);
    $createdOn   = date('Y-m-d H:i:s'); // ✅ Added timestamp here
    // ✅ Handle Scheduler Break logging (start / stop)
    if (in_array($actionType, ['scheduler_break_start', 'scheduler_break_stop'])) {
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        if (mysqli_query($conn, $sql)) {
            echo json_encode(["success" => true, "message" => "Scheduler break logged successfully"]);
        } else {
            echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
        }
        exit;
    }
    // ✅ Normal action logging (start / pause / finish / breakdown)
    $sql = "INSERT INTO machine_activity_log 
            (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
            VALUES ($workOrderId, $partId, $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
    if ($actionType === 'finish') {
        $sqlFinish = "
            UPDATE cnc_machine_table 
            SET finished = 1 
            WHERE work_order_id = $workOrderId 
              AND part_id = $partId
        ";
        mysqli_query($conn, $sqlFinish);
    }
    if (mysqli_query($conn, $sql)) {
        echo json_encode(["success" => true]);
    } else {
        echo json_encode(["success" => false, "message" => mysqli_error($conn)]);
    }
    exit;
}
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'log_bulk_action_cnc') {
    include "config.php";
    session_start();
    
    $actionType = mysqli_real_escape_string($conn, $_POST['action_type']);
    $workOrders = json_decode($_POST['work_orders'], true);
    $engineerId = intval($_SESSION['user_id']);
    $createdOn  = date('Y-m-d H:i:s');
    
    $successCount = 0;
    $errorCount = 0;
    $skippedCount = 0;
    
    if (!is_array($workOrders) || empty($workOrders)) {
        echo json_encode(['success' => false, 'message' => 'No work orders provided.']);
        exit;
    }
    
    foreach ($workOrders as $order) {
        $workOrderId = intval($order['workOrderId'] ?? 0);
        $partId      = mysqli_real_escape_string($conn, $order['partId'] ?? '');
        $machineId   = intval($order['machineId'] ?? 0);
        $tableId     = intval($order['tableId'] ?? 0);
        
        if (!$workOrderId || !$machineId || !$engineerId || !$actionType) {
            $errorCount++;
            continue;
        }
        
        // ✅ Check current state before inserting
        $checkSql = "SELECT action_type 
                     FROM machine_activity_log 
                     WHERE machine_id = $machineId 
                     AND table_id = $tableId 
                     ORDER BY created_at DESC 
                     LIMIT 1";
        
        $checkResult = mysqli_query($conn, $checkSql);
        
        if ($checkResult && mysqli_num_rows($checkResult) > 0) {
            $currentState = mysqli_fetch_assoc($checkResult)['action_type'];
            
            // ✅ Skip if already in desired state
            // If trying to start but already started, skip
            // If trying to pause but already paused, skip
            if (($actionType === 'start' && $currentState === 'start') || 
                ($actionType === 'pause' && $currentState === 'pause')) {
                $skippedCount++;
                continue; // Skip this machine
            }
        }
        
        // ✅ Insert only if state needs to change
        $sql = "INSERT INTO machine_activity_log 
                (work_order_id, part_id, machine_id, table_id, engineer_id, action_type, created_at) 
                VALUES ($workOrderId, '$partId', $machineId, $tableId, $engineerId, '$actionType', '$createdOn')";
        
        if (mysqli_query($conn, $sql)) {
            // ✅ Optional: Mark as finished if action_type = 'finish'
            if ($actionType === 'finish') {
                $updateSql = "UPDATE cnc_machine_table 
                             SET finished = 1 
                             WHERE work_order_id = $workOrderId 
                             AND part_id = '$partId'";
                mysqli_query($conn, $updateSql);
            }
            $successCount++;
        } else {
            $errorCount++;
        }
    }
    
    // ✅ Better response message
    $message = "Processed: $successCount changed";
    if ($skippedCount > 0) {
        $message .= ", $skippedCount already in desired state";
    }
    if ($errorCount > 0) {
        $message .= ", $errorCount failed";
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'changed' => $successCount,
        'skipped' => $skippedCount,
        'errors' => $errorCount
    ]);
    exit;
}

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

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

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

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

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

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

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

    // NOK / Quarantine
    else {

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

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

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

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

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

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

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

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

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

    exit;
}

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

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

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

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

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

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

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

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

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

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

    // NOK / Quarantine
    else {

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

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

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

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

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

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

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

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

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

    exit;
}

////////////////////////////////////////////// for pu ends /////////////////////////////////////
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;
    }

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

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

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

    } else {

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

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

    if ($result) {

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

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

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

    exit;
}

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

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

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

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

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



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

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

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

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

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

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

    } else {

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

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

    if ($result) {

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

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

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

    exit;
}

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

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

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

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

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

