<?php

namespace App\Http\Controllers;

use App\Models\CharacteristicApproverMaster;
use App\Models\CharacteristicValue;
use App\Models\ClassCharacteristic;
use App\Models\Item;
use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\ProductCharacteristicsMaster;
use App\Models\RequestCharacteristic;
use App\Models\StickerMaster;
use App\Models\TempClassCharacteristic;
use App\Models\User;
use App\Models\WindedSerialValidationError;
use App\Models\WorkGroupMaster;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use Schema;
use Str;

class CharacteristicsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    public function getCharacteristicsMaster(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $plantCode = $request->header('plant-code');

        $itemCode = $request->header('item-code');

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        } elseif ($itemCode == null || $itemCode == '' || ! $itemCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $item = Item::where('code', $itemCode)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
            ], 404);
        }

        $itemId = $item->id;

        // $characteristics = ProductCharacteristicsMaster::where('plant_id', $plantId)
        // ->where('item_id', $itemId)
        // ->first([
        //     'line_id',
        //     'machine_id',
        //     'characteristics_type',
        //     'name',
        //     'inspection_type',
        //     'upper',
        //     'lower',
        //     'middle'
        // ]);

        $characteristics = ProductCharacteristicsMaster::where('item_id', $itemId)->where('plant_id', $plantId)
            ->get([
                'line_id',
                'machine_id',
                'name',
                'characteristics_type',
                'inspection_type',
                'lower',
                'middle',
                'upper',
            ]);

        if ($characteristics->count() == 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'message' => "No data found for the plant code '{$plantCode}' and item code '{$itemCode}'!",
            ], 404);
        }

        $items = [];

        // $response = $characteristics->toArray();

        // $line = Line::find($characteristics->line_id);
        // $lineName = $line ? $line->name : null;

        // // Remove line_id from response
        // $machineId = $characteristics->machine_id;
        // unset($response['line_id']);
        // unset($response['machine_id']);

        // $workCenter = Machine::where('id', $machineId)
        //     ->where('plant_id', $plantId)
        //     ->where('line_id', $characteristics->line_id)
        //     ->value('work_center');

        // $workGroupMasterId = Machine::where('line_id', $characteristics->line_id)
        //     ->where('plant_id', $plantId)
        //     ->value('work_group_master_id');

        // $groupWorkCenter = null;
        // if ($workGroupMasterId) {
        //     $groupWorkCenter = WorkGroupMaster::where('id', $workGroupMasterId)
        //         ->value('name');
        // }

        // $response  = [
        //     'line_name' => $lineName,
        //     'group_work_center' => $groupWorkCenter,
        //     'work_center' => $workCenter,
        //     'characteristics_type' => $characteristics->characteristics_type,
        //     'name' => $characteristics->name,
        //     'inspection_type' => $characteristics->inspection_type,
        //     // 'upper' => $characteristics->upper ?? 0,
        //     // 'lower' => $characteristics->lower ?? 0,
        //     // 'middle' => $characteristics->middle ?? 0,
        //     'lower' => (string)($characteristics->lower ?? 0),
        //     'middle' => (string)($characteristics->middle ?? 0),
        //     'upper' => (string)($characteristics->upper ?? 0),
        // ];

        // return response()->json($response);

        foreach ($characteristics as $char) {

            $line = Line::find($char->line_id);
            $lineName = $line ? $line->name : null;

            $workCenter = Machine::where('id', $char->machine_id)->where('line_id', $char->line_id)->where('plant_id', $plantId)->value('work_center');

            $workGroupMasterId = ProductCharacteristicsMaster::where('line_id', $char->line_id)->where('plant_id', $plantId)->value('work_group_master_id');

            $groupWorkCenter = null;
            if ($workGroupMasterId) {
                $groupWorkCenter = WorkGroupMaster::where('id', $workGroupMasterId)->value('name');
            }

            $items[] = [
                'line_name' => $lineName,
                'group_work_center' => $groupWorkCenter,
                'work_center' => $workCenter,
                'characteristics_type' => $char->characteristics_type,
                'name' => $char->name,
                'inspection_type' => $char->inspection_type,
                'lower' => (string) ($char->lower ?? 0),
                'middle' => (string) ($char->middle ?? 0),
                'upper' => (string) ($char->upper ?? 0),
            ];
        }

        return response()->json([
            'items' => $items,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    // public function store(Request $request)
    // {
    //     //
    // }

    // Route::post('laser/store-test-datas', [CharacteristicsController::class, 'test'])
    public function storeLaserStatus(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        $data = $request->all();

        $plantCode = $data['plant_code'] ?? '';
        $workCenter = $data['work_center'] ?? '';
        $jobNo = $data['aufnr'] ?? '';
        $serialNumber = $data['gernr'] ?? '';
        $itemCode = $data['item_code'] ?? '';
        $modelType = $data['model_type'] ?? '';
        $expectedTime = $data['expected_time'] ?? 0;
        $markedStatus = (Str::contains($data['marked_status'], 'marked', ignoreCase: true)) ? 'Marked' : 'Stopped';
        $characteristics = $data['characteristics'];

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        if ($modelType == null || $modelType == '' || ! $modelType) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Marked model type can't be empty!",
            ], 404);
        } elseif ($modelType != 'MOTOR' && $modelType != 'PUMP' && $modelType != 'NAME_PLATE') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' doesn't have valid marked model type to proceed!",
            ], 404);
        }

        if ($expectedTime == null || $expectedTime == '' || $expectedTime == '0' || ! $expectedTime) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Expected time can't be empty or zero!",
            ], 404);
        } elseif (! is_numeric($expectedTime)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid expected time found!',
            ], 404);
        } else {
            $expectedTime = (float) $expectedTime;
        }

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            if (Str::length($jobNo) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should not begin with '0'!",
                ], 404);
            }
        }

        if ($serialNumber == null || $serialNumber == '' || ! $serialNumber) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number can't be empty!",
            ], 404);
        } elseif (Str::length($serialNumber) < 9) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should contain minimum 9 digits!",
            ], 404);
        } elseif (! ctype_alnum($serialNumber)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should not begin with '0' or letter!",
            ], 404);
        }

        if ($itemCode == null || $itemCode == '' || ! $itemCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plant table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        } elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 403);
        }

        $work = Machine::where('work_center', $workCenter)->first();

        if (! $work) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            $job = ClassCharacteristic::where('aufnr', $jobNo)->first();

            if (! $job) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found!",
                ], 404);
            }

            $jobPlant = ClassCharacteristic::where('aufnr', $jobNo)->where('plant_id', $plantId)->first();

            if (! $jobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $jobWorkCenter = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            if (! $jobWorkCenter) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the work center '{$workCenter}'!",
                ], 404);
            }
        }

        $item = Item::where('code', $itemCode)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $itemPlant = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

        if (! $itemPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
            ], 404);
        }

        $itemId = $itemPlant->id;

        $sNo = ClassCharacteristic::where('gernr', $serialNumber)->first();

        $typesToCreate = [];

        if (! $sNo) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found!",
            ], 404);
        } else {
            $modelHeading = $sNo->zmm_heading ?? '';

            if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
            } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP'];
            } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['PUMP'];
            } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
                $typesToCreate = ['MOTOR'];
            } else {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
                ], 404);
            }

            if (! in_array($modelType, $typesToCreate, true)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Model type '{$modelType}' does not match with the model heading '{$modelHeading}'!",
                ], 404);
            }
        }

        $sNoPlant = ClassCharacteristic::where('gernr', $serialNumber)->where('plant_id', $plantId)->first();

        if (! $sNoPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found for the plant code '{$plantCode}'!",
            ], 404);
        }

        $sNoItem = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('plant_id', $plantId)->first();

        if (! $sNoItem) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found with the item code '{$itemCode}'!",
            ], 404);
        }

        $curStat = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

        if (! $curStat) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found for the work center '{$workCenter}'!",
            ], 404);
        }

        if (empty($characteristics) || ! is_array($characteristics) || count($characteristics) == 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Characteristics can't be empty!",
            ], 404);
        }

        $curHead = null;
        $hasMvhs = false;
        if ($jobNo != null && $jobNo != '' && $jobNo) {
            $jobItemCode = ClassCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $jobItemCode) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found with the item code '{$itemCode}'!",
                ], 404);
            }

            $curStat = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $curStat) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for the job number '$jobNo'!",
                ], 404);
            } else {
                $curHead = $curStat?->zmm_heading;
                if (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $hasMvhs = true;
                }
            }
        } else {
            $curHead = $curStat?->zmm_heading;
            if (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $hasMvhs = true;
            }
        }

        $mvhsCnt = 1;
        if ($hasMvhs == true) {
            $stick = StickerMaster::where('item_id', $itemId)->first();

            if (! $stick) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                ], 404);
            }

            $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

            if (! $stickPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                ], 404);
            } else {
                $curMvhs = trim($stickPlant?->laser_part_validation2);
                if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                    ], 404);
                } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'The MVHS master count should be between 1 to 9!', // "MVHS master count '{$curMvhs}' should contain only numeric values between 1 to 9!"
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     $mvhsCnt = 1;
                } else {
                    $mvhsCnt = $curMvhs;
                }
            }
        } else {
            if ($modelType == 'NAME_PLATE') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' doesn't have name plate model to proceed!",
                ], 404);
            } elseif (Str::contains($curHead, 'PUMP', ignoreCase: true) && ! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                if ($modelType == 'MOTOR') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have motor model to proceed!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                    //     ], 404);
                }
            } elseif (Str::contains($curHead, 'MOTOR', ignoreCase: true)) {
                if ($modelType == 'PUMP') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have pump model to proceed!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                    //     ], 404);
                }
            } elseif (! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' doesn't have valid model type to proceed!",
                ], 404);
            }
        }

        $col = ['marked_by', 'man_marked_by', 'motor_marked_by', 'pump_marked_by', 'name_plate_marked_by'];
        $missingUsers = [];
        $missingUsersPlant = [];
        $missingUsersRight = [];
        foreach ($characteristics as $ch) {
            foreach ($col as $field) {
                if (! empty($ch[$field])) {
                    $markUser = $ch[$field];
                    if ($markUser == 'jothi') {
                        $markUser = 'Admin';
                    }

                    $user = User::where('name', $markUser)->first();

                    if (! $user) {
                        $missingUsers[$field] = $markUser;
                    } else {
                        $userPlant = User::where('name', $markUser)->where('plant_id', $plantId)->first();

                        if (! $userPlant && ! $user->hasRole('Super Admin')) {
                            $missingUsersPlant[$field] = $markUser;
                        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
                            $missingUsersRight[$field] = $markUser;
                        }
                    }
                }
            }
        }

        if (! empty($missingUsers)) {
            // return response()->json([
            //     'user_not_found' => $missingUsers
            // ], 404);
            $uniqueMissingUsers = array_unique($missingUsers);

            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsers)."' not found in users table!",
            ], 404);
        } elseif (! empty($missingUsersPlant)) {
            $uniqueMissingUsersPlant = array_unique($missingUsersPlant);

            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsersPlant)."' not found for the plant code '{$plantCode}' in users table!",
            ], 404);
        } elseif (! empty($missingUsersRight)) {
            $uniqueMissingUsersRight = array_unique($missingUsersRight);

            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Following users : '".implode(', ', $uniqueMissingUsersRight)."' does not have rights!",
            ], 404);
        }

        $updatedRows = 0;
        $statusTyp = strtolower($markedStatus); // ($markedStatus == 'Stopped') ? 'stopped' : 'marked';
        $modelTyp = strtolower($modelType);
        $isAuto = false;

        foreach ($data['characteristics'] as $char) {
            $curMarkStat = $curStat->mark_status ?? null;
            $curMotorMarkStat = $curStat->motor_marked_status ?? null;
            $curPumpMarkStat = $curStat->pump_marked_status ?? null;
            $curNamePlateMarkStat = $curStat->name_plate_marked_status ?? null;
            $curMarkBy = $curStat->marked_by ?? null;
            $curMotorMarkBy = $curStat->motor_marked_by ?? null;
            $curPumpMarkBy = $curStat->pump_marked_by ?? null;
            $curNamePlateMarkBy = $curStat->name_plate_marked_by ?? null;
            $curManualMarkBy = $curStat->man_marked_by ?? null;
            $curWindNo = $curStat->winded_serial_number ?? null;
            $curRewWind = ($curStat->winded_rework_status == '1') ? '1' : '0';
            $curMMach = $curStat->motor_machine_name ?? null;
            $curPMach = $curStat->pump_machine_name ?? null;
            $curNpMach = $curStat->name_plate_machine_name ?? null;
            $curPart1 = $curStat->part_validation_1 ?? null;
            $curPart2 = $curStat->part_validation_2 ?? null;
            $slUser = $curStat->samlight_logged_name ?? null;
            $curWorkFlow = $curStat->has_work_flow_id ?? '0';

            $curMotMarkTim = empty($curStat->motor_marked_datetime) ? null : $curStat->motor_marked_datetime;
            $curPumMarkTim = empty($curStat->pump_marked_datetime) ? null : $curStat->pump_marked_datetime;
            $curNapMarkTim = empty($curStat->name_plate_marked_datetime) ? null : $curStat->name_plate_marked_datetime;

            if ($jobNo != null && $jobNo != '' && $jobNo) {
                // $curStat = ClassCharacteristic::where('plant_id', $plantId)->where('machine_id', $machineId)->where('aufnr', $jobNo)->where('gernr', $serialNumber)->where('item_id', $itemId)->first();
                if ($modelType == 'MOTOR' && ($curMarkStat == 'Marked' || $curMotorMarkStat == 'Marked')) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Motor serial number '{$serialNumber}' already marked in auto mode!",
                    ], 404);
                } elseif ($modelType == 'PUMP' && ($curMarkStat == 'Marked' || $curPumpMarkStat == 'Marked')) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Pump serial number '{$serialNumber}' already marked in auto mode!",
                    ], 404);
                } elseif ($modelType == 'NAME_PLATE' && ($curMarkStat == 'Marked' || $curNamePlateMarkStat == 'Marked')) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Name plate serial number '{$serialNumber}' already marked in auto mode!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET' && $curMarkStat == 'Marked') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Pumpset serial number '{$serialNumber}' already marked in auto mode!",
                    //     ], 404);
                }

                $physiCnt = (intval($curStat->marked_physical_count ?? 0) ?: 0) + 1;
                // $physiCnt = (($curStat->marked_physical_count == null || $curStat->marked_physical_count == '' || $curStat->marked_physical_count == '0') ? 0 : (int) $curStat->marked_physical_count) + 1;
                // marked_expected_time
                $motPhysiCnt = intval($curStat->motor_marked_physical_count ?? 0) ?: 0;
                $pumPhysiCnt = intval($curStat->pump_marked_physical_count ?? 0) ?: 0;

                $expecTim = (floatval($curStat->marked_expected_time ?? 0.0) ?: 0.0) + $expectedTime;
                $motExpecTim = floatval($curStat->motor_expected_time ?? 0.0) ?: 0.0;
                $pumExpecTim = floatval($curStat->pump_expected_time ?? 0.0) ?: 0.0;
                $napExpecTim = floatval($curStat->name_plate_expected_time ?? 0.0) ?: 0.0;

                if ($char['motor_pump_pumpset_status'] == '3') {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        } elseif ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                        }

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $motPhysiCnt = $motPhysiCnt + 1;
                            $motExpecTim = $motExpecTim + $expectedTime;
                            if ($motPhysiCnt >= $mvhsCnt) {
                                $curMotorMarkStat = 'Marked';
                            }
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $pumPhysiCnt = $pumPhysiCnt + 1;
                            $pumExpecTim = $pumExpecTim + $expectedTime;
                            if ($pumPhysiCnt >= $mvhsCnt) {
                                $curPumpMarkStat = 'Marked';
                            }
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        } elseif ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $napExpecTim = $napExpecTim + $expectedTime;
                            $curNamePlateMarkStat = 'Marked';
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($hasMvhs == true && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked' && $curNamePlateMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        } elseif ($hasMvhs == false && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_status' => $curMotorMarkStat,
                            'motor_marked_physical_count' => (string) $motPhysiCnt,
                            'motor_expected_time' => (string) $motExpecTim,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_status' => $curPumpMarkStat,
                            'pump_marked_physical_count' => (string) $pumPhysiCnt,
                            'pump_expected_time' => (string) $pumExpecTim,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_status' => $curNamePlateMarkStat,
                            'name_plate_expected_time' => (string) $napExpecTim,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach,
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                } elseif ($hasMvhs == true && $char['motor_pump_pumpset_status'] == '4') {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                        }

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'name_plate_machine_name' => $curNpMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $napExpecTim = $napExpecTim + $expectedTime;
                            $curNamePlateMarkStat = 'Marked';
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked' && $curNamePlateMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'name_plate_marked_status' => $curNamePlateMarkStat,
                            'name_plate_expected_time' => (string) $napExpecTim,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'name_plate_machine_name' => $curNpMach,
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                } elseif ($char['motor_pump_pumpset_status'] == '2') {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        }

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'pump_machine_name' => $curPMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $pumPhysiCnt = $pumPhysiCnt + 1;
                            $pumExpecTim = $pumExpecTim + $expectedTime;
                            if ($pumPhysiCnt >= $mvhsCnt) {
                                $curPumpMarkStat = 'Marked';
                            }
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($hasMvhs == true && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked' && $curNamePlateMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        } elseif ($hasMvhs == false && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'pump_marked_status' => $curPumpMarkStat,
                            'pump_marked_physical_count' => (string) $pumPhysiCnt,
                            'pump_expected_time' => (string) $pumExpecTim,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'pump_machine_name' => $curPMach,
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                } elseif ($char['motor_pump_pumpset_status'] == '1') {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        }

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'motor_machine_name' => $curMMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $motPhysiCnt = $motPhysiCnt + 1;
                            $motExpecTim = $motExpecTim + $expectedTime;
                            if ($motPhysiCnt >= $mvhsCnt) {
                                $curMotorMarkStat = 'Marked';
                            }
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($hasMvhs == true && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked' && $curNamePlateMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        } elseif ($hasMvhs == false && $curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_status' => $curMotorMarkStat,
                            'motor_marked_physical_count' => (string) $motPhysiCnt,
                            'motor_expected_time' => (string) $motExpecTim,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'motor_pump_pumpset_status' => '3',
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'motor_machine_name' => $curMMach,
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                } elseif ($hasMvhs == true) {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        } elseif ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                        }

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => null,
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $motPhysiCnt = $motPhysiCnt + 1;
                            $motExpecTim = $motExpecTim + $expectedTime;
                            if ($motPhysiCnt >= $mvhsCnt) {
                                $curMotorMarkStat = 'Marked';
                            }
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $pumPhysiCnt = $pumPhysiCnt + 1;
                            $pumExpecTim = $pumExpecTim + $expectedTime;
                            if ($pumPhysiCnt >= $mvhsCnt) {
                                $curPumpMarkStat = 'Marked';
                            }
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        } elseif ($modelType == 'NAME_PLATE') {
                            $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? now() : $char['name_plate_marked_datetime'];
                            $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                            $napExpecTim = $napExpecTim + $expectedTime;
                            $curNamePlateMarkStat = 'Marked';
                            $curNamePlateMarkBy = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? $curNamePlateMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked' && $curNamePlateMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_status' => $curMotorMarkStat,
                            'motor_marked_physical_count' => (string) $motPhysiCnt,
                            'motor_expected_time' => (string) $motExpecTim,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_status' => $curPumpMarkStat,
                            'pump_marked_physical_count' => (string) $pumPhysiCnt,
                            'pump_expected_time' => (string) $pumExpecTim,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_status' => $curNamePlateMarkStat,
                            'name_plate_expected_time' => (string) $napExpecTim,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => null,
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach,
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                } else {
                    if ($markedStatus == 'Stopped') {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                        }

                        // $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? $curNapMarkTim : $char['name_plate_marked_datetime'];

                        $values = [
                            'mark_status' => $markedStatus,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => null,
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach,
                            'stopped_datetime' => now(),
                            'is_stopped' => '2',
                            'stopped_by' => $userName ?? null,
                            'updated_by' => $userName ?? null,
                        ];
                    } else {
                        if ($modelType == 'MOTOR') {
                            $curMotMarkTim = empty($char['motor_marked_datetime']) ? now() : $char['motor_marked_datetime'];
                            $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                            $motPhysiCnt = $motPhysiCnt + 1;
                            $motExpecTim = $motExpecTim + $expectedTime;
                            if ($motPhysiCnt >= $mvhsCnt) {
                                $curMotorMarkStat = 'Marked';
                            }
                            $curMotorMarkBy = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? $curMotorMarkBy;
                        } elseif ($modelType == 'PUMP') {
                            $curPumMarkTim = empty($char['pump_marked_datetime']) ? now() : $char['pump_marked_datetime'];
                            $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                            $pumPhysiCnt = $pumPhysiCnt + 1;
                            $pumExpecTim = $pumExpecTim + $expectedTime;
                            if ($pumPhysiCnt >= $mvhsCnt) {
                                $curPumpMarkStat = 'Marked';
                            }
                            $curPumpMarkBy = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? $curPumpMarkBy;
                            // } elseif ($modelType == 'PUMPSET' && $physiCnt >= $mvhsCnt) {
                            //     $curMarkStat = 'Marked';
                        }

                        // $curNapMarkTim = empty($char['name_plate_marked_datetime']) ? $curNapMarkTim : $char['name_plate_marked_datetime'];

                        $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                        if ($curMotorMarkStat == 'Marked' && $curPumpMarkStat == 'Marked') {
                            $curMarkStat = 'Marked';
                        } elseif (Str::contains($curHead, 'PUMP', ignoreCase: true) && ! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                            if ($modelType == 'PUMP' && $pumPhysiCnt >= $mvhsCnt) {
                                $curMarkStat = 'Marked';
                            }
                        } elseif (Str::contains($curHead, 'MOTOR', ignoreCase: true)) {
                            if ($modelType == 'MOTOR' && $motPhysiCnt >= $mvhsCnt) {
                                $curMarkStat = 'Marked';
                            }
                        }

                        $values = [
                            'mark_status' => $curMarkStat,
                            'marked_datetime' => empty($char['marked_datetime']) ? now() : $char['marked_datetime'],
                            'marked_physical_count' => (string) $physiCnt,
                            'marked_expected_time' => (string) $expecTim,
                            'marked_by' => ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? $curMarkBy,
                            'motor_marked_status' => $curMotorMarkStat,
                            'motor_marked_physical_count' => (string) $motPhysiCnt,
                            'motor_expected_time' => (string) $motExpecTim,
                            'motor_marked_datetime' => $curMotMarkTim,
                            'motor_marked_by' => $curMotorMarkBy,
                            'pump_marked_status' => $curPumpMarkStat,
                            'pump_marked_physical_count' => (string) $pumPhysiCnt,
                            'pump_expected_time' => (string) $pumExpecTim,
                            'pump_marked_datetime' => $curPumMarkTim,
                            'pump_marked_by' => $curPumpMarkBy,
                            'name_plate_marked_status' => $curNamePlateMarkStat,
                            'name_plate_expected_time' => (string) $napExpecTim,
                            'name_plate_marked_datetime' => $curNapMarkTim,
                            'name_plate_marked_by' => $curNamePlateMarkBy,
                            'motor_pump_pumpset_status' => null,
                            'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                            'winded_rework_status' => (string) $curRewWind,
                            'motor_machine_name' => $curMMach,
                            'pump_machine_name' => $curPMach,
                            'name_plate_machine_name' => $curNpMach, // empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'],
                            'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                            'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                            'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                            'pending_released_status' => $char['pending_released_status'] ?? 0,
                            'has_work_flow_id' => $char['has_work_flow_id'] ?? $curWorkFlow,
                            'updated_by' => $userName ?? null,
                        ];
                        // $values = array_merge($values1 ?? [], $values2 ?? [], $values3 ?? [], $values4 ?? [], $values5 ?? []);
                    }
                }

                $isAuto = true;
                $affected = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->update($values);

                $updatedRows += $affected;
            } else {
                // $curStat = ClassCharacteristic::where('plant_id', $plantId)->where('machine_id', $machineId)->where('gernr', $serialNumber)->where('item_id', $itemId)->first();
                if ($modelType == 'MOTOR' && $curMarkStat != 'Marked' && $curMotorMarkStat != 'Marked') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Motor serial number '{$serialNumber}' doesn't marked in auto mode!",
                    ], 404);
                } elseif ($modelType == 'PUMP' && $curMarkStat != 'Marked' && $curPumpMarkStat != 'Marked') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Pump serial number '{$serialNumber}' doesn't marked in auto mode!",
                    ], 404);
                } elseif ($modelType == 'NAME_PLATE' && $curMarkStat != 'Marked' && $curNamePlateMarkStat != 'Marked') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Name plate serial number '{$serialNumber}' doesn't marked in auto mode!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET' && $curMarkStat != 'Marked') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Pumpset serial number '{$serialNumber}' doesn't marked in auto mode!",
                    //     ], 404);
                }

                if ($modelType == 'MOTOR') {
                    $curMMach = empty($char['motor_machine_name']) ? $curMMach : $char['motor_machine_name'];
                } elseif ($modelType == 'PUMP') {
                    $curPMach = empty($char['pump_machine_name']) ? $curPMach : $char['pump_machine_name'];
                } elseif ($modelType == 'NAME_PLATE') {
                    $curNpMach = empty($char['name_plate_machine_name']) ? $curNpMach : $char['name_plate_machine_name'];
                }

                $curRewWind = ($char['winded_rework_status'] == '1') ? '1' : $curRewWind;

                $manStat = (intval($curStat->man_marked_status ?? 0) ?: 0) + 1;
                // $manStat = ($curStat->man_marked_status == null || $curStat->man_marked_status == '' || $curStat->man_marked_status == '0') ? 0 : (int) $curStat->man_marked_status;
                $values = [
                    'man_marked_status' => (string) $manStat,
                    'man_marked_datetime' => empty($char['man_marked_datetime']) ? now() : $char['man_marked_datetime'],
                    'man_marked_by' => (($char['man_marked_by'] == 'jothi') ? 'Admin' : $char['man_marked_by']) ?? $curManualMarkBy,
                    'winded_serial_number' => empty($char['winded_serial_number']) ? $curWindNo : $char['winded_serial_number'],
                    'winded_rework_status' => (string) $curRewWind,
                    'motor_machine_name' => $curMMach,
                    'pump_machine_name' => $curPMach,
                    'name_plate_machine_name' => $curNpMach,
                    'part_validation_1' => empty($char['part_validation_1']) ? $curPart1 : $char['part_validation_1'],
                    'part_validation_2' => empty($char['part_validation_2']) ? $curPart2 : $char['part_validation_2'],
                    'samlight_logged_name' => empty($char['samlight_logged_name']) ? $slUser : $char['samlight_logged_name'],
                    'updated_by' => $userName ?? null,
                ];

                $isAuto = false;
                $affected = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->update($values);

                $updatedRows += $affected;
            }
        }

        if ($updatedRows == 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => $isAuto ? "Failed to update auto {$statusTyp} status for the {$modelTyp} serial number '{$serialNumber}'." : "Failed to update manual {$statusTyp} status for the {$modelTyp} serial number '{$serialNumber}'.",
            ], 404);
        } else {
            return response()->json([
                'status_code' => 'SUCCESS',
                'status_description' => $isAuto ? "Successfully auto {$statusTyp} status updated for the {$modelTyp} serial number '{$serialNumber}'." : "Successfully manual {$statusTyp} status updated for the {$modelTyp} serial number '{$serialNumber}'.",
            ], 200);
        }
    }

    public function storeLaserWindStatus(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        $data = $request->all();

        $plantCode = $data['plant_code'] ?? '';
        $workCenter = $data['work_center'] ?? '';
        $machineName = $data['machine_name'] ?? '';
        $jobNo = $data['aufnr'] ?? '';
        $serialNumber = $data['gernr'] ?? '';
        $itemCode = $data['item_code'] ?? '';
        $modelType = $data['model_type'] ?? '';
        $windedStatus = $data['winded_status'] ?? '';
        $windedQr = $data['winded_qr'] ?? '';
        $windedCode = $data['winded_code'] ?? '';
        $windedSerialNumber = $data['winded_serial_number'] ?? '';

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        if ($modelType == null || $modelType == '' || ! $modelType) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Marked model type can't be empty!",
            ], 404);
        } elseif ($modelType != 'MOTOR' && $modelType != 'PUMP' && $modelType != 'NAME_PLATE') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' doesn't have valid model type to proceed!",
            ], 404);
        }

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            if (Str::length($jobNo) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should not begin with '0'!",
                ], 404);
            }
        }

        if ($serialNumber == null || $serialNumber == '' || ! $serialNumber) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number can't be empty!",
            ], 404);
        } elseif (Str::length($serialNumber) < 9) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should contain minimum 9 digits!",
            ], 404);
        } elseif (! ctype_alnum($serialNumber)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' should not begin with '0' or letter!",
            ], 404);
        }

        if ($itemCode == null || $itemCode == '' || ! $itemCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plant table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        } elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 403);
        }

        $work = Machine::where('work_center', $workCenter)->first();

        if (! $work) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            $job = ClassCharacteristic::where('aufnr', $jobNo)->first();

            if (! $job) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found!",
                ], 404);
            }

            $jobPlant = ClassCharacteristic::where('aufnr', $jobNo)->where('plant_id', $plantId)->first();

            if (! $jobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $jobWorkCenter = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            if (! $jobWorkCenter) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the work center '{$workCenter}'!",
                ], 404);
            }
        }

        $item = Item::where('code', $itemCode)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $itemPlant = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

        if (! $itemPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
            ], 404);
        }

        $itemId = $itemPlant->id;

        $sNo = ClassCharacteristic::where('gernr', $serialNumber)->first();

        $typesToCreate = [];

        if (! $sNo) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found!",
            ], 404);
        } else {
            $modelHeading = $sNo->zmm_heading ?? '';

            if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
            } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP'];
            } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['PUMP'];
            } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
                $typesToCreate = ['MOTOR'];
            } else {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
                ], 404);
            }

            if (! in_array($modelType, $typesToCreate, true)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Model type '{$modelType}' does not match with the model heading '{$modelHeading}'!",
                ], 404);
            }
        }

        $sNoPlant = ClassCharacteristic::where('gernr', $serialNumber)->where('plant_id', $plantId)->first();

        if (! $sNoPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found for the plant code '{$plantCode}'!",
            ], 404);
        }

        $sNoItem = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('plant_id', $plantId)->first();

        if (! $sNoItem) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found with the item code '{$itemCode}'!",
            ], 404);
        }

        $curStat = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

        if (! $curStat) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Serial number '{$serialNumber}' not found for the work center '{$workCenter}'!",
            ], 404);
        }

        $curHead = null;
        $hasMvhs = false;
        if ($jobNo != null && $jobNo != '' && $jobNo) {
            $jobItemCode = ClassCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $jobItemCode) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found with the item code '{$itemCode}'!",
                ], 404);
            }

            $curStat = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $curStat) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for the job number '$jobNo'!",
                ], 404);
            } else {
                $curHead = $curStat?->zmm_heading;
                if (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $hasMvhs = true;
                }
            }
        } else {
            $curHead = $curStat?->zmm_heading;
            if (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $hasMvhs = true;
            }
        }

        if ($hasMvhs == true) {
            $stick = StickerMaster::where('item_id', $itemId)->first();

            if (! $stick) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                ], 404);
            }

            $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

            if (! $stickPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                ], 404);
            } else {
                $curMvhs = trim($stickPlant?->laser_part_validation2);
                if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                    ], 404);
                } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'The MVHS master count should be between 1 to 9!', // "MVHS master count '{$curMvhs}' should contain only numeric values between 1 to 9!"
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     $mvhsCnt = 1;
                }
            }
        } else {
            if ($modelType == 'NAME_PLATE') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' doesn't have name plate model to proceed!",
                ], 404);
            } elseif (Str::contains($curHead, 'PUMP', ignoreCase: true) && ! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                if ($modelType == 'MOTOR') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have motor model to proceed!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                    //     ], 404);
                }
            } elseif (Str::contains($curHead, 'MOTOR', ignoreCase: true)) {
                if ($modelType == 'PUMP') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have pump model to proceed!",
                    ], 404);
                    // } elseif ($modelType == 'PUMPSET') {
                    //     return response()->json([
                    //         'status_code' => 'ERROR',
                    //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                    //     ], 404);
                }
            } elseif (! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' doesn't have valid model type to proceed!",
                ], 404);
            }
        }

        $updatedRows = 0;
        $modelTyp = strtolower($modelType ? $modelType.' ' : '');
        $isAuto = false;

        $curMarkStat = $curStat->mark_status ?? null;
        $curMotorMarkStat = $curStat->motor_marked_status ?? null;
        $curPumpMarkStat = $curStat->pump_marked_status ?? null;
        $curNamePlateMarkStat = $curStat->name_plate_marked_status ?? null;

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            if ($modelType == 'MOTOR' && ($curMarkStat == 'Marked' || $curMotorMarkStat == 'Marked')) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Motor serial number '{$serialNumber}' already marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'PUMP' && ($curMarkStat == 'Marked' || $curPumpMarkStat == 'Marked')) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Pump serial number '{$serialNumber}' already marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'NAME_PLATE' && ($curMarkStat == 'Marked' || $curNamePlateMarkStat == 'Marked')) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Name plate serial number '{$serialNumber}' already marked in auto mode!",
                ], 404);
                // } elseif ($modelType == 'PUMPSET' && $curMarkStat == 'Marked') {
                //     return response()->json([
                //         'status_code' => 'ERROR',
                //         'status_description' => "Pumpset serial number '{$serialNumber}' already marked in auto mode!",
                //     ], 404);
            }

            $values = [
                'plant_id' => $plantId,
                'item_id' => $itemId,
                'machine_id' => $machineId,
                'machine_name' => $machineName,
                'aufnr' => $jobNo,
                'gernr' => $serialNumber,
                'model_type' => $modelType,
                'winded_status' => $windedStatus,
                'winded_qr' => $windedQr,
                'winded_code' => $windedCode,
                'winded_serial_number' => $windedSerialNumber,
                'created_by' => $userName ?? null,
                'updated_by' => $userName ?? null,
            ];

            $isAuto = true;
            WindedSerialValidationError::create($values);
            $updatedRows = 1;
        } else {
            if ($modelType == 'MOTOR' && $curMarkStat != 'Marked' && $curMotorMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Motor serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'PUMP' && $curMarkStat != 'Marked' && $curPumpMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Pump serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'NAME_PLATE' && $curMarkStat != 'Marked' && $curNamePlateMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Name plate serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
                // } elseif ($modelType == 'PUMPSET' && $curMarkStat != 'Marked') {
                //     return response()->json([
                //         'status_code' => 'ERROR',
                //         'status_description' => "Pumpset serial number '{$serialNumber}' doesn't marked in auto mode!",
                //     ], 404);
            }

            $values = [
                'plant_id' => $plantId,
                'item_id' => $itemId,
                'machine_id' => $machineId,
                'machine_name' => $machineName,
                'aufnr' => $curStat?->aufnr,
                'gernr' => $serialNumber,
                'model_type' => $modelType,
                'winded_status' => $windedStatus,
                'winded_qr' => $windedQr,
                'winded_code' => $windedCode,
                'winded_serial_number' => $windedSerialNumber,
                'created_by' => $userName ?? null,
                'updated_by' => $userName ?? null,
            ];

            $isAuto = false;
            WindedSerialValidationError::create($values);
            $updatedRows = 1;
        }

        if ($updatedRows == 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => $isAuto ? "Failed to update auto mode winding status for the {$modelTyp}serial number '{$serialNumber}'!" : "Failed to update manual mode winding status for the {$modelTyp}serial number '{$serialNumber}'!",
            ], 404);
        } else {
            return response()->json([
                'status_code' => 'SUCCESS',
                'status_description' => $isAuto ? "Successfully auto mode winding status updated for the {$modelTyp}serial number '{$serialNumber}'." : "Successfully manual mode winding status updated for the {$modelTyp}serial number '{$serialNumber}'.",
            ], 200);
        }
    }

    public function storeClassChar(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        $data = $request->all();

        $plantCode = $data['plant_code'];
        $workCenter = $data['work_center'];
        $jobNo = $data['aufnr'] ?? '';
        $itemCode = $data['item_code'] ?? '';
        $serialNumbers = $data['serial_numbers'] ?? '';
        $characteristics = $data['characteristics'];

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        } elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 403);
        }

        $work = Machine::where('work_center', $workCenter)->first();

        if (! $work) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        if ($jobNo != null && $jobNo != '' && $jobNo) {
            if (Str::length($jobNo) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNo)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' should not begin with '0'!",
                ], 404);
            }
        }

        $availFields = ['class', 'arbid', 'gamng', 'lmnga', 'zz1_cn_bill_ord', 'zmm_amps', 'zmm_brand', 'zmm_degreeofprotection', 'zmm_delivery', 'zmm_dir_rot', 'zmm_discharge', 'zmm_discharge_max', 'zmm_discharge_min', 'zmm_duty', 'zmm_eff_motor', 'zmm_eff_pump', 'zmm_frequency', 'zmm_head', 'zmm_heading', 'zmm_head_max', 'zmm_head_minimum', 'zmm_idx_eff_mtr', 'zmm_idx_eff_pump', 'zmm_kvacode', 'zmm_maxambtemp', 'zmm_mincoolingflow', 'zmm_motorseries', 'zmm_motor_model', 'zmm_outlet', 'zmm_phase', 'zmm_pressure', 'zmm_pumpflowtype', 'zmm_pumpseries', 'zmm_pump_model', 'zmm_ratedpower', 'zmm_region', 'zmm_servicefactor', 'zmm_servicefactormaximumamps', 'zmm_speed', 'zmm_suction', 'zmm_suctionxdelivery', 'zmm_supplysource', 'zmm_temperature', 'zmm_thrustload', 'zmm_volts', 'zmm_wire', 'zmm_package', 'zmm_pvarrayrating', 'zmm_isi', 'zmm_isimotor', 'zmm_isipump', 'zmm_isipumpset', 'zmm_pumpset_model', 'zmm_stages', 'zmm_headrange', 'zmm_overall_efficiency', 'zmm_connection', 'zmm_min_bore_size', 'zmm_isireference', 'zmm_category', 'zmm_submergence', 'zmm_capacitorstart', 'zmm_capacitorrun', 'zmm_inch', 'zmm_motor_type', 'zmm_dismantle_direction', 'zmm_eff_ovrall', 'zmm_bodymoc', 'zmm_rotormoc', 'zmm_dlwl', 'zmm_inputpower', 'zmm_imp_od', 'zmm_ambtemp', 'zmm_de', 'zmm_dischargerange', 'zmm_efficiency_class', 'zmm_framesize', 'zmm_impellerdiameter', 'zmm_insulationclass', 'zmm_maxflow', 'zmm_minhead', 'zmm_mtrlofconst', 'zmm_nde', 'zmm_powerfactor', 'zmm_tagno', 'zmm_year', 'zmm_laser_name', 'zmm_logo_cp', 'zmm_logo_ce', 'zmm_logo_nsf', 'zmm_logo_eac', 'zmm_grwt_motor', 'zmm_grwt_pump', 'zmm_grwt_pset', 'zmm_grwt_cable', 'zmm_grwt_pf', 'zmm_newt_motor', 'zmm_newt_pump', 'zmm_newt_pset', 'zmm_newt_cable', 'zmm_newt_pf', 'zmm_operating_range', 'zmm_intake_air', 'zmm_oxygen_transfer_rate', 'zmm_air_inlet_pipesize', 'zmm_sump_depth', 'zmm_poles', 'zmm_motor_heading', 'zmm_motor_speed', 'zmm_beenote', 'zmm_beenumber', 'zmm_beestar', 'zmm_eff_ttl', 'zmm_labelperiod', 'zmm_modelyear', 'zmm_performance_factor', 'zqmm_qty', 'zmm_operating_temperature', 'zmm_axial_force', 'zmm_codeclass', 'zmm_colour', 'zmm_grade', 'zmm_isivalve', 'zmm_isi_wc', 'zmm_length', 'zmm_license_cml_no', 'zmm_mfgmonyr', 'zmm_motoridentification', 'zmm_packtype', 'zmm_panel', 'zmm_pumpidentification', 'zmm_psettype', 'zmm_size', 'zmm_type', 'zmm_usp', 'marked_datetime', 'marked_by', 'motor_pump_pumpset_status', 'motor_machine_name', 'pump_machine_name', 'name_plate_machine_name', 'pending_released_status', 'has_work_flow_id']; // 'mark_status','marked_physical_count', 'marked_expected_time', 'man_marked_status', 'man_marked_datetime', 'man_marked_by', 'motor_marked_status', 'motor_marked_physical_count', 'motor_expected_time', 'motor_marked_datetime', 'motor_marked_by', 'pump_marked_status', 'pump_marked_physical_count', 'pump_expected_time', 'pump_marked_datetime', 'pump_marked_by', 'name_plate_marked_status', 'name_plate_expected_time', 'name_plate_marked_datetime', 'name_plate_marked_by', 'winded_serial_number', 'winded_rework_status', 'part_validation_1', 'part_validation_2', 'samlight_logged_name'

        if ($itemCode != '' && $itemCode != null && $itemCode && Str::length($itemCode) > 0) {
            $existingJobNo = ClassCharacteristic::where('aufnr', $jobNo)->first(); // ->where('machine_id', $machineId)->where('plant_id', $plantId)

            if ($existingJobNo) {
                $curPlant = Plant::where('id', $existingJobNo->plant_id)->first();
                $curMachine = Machine::where('id', $existingJobNo->machine_id)->first();

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Duplicate job number '{$jobNo}' found for the plant name '{$curPlant?->name}' and work center '$curMachine?->work_center'!",
                ], 404);
            }

            if (Str::length($itemCode) < 6) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
                ], 404);
            } elseif (! ctype_alnum($itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
                ], 404);
            } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
                ], 404);
            }

            $item = Item::where('code', $itemCode)->first();

            if (! $item) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found in items table!",
                ], 404);
            }

            $itemPlant = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

            if (! $itemPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
                ], 404);
            }

            $itemId = $itemPlant->id;

            if (empty($serialNumbers) || ! is_array($serialNumbers) || count($serialNumbers) == 0) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial numbers can't be empty!",
                ], 404);
            }

            if (empty($characteristics) || ! is_array($characteristics) || count($characteristics) == 0) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Characteristics can't be empty!",
                ], 404);
            }

            $columns = Schema::getColumnListing((new ClassCharacteristic)->getTable());

            $invalidFields = [];

            foreach ($request->input('characteristics', []) as $char) {
                $inputKeys = array_keys($char);

                $unexpected = array_diff($inputKeys, $columns);

                if (! empty($unexpected)) {
                    $invalidFields = array_merge($invalidFields, $unexpected);
                }
            }

            if (! empty($invalidFields)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown characteristics names found '".implode(', ', $invalidFields)."'.",
                ], 404);
            }

            $col = ['marked_by']; // , 'man_marked_by', 'motor_marked_by', 'pump_marked_by', 'name_plate_marked_by'
            $missingUsers = [];
            $missingUsersPlant = [];
            $missingUsersRight = [];
            foreach ($characteristics as $ch) {
                $curHead = $ch['zmm_heading'] ?? null;
                if ($curHead == '' || $curHead == null) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "ZMM_HEADING - characteristics doesn't have value to proceed!",
                    ], 404);
                } elseif (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $stick = StickerMaster::where('item_id', $itemId)->first();

                    if (! $stick) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                        ], 404);
                    }

                    $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                    if (! $stickPlant) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                        ], 404);
                    } else {
                        $curMvhs = trim($stickPlant?->laser_part_validation2);
                        if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                            ], 404);
                        } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'The MVHS master count should be between 1 to 9!',
                            ], 404);
                        }
                    }
                }

                foreach ($col as $field) {
                    if (! empty($ch[$field])) {
                        $markUser = $ch[$field];
                        if ($markUser == 'jothi') {
                            $markUser = 'Admin';
                        }

                        $user = User::where('name', $markUser)->first();

                        if (! $user) {
                            $missingUsers[$field] = $markUser;
                        } else {
                            $userPlant = User::where('name', $markUser)->where('plant_id', $plantId)->first();

                            if (! $userPlant && ! $user->hasRole('Super Admin')) {
                                $missingUsersPlant[$field] = $markUser;
                            } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
                                $missingUsersRight[$field] = $markUser;
                            }
                        }
                    }
                }
            }

            if (! empty($missingUsers)) {
                // return response()->json([
                //     'user_not_found' => $missingUsers
                // ], 404);
                $uniqueMissingUsers = array_unique($missingUsers);

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsers)."' not found in users table!",
                ], 404);
            } elseif (! empty($missingUsersPlant)) {
                $uniqueMissingUsersPlant = array_unique($missingUsersPlant);

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsersPlant)."' not found for the plant code '{$plantCode}' in users table!",
                ], 404);
            } elseif (! empty($missingUsersRight)) {
                $uniqueMissingUsersRight = array_unique($missingUsersRight);

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Following users : '".implode(', ', $uniqueMissingUsersRight)."' does not have rights!",
                ], 404);
            }

            $dupSerials = [];
            $duplicateSerials = [];
            $seenSerialNumbers = [];
            foreach ($serialNumbers as $serial) {
                try {
                    $existing = ClassCharacteristic::where('gernr', $serial)->where('plant_id', $plantId)->first();
                    // ->where('item_id', $itemId)

                    if ($existing) {
                        $dupSerials[] = $serial;
                    }

                    if (in_array($serial, $seenSerialNumbers)) {
                        $duplicateSerials[] = $serial;
                    } else {
                        $seenSerialNumbers[] = $serial;
                    }
                } catch (\Exception $e) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Error occurred while inserting new master characteristics for the serial number '{$serial}', {$e->getMessage()}",
                        // 'char_data' => $char
                    ], 500);
                }
            }

            if (! empty($duplicateSerials)) {
                $uniqueDupSerials = array_unique($duplicateSerials);

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Following serial number(s) are already exist in POST API : '".implode(', ', $uniqueDupSerials)."'!",
                ], 404);
            } elseif (! empty($dupSerials)) {
                $uniqueDupSerials = array_unique($dupSerials);

                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Following serial number(s) are already exist in cloud : '".implode(', ', $uniqueDupSerials)."'!",
                ], 404);
            }

            $isInsert = false;

            foreach ($serialNumbers as $serial) {
                foreach ($characteristics as $char) {
                    try {
                        $insertData = [
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'aufnr' => $jobNo,
                            'item_id' => $itemId,
                            'gernr' => $serial,
                        ];

                        foreach ($availFields as $field) {
                            if (in_array($field, $columns)) {
                                $insertData[$field] = $char[$field] ?? null;
                            }
                        }

                        $insertData['marked_datetime'] = empty($char['marked_datetime']) ? now() : $char['marked_datetime'];

                        $insertData['marked_by'] = ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? null;
                        // $insertData['man_marked_by'] = ($char['man_marked_by'] == 'jothi') ? 'Admin' : $char['man_marked_by'] ?? null;
                        // $insertData['motor_marked_by'] = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? null;
                        // $insertData['pump_marked_by'] = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? null;
                        // $insertData['name_plate_marked_by'] = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? null;

                        $existing = ClassCharacteristic::where('gernr', $serial)->where('plant_id', $plantId)->first(); // ->where('item_id', $itemId)

                        if ($existing) {
                            // $insertData['updated_by'] = $userName ?? null;
                            // $existing->update($insertData);
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Duplicate serial number '{$serial}' found while inserting new master characteristics in job number '{$existing->aufnr}'!",
                            ], 404);
                        } else {
                            $isInsert = true;
                            $insertData['created_by'] = $userName ?? null;
                            ClassCharacteristic::create($insertData);
                        }
                    } catch (\Exception $e) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Error occurred while inserting new master characteristics for the serial number '{$serial}', {$e->getMessage()}",
                            // 'char_data' => $char
                        ], 500);
                    }
                }
            }

            if ($isInsert) {
                $classChar = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();
                $modelHeading = $classChar?->zmm_heading ?? '';
                $typesToCreate = [];

                if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
                } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                    $typesToCreate = ['MOTOR', 'PUMP'];
                } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                    $typesToCreate = ['PUMP'];
                } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
                    $typesToCreate = ['MOTOR'];
                } else {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
                    ], 404);
                }

                TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                foreach ($typesToCreate as $type) {
                    TempClassCharacteristic::create([
                        'plant_id' => $plantId,
                        'machine_id' => $machineId,
                        'item_id' => $itemId,
                        'aufnr' => $jobNo,
                        'model_type' => $type,
                        'has_work_flow_id' => '2',
                        'created_by' => $userName,
                        'updated_by' => $userName,
                    ]);
                }

                if ($classChar) {
                    ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                        ->update([
                            'has_work_flow_id' => '2',
                            'updated_at' => now(),
                            'updated_by' => $userName,
                        ]);
                }
            }

            return response()->json([
                'status_code' => 'SUCCESS',
                'status_description' => $isInsert ? "Successfully inserted new master characteristics for the job number '{$jobNo}'." : "Failed to insert new master characteristics for the job number '{$jobNo}'.",
            ], 200);
        } else {
            $hasNewSno = false;

            if (empty($characteristics) || ! is_array($characteristics) || count($characteristics) == 0) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Characteristics can't be empty!",
                ], 404);
            }

            $columns = Schema::getColumnListing((new ClassCharacteristic)->getTable());

            $invalidFields = [];

            foreach ($request->input('characteristics', []) as $char) {
                $inputKeys = array_keys($char);

                $unexpected = array_diff($inputKeys, $columns);

                if (! empty($unexpected)) {
                    $invalidFields = array_merge($invalidFields, $unexpected);
                }
            }

            if (! empty($invalidFields)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown characteristics names found '".implode(', ', $invalidFields)."'.",
                ], 404);
            }

            $existingJobNo = ClassCharacteristic::where('aufnr', $jobNo)->first();

            if (! $existingJobNo) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found!",
                ], 404);
            }

            $existingJobPlant = ClassCharacteristic::where('aufnr', $jobNo)->where('plant_id', $plantId)->first();

            if (! $existingJobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $classChar = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            if (! $classChar) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNo}' not found for the work center '{$workCenter}'!", // plant code '{$plantCode}' and
                ], 404);
            }

            $itemId = $classChar->item_id;

            $item = Item::where('id', $itemId)->first();

            $itemCode = $item?->code;

            if (empty($serialNumbers) || ! is_array($serialNumbers) || count($serialNumbers) == 0) {
                $hasNewSno = false;
                // return response()->json([
                //     'status_code' => "ERROR",
                //     'status_description' => "Serial numbers can't be empty!"
                // ], 404);
                foreach ($characteristics as $ch) {
                    $curHead = $ch['zmm_heading'] ?? null;
                    if ($curHead == '' || $curHead == null) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "ZMM_HEADING - characteristics doesn't have value to proceed!",
                        ], 404);
                    } elseif (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                        $stick = StickerMaster::where('item_id', $itemId)->first();

                        if (! $stick) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                            ], 404);
                        }

                        $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                        if (! $stickPlant) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                            ], 404);
                        } else {
                            $curMvhs = trim($stickPlant?->laser_part_validation2);
                            if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                                return response()->json([
                                    'status_code' => 'ERROR',
                                    'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                                ], 404);
                            } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                                return response()->json([
                                    'status_code' => 'ERROR',
                                    'status_description' => 'The MVHS master count should be between 1 to 9!',
                                ], 404);
                            }
                        }
                    }
                }
            } else {
                $hasNewSno = true;

                $col = ['marked_by']; // , 'man_marked_by', 'motor_marked_by', 'pump_marked_by', 'name_plate_marked_by'
                $missingUsers = [];
                $missingUsersPlant = [];
                $missingUsersRight = [];
                foreach ($characteristics as $ch) {
                    $curHead = $ch['zmm_heading'] ?? null;
                    if ($curHead == '' || $curHead == null) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "ZMM_HEADING - characteristics doesn't have value to proceed!",
                        ], 404);
                    } elseif (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                        $stick = StickerMaster::where('item_id', $itemId)->first();

                        if (! $stick) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                            ], 404);
                        }

                        $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                        if (! $stickPlant) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                            ], 404);
                        } else {
                            $curMvhs = trim($stickPlant?->laser_part_validation2);
                            if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                                return response()->json([
                                    'status_code' => 'ERROR',
                                    'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                                ], 404);
                            } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                                return response()->json([
                                    'status_code' => 'ERROR',
                                    'status_description' => 'The MVHS master count should be between 1 to 9!',
                                ], 404);
                            }
                        }
                    }

                    foreach ($col as $field) {
                        if (! empty($ch[$field])) {
                            $markUser = $ch[$field];
                            if ($markUser == 'jothi') {
                                $markUser = 'Admin';
                            }

                            $user = User::where('name', $markUser)->first();

                            if (! $user) {
                                $missingUsers[$field] = $markUser;
                            } else {
                                $userPlant = User::where('name', $markUser)->where('plant_id', $plantId)->first();

                                if (! $userPlant && ! $user->hasRole('Super Admin')) {
                                    $missingUsersPlant[$field] = $markUser;
                                } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
                                    $missingUsersRight[$field] = $markUser;
                                }
                            }
                        }
                    }
                }

                if (! empty($missingUsers)) {
                    // return response()->json([
                    //     'user_not_found' => $missingUsers
                    // ], 404);
                    $uniqueMissingUsers = array_unique($missingUsers);

                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsers)."' not found in users table!",
                    ], 404);
                } elseif (! empty($missingUsersPlant)) {
                    $uniqueMissingUsersPlant = array_unique($missingUsersPlant);

                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Following user names : '".implode(', ', $uniqueMissingUsersPlant)."' not found for the plant code '{$plantCode}' in users table!",
                    ], 404);
                } elseif (! empty($missingUsersRight)) {
                    $uniqueMissingUsersRight = array_unique($missingUsersRight);

                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Following users : '".implode(', ', $uniqueMissingUsersRight)."' does not have rights!",
                    ], 404);
                }

                $dupSerials = [];
                $duplicateSerials = [];
                $seenSerialNumbers = [];
                foreach ($serialNumbers as $serial) {
                    try {
                        $existing = ClassCharacteristic::where('gernr', $serial)->where('plant_id', $plantId)->first(); // ->where('item_id', $itemId)

                        $existSnoJob = ClassCharacteristic::where('gernr', $serial)->where('aufnr', '!=', $jobNo)->where('plant_id', $plantId)->first();

                        if ($existing && $existSnoJob) {
                            $dupSerials[] = $serial;
                        }

                        if (in_array($serial, $seenSerialNumbers)) {
                            $duplicateSerials[] = $serial;
                        } else {
                            $seenSerialNumbers[] = $serial;
                        }
                    } catch (\Exception $e) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Error occurred while inserting new master characteristics for the serial number '{$serial}', {$e->getMessage()}",
                            // 'char_data' => $char
                        ], 500);
                    }
                }

                if (! empty($duplicateSerials)) {
                    $uniqueDupSerials = array_unique($duplicateSerials);

                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Following serial number(s) are already exist in POST API : '".implode(', ', $uniqueDupSerials)."'!",
                    ], 404);
                } elseif (! empty($dupSerials)) { // // Skip duplicate warning...
                    $uniqueDupSerials = array_unique($dupSerials);

                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Following serial number(s) are already exist in cloud : '".implode(', ', $uniqueDupSerials)."'!",
                    ], 404);
                }
            }

            $masterFields = ['class', 'arbid', 'gamng', 'lmnga', 'zz1_cn_bill_ord', 'zmm_amps', 'zmm_brand', 'zmm_degreeofprotection', 'zmm_delivery', 'zmm_dir_rot', 'zmm_discharge', 'zmm_discharge_max', 'zmm_discharge_min', 'zmm_duty', 'zmm_eff_motor', 'zmm_eff_pump', 'zmm_frequency', 'zmm_head', 'zmm_heading', 'zmm_head_max', 'zmm_head_minimum', 'zmm_idx_eff_mtr', 'zmm_idx_eff_pump', 'zmm_kvacode', 'zmm_maxambtemp', 'zmm_mincoolingflow', 'zmm_motorseries', 'zmm_motor_model', 'zmm_outlet', 'zmm_phase', 'zmm_pressure', 'zmm_pumpflowtype', 'zmm_pumpseries', 'zmm_pump_model', 'zmm_ratedpower', 'zmm_region', 'zmm_servicefactor', 'zmm_servicefactormaximumamps', 'zmm_speed', 'zmm_suction', 'zmm_suctionxdelivery', 'zmm_supplysource', 'zmm_temperature', 'zmm_thrustload', 'zmm_volts', 'zmm_wire', 'zmm_package', 'zmm_pvarrayrating', 'zmm_isi', 'zmm_isimotor', 'zmm_isipump', 'zmm_isipumpset', 'zmm_pumpset_model', 'zmm_stages', 'zmm_headrange', 'zmm_overall_efficiency', 'zmm_connection', 'zmm_min_bore_size', 'zmm_isireference', 'zmm_category', 'zmm_submergence', 'zmm_capacitorstart', 'zmm_capacitorrun', 'zmm_inch', 'zmm_motor_type', 'zmm_dismantle_direction', 'zmm_eff_ovrall', 'zmm_bodymoc', 'zmm_rotormoc', 'zmm_dlwl', 'zmm_inputpower', 'zmm_imp_od', 'zmm_ambtemp', 'zmm_de', 'zmm_dischargerange', 'zmm_efficiency_class', 'zmm_framesize', 'zmm_impellerdiameter', 'zmm_insulationclass', 'zmm_maxflow', 'zmm_minhead', 'zmm_mtrlofconst', 'zmm_nde', 'zmm_powerfactor', 'zmm_tagno', 'zmm_year', 'zmm_laser_name', 'zmm_logo_cp', 'zmm_logo_ce', 'zmm_logo_nsf', 'zmm_logo_eac', 'zmm_grwt_motor', 'zmm_grwt_pump', 'zmm_grwt_pset', 'zmm_newt_motor', 'zmm_newt_pump', 'zmm_newt_pset', 'zmm_operating_range', 'zmm_intake_air', 'zmm_oxygen_transfer_rate', 'zmm_air_inlet_pipesize', 'zmm_sump_depth', 'zmm_poles', 'zmm_motor_heading', 'zmm_motor_speed', 'zmm_beenote', 'zmm_beenumber', 'zmm_beestar', 'zmm_eff_ttl', 'zmm_labelperiod', 'zmm_modelyear', 'zmm_performance_factor', 'zqmm_qty', 'zmm_operating_temperature', 'zmm_axial_force', 'pending_released_status'];

            $isInsertOrUpdate = false;

            foreach ($characteristics as $char) {
                try {
                    $insertData = [
                        'plant_id' => $plantId,
                        'machine_id' => $machineId,
                        'aufnr' => $jobNo,
                    ];

                    foreach ($masterFields as $field) {
                        if (in_array($field, $columns)) {
                            $insertData[$field] = $char[$field] ?? null;
                        }
                    }

                    $existing = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId);

                    if ($existing) {
                        $isInsertOrUpdate = true;
                        $insertData['updated_by'] = $userName ?? null;
                        $existing->update($insertData);
                    } else {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Job number '{$jobNo}' not found to update exist master characteristics!",
                        ], 404);
                    }
                } catch (\Exception $e) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Error occurred while updating exist master characteristics for the job number '{$jobNo}', {$e->getMessage()}",
                        // 'char_data' => $char
                    ], 404);
                }
            }

            if ($hasNewSno) {
                // $itemId = $classChar->item_id;
                foreach ($serialNumbers as $serial) {
                    foreach ($characteristics as $char) {
                        try {
                            $insertData = [
                                'plant_id' => $plantId,
                                'machine_id' => $machineId,
                                'aufnr' => $jobNo,
                                'item_id' => $itemId,
                                'gernr' => $serial,
                            ];

                            foreach ($availFields as $field) {
                                if (in_array($field, $columns)) {
                                    $insertData[$field] = $char[$field] ?? null;
                                }
                            }

                            $insertData['marked_datetime'] = empty($char['marked_datetime']) ? now() : $char['marked_datetime'];

                            $insertData['marked_by'] = ($char['marked_by'] == 'jothi') ? 'Admin' : $char['marked_by'] ?? null;
                            // $insertData['man_marked_by'] = ($char['man_marked_by'] == 'jothi') ? 'Admin' : $char['man_marked_by'] ?? null;
                            // $insertData['motor_marked_by'] = ($char['motor_marked_by'] == 'jothi') ? 'Admin' : $char['motor_marked_by'] ?? null;
                            // $insertData['pump_marked_by'] = ($char['pump_marked_by'] == 'jothi') ? 'Admin' : $char['pump_marked_by'] ?? null;
                            // $insertData['name_plate_marked_by'] = ($char['name_plate_marked_by'] == 'jothi') ? 'Admin' : $char['name_plate_marked_by'] ?? null;

                            $existing = ClassCharacteristic::where('gernr', $serial)->where('plant_id', $plantId)->first(); // ->where('item_id', $itemId)

                            $existSnoJob = ClassCharacteristic::where('gernr', $serial)->where('aufnr', '!=', $jobNo)->where('plant_id', $plantId)->first();

                            if ($existing && $existSnoJob) { // // Skip duplicate warning...
                                return response()->json([
                                    'status_code' => 'ERROR',
                                    'status_description' => "Duplicate serial number '{$serial}' found while updating exist master characteristics in job number '{$existSnoJob->aufnr}'!",
                                ], 404);
                            } else {
                                $isInsertOrUpdate = true;
                                $insertData['created_by'] = $userName ?? null;
                                ClassCharacteristic::create($insertData);
                            }
                        } catch (\Exception $e) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => "Error occurred while inserting new master characteristics for the serial number '{$serial}', {$e->getMessage()}",
                                // 'char_data' => $char
                            ], 500);
                        }
                    }
                }
            }

            // $classChar = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();
            $modelHeading = $classChar?->zmm_heading ?? '';

            $typesToCreate = [];

            if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
            } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['MOTOR', 'PUMP'];
            } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
                $typesToCreate = ['PUMP'];
            } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
                $typesToCreate = ['MOTOR'];
            } else {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
                ], 404);
            }

            if ($isInsertOrUpdate) {
                TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                foreach ($typesToCreate as $type) {
                    TempClassCharacteristic::create([
                        'plant_id' => $plantId,
                        'machine_id' => $machineId,
                        'item_id' => $itemId,
                        'aufnr' => $jobNo,
                        'model_type' => $type,
                        'has_work_flow_id' => '2',
                        'created_by' => $userName,
                        'updated_by' => $userName,
                    ]);
                }

                // $classChar = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();
                if ($classChar) {
                    ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                        ->update([
                            'has_work_flow_id' => '2',
                            'updated_at' => now(),
                            'updated_by' => $userName,
                        ]);
                }
            }

            return response()->json([
                'status_code' => 'SUCCESS',
                'status_description' => $isInsertOrUpdate ? "Successfully updated master characteristics for the job number '{$jobNo}'." : "Failed to update master characteristics for the job number '{$jobNo}'.",
            ], 200);
        }
    }

    public function getClassChar(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        $plantCode = $request->header('plant-code');

        $workCenter = $request->header('work-center');

        $jobNumber = $request->header('job-number');

        $itemCode = $request->header('item-code');

        $modelType = $request->header('model-type');

        $serialNumber = $request->header('serial-number');

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        if (! $modelType || $modelType == null || $modelType == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model type can't be empty!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant Code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        } elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 403);
        }

        $work = Machine::where('work_center', $workCenter)->first();

        if (! $work) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        if (($itemCode == '' || $itemCode == null) && ($serialNumber == '' || $serialNumber == null)) {
            if (! $jobNumber) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number can't be empty",
                ], 404);
            } elseif (Str::length($jobNumber) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should not begin with '0'!",
                ], 404);
            }

            $job = ClassCharacteristic::where('aufnr', $jobNumber)->first();

            if (! $job) {
                return response()->json([
                    'status_code' => 'SUCCESS',
                    'status_description' => "Job number '{$jobNumber}' not found!",
                ], 404);
            }

            $jobPlant = ClassCharacteristic::where('aufnr', $jobNumber)->where('plant_id', $plantId)->first();

            if (! $jobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $jobWorkCenter = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $jobWorkCenter) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the work center '{$workCenter}'!",
                ], 404);
            }

            $columnsToShow = ['mark_status', 'marked_datetime', 'marked_physical_count', 'marked_expected_time', 'marked_by', 'man_marked_status', 'man_marked_datetime', 'man_marked_by', 'motor_marked_status', 'motor_marked_physical_count', 'motor_expected_time', 'motor_marked_datetime', 'motor_marked_by', 'pump_marked_status', 'pump_marked_physical_count', 'pump_expected_time', 'pump_marked_datetime', 'pump_marked_by', 'name_plate_marked_status', 'name_plate_expected_time', 'name_plate_marked_datetime', 'name_plate_marked_by', 'motor_pump_pumpset_status', 'winded_serial_number', 'winded_rework_status', 'motor_machine_name', 'pump_machine_name', 'name_plate_machine_name', 'part_validation_1', 'part_validation_2', 'samlight_logged_name', 'pending_released_status', 'has_work_flow_id'];

            $characteristicsColumns = ['class', 'arbid', 'gamng', 'lmnga', 'zz1_cn_bill_ord', 'zmm_amps', 'zmm_brand', 'zmm_degreeofprotection', 'zmm_delivery', 'zmm_dir_rot', 'zmm_discharge', 'zmm_discharge_max', 'zmm_discharge_min', 'zmm_duty', 'zmm_eff_motor', 'zmm_eff_pump', 'zmm_frequency', 'zmm_head', 'zmm_heading', 'zmm_head_max', 'zmm_head_minimum', 'zmm_idx_eff_mtr', 'zmm_idx_eff_pump', 'zmm_kvacode', 'zmm_maxambtemp', 'zmm_mincoolingflow', 'zmm_motorseries', 'zmm_motor_model', 'zmm_outlet', 'zmm_phase', 'zmm_pressure', 'zmm_pumpflowtype', 'zmm_pumpseries', 'zmm_pump_model', 'zmm_ratedpower', 'zmm_region', 'zmm_servicefactor', 'zmm_servicefactormaximumamps', 'zmm_speed', 'zmm_suction', 'zmm_suctionxdelivery', 'zmm_supplysource', 'zmm_temperature', 'zmm_thrustload', 'zmm_volts', 'zmm_wire', 'zmm_package', 'zmm_pvarrayrating', 'zmm_isi', 'zmm_isimotor', 'zmm_isipump', 'zmm_isipumpset', 'zmm_pumpset_model', 'zmm_stages', 'zmm_headrange', 'zmm_overall_efficiency', 'zmm_connection', 'zmm_min_bore_size', 'zmm_isireference', 'zmm_category', 'zmm_submergence', 'zmm_capacitorstart', 'zmm_capacitorrun', 'zmm_inch', 'zmm_motor_type', 'zmm_dismantle_direction', 'zmm_eff_ovrall', 'zmm_bodymoc', 'zmm_rotormoc', 'zmm_dlwl', 'zmm_inputpower', 'zmm_imp_od', 'zmm_ambtemp', 'zmm_de', 'zmm_dischargerange', 'zmm_efficiency_class', 'zmm_framesize', 'zmm_impellerdiameter', 'zmm_insulationclass', 'zmm_maxflow', 'zmm_minhead', 'zmm_mtrlofconst', 'zmm_nde', 'zmm_powerfactor', 'zmm_tagno', 'zmm_year', 'zmm_laser_name', 'zmm_logo_cp', 'zmm_logo_ce', 'zmm_logo_nsf', 'zmm_logo_eac', 'zmm_grwt_motor', 'zmm_grwt_pump', 'zmm_grwt_pset', 'zmm_newt_motor', 'zmm_newt_pump', 'zmm_newt_pset', 'zmm_operating_range', 'zmm_intake_air', 'zmm_oxygen_transfer_rate', 'zmm_air_inlet_pipesize', 'zmm_sump_depth', 'zmm_poles', 'zmm_motor_heading', 'zmm_motor_speed', 'zmm_beenote', 'zmm_beenumber', 'zmm_beestar', 'zmm_eff_ttl', 'zmm_labelperiod', 'zmm_modelyear', 'zmm_performance_factor', 'zqmm_qty', 'zmm_operating_temperature', 'zmm_axial_force'];

            $characteristicsData = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->distinct()->get($characteristicsColumns); // ->get();

            if ($characteristicsData->isEmpty()) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'No characteristics data found for the provided Plant Code, Work Center, and Job Number!',
                ], 404);
            }

            $serials = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('gernr')->get(array_merge(['gernr', 'item_id'], $columnsToShow)); // ->get(array_merge(['gernr'], $columnsToShow));

            $itemId = $serials->first()->item_id;

            $itemcode = Item::where('id', $itemId)->value('code') ?? '';

            $markedSerials = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->get(['gernr', 'mark_status']);

            $allMarked = $markedSerials->every(function ($serial) {
                return strtolower($serial->mark_status) == 'marked';
            });

            if ($allMarked) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'All serial numbers are already marked!',
                ], 404);
            }

            $serialNumbers = $serials->map(function ($serial) use ($columnsToShow) {
                $otherData = [];
                foreach ($columnsToShow as $col) {
                    $otherData[strtoupper($col)] = (string) $serial->$col ?? '';
                }

                $otherData['MARKED_BY'] = ($otherData['MARKED_BY'] == 'Admin') ? 'jothi' : $otherData['MARKED_BY'] ?? ''; // marked_by
                $otherData['MAN_MARKED_BY'] = ($otherData['MAN_MARKED_BY'] == 'Admin') ? 'jothi' : $otherData['MAN_MARKED_BY'] ?? ''; // man_marked_by
                $otherData['MOTOR_MARKED_BY'] = ($otherData['MOTOR_MARKED_BY'] == 'Admin') ? 'jothi' : $otherData['MOTOR_MARKED_BY'] ?? ''; // motor_marked_by
                $otherData['PUMP_MARKED_BY'] = ($otherData['PUMP_MARKED_BY'] == 'Admin') ? 'jothi' : $otherData['PUMP_MARKED_BY'] ?? ''; // pump_marked_by
                $otherData['NAME_PLATE_MARKED_BY'] = ($otherData['NAME_PLATE_MARKED_BY'] == 'Admin') ? 'jothi' : $otherData['NAME_PLATE_MARKED_BY'] ?? ''; // name_plate_marked_by

                // $otherData['pending_released_status'] = (string)$otherData['pending_released_status'] ?? '';
                return array_merge(['GERNR' => $serial->gernr], $otherData);
            });

            $characteristics = $characteristicsData->map(function ($char) use ($characteristicsColumns) {
                $data = [];
                foreach ($characteristicsColumns as $col) {
                    $data[strtoupper($col)] = $char->$col ?? '';
                }

                return $data;
            });

            $response = [
                'item_code' => $itemcode,
                'serial_numbers' => $serialNumbers,
                'characteristics' => $characteristics,
            ];

            return response()->json($response);

        } elseif (($itemCode != '' && $itemCode != null) || ($serialNumber != '' && $serialNumber != null)) {
            if ($modelType != 'MOTOR' && $modelType != 'PUMP' && $modelType != 'NAME_PLATE') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Unknown model type '{$modelType}' found!",
                ], 404);
            }

            if (Str::length($serialNumber) < 9) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should contain minimum 9 digits!",
                ], 404);
            } elseif (! ctype_alnum($serialNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should contain only alpha-numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should not begin with '0'!",
                ], 404);
            }

            if (Str::length($itemCode) < 6) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'Item code should contain minimum 6 digits!',
                ], 404);
            } elseif (! ctype_alnum($itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
                ], 404);
            } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
                ], 404);
            }

            $item = Item::where('code', $itemCode)->first();

            if (! $item) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found in items table!",
                ], 404);
            }

            $itemPlant = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

            if (! $itemPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
                ], 404);
            }

            $itemId = $itemPlant->id; // Item::where('code', $itemCode)->where('plant_id', $plantId)->value('id');

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for plant code '{$plantCode}'!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found with the item code '{$itemCode}'!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for work center '{$workCenter}'!",
                ], 404);
            }

            $curHead = null;
            $curHead = $serialExists?->zmm_heading;
            if (Str::contains($curHead, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                $stick = StickerMaster::where('item_id', $itemId)->first();

                if (! $stick) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                    ], 404);
                }

                $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                if (! $stickPlant) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                    ], 404);
                } else {
                    $curMvhs = trim($stickPlant?->laser_part_validation2);
                    if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                        ], 404);
                    } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => 'The MVHS master count should be between 1 to 9!', // "MVHS master count '{$curMvhs}' should contain only numeric values between 1 to 9!"
                        ], 404);
                    }
                }
            } else {
                if ($modelType == 'NAME_PLATE') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have name plate model to proceed!",
                    ], 404);
                } elseif (Str::contains($curHead, 'PUMP', ignoreCase: true) && ! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                    if ($modelType == 'MOTOR') {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Serial number '{$serialNumber}' doesn't have motor model to proceed!",
                        ], 404);
                        // } elseif ($modelType == 'PUMPSET') {
                        //     return response()->json([
                        //         'status_code' => 'ERROR',
                        //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                        //     ], 404);
                    }
                } elseif (Str::contains($curHead, 'MOTOR', ignoreCase: true)) {
                    if ($modelType == 'PUMP') {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Serial number '{$serialNumber}' doesn't have pump model to proceed!",
                        ], 404);
                        // } elseif ($modelType == 'PUMPSET') {
                        //     return response()->json([
                        //         'status_code' => 'ERROR',
                        //         'status_description' => "Serial number '{$serialNumber}' doesn't have pumpset model to proceed!",
                        //     ], 404);
                    }
                } elseif (! Str::contains($curHead, 'PUMP SET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPSET', ignoreCase: true) && ! Str::contains($curHead, 'PUMPS', ignoreCase: true)) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Serial number '{$serialNumber}' doesn't have valid model type to proceed!",
                    ], 404);
                }
            }

            $curMarkStat = $serialExists->mark_status ?? null;
            $curMotorMarkStat = $serialExists->motor_marked_status ?? null;
            $curPumpMarkStat = $serialExists->pump_marked_status ?? null;
            $curNamePlateMarkStat = $serialExists->name_plate_marked_status ?? null;

            if ($modelType == 'MOTOR' && $curMarkStat != 'Marked' && $curMotorMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Motor serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'PUMP' && $curMarkStat != 'Marked' && $curPumpMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Pump serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
            } elseif ($modelType == 'NAME_PLATE' && $curMarkStat != 'Marked' && $curNamePlateMarkStat != 'Marked') {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Name plate serial number '{$serialNumber}' doesn't marked in auto mode!",
                ], 404);
                // } elseif ($modelType == 'PUMPSET' && $curMarkStat != 'Marked') {
                //     return response()->json([
                //         'status_code' => 'ERROR',
                //         'status_description' => "Pumpset serial number '{$serialNumber}' doesn't marked in auto mode!",
                //     ], 404);
            }

            if ($serialExists->mark_status != 'Marked' && $serialExists->motor_marked_status != 'Marked' && $serialExists->pump_marked_status != 'Marked') {
                // "Serial number '{$serialNumber}' is not marked yet.<br>Please proceed with marking first.";
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' does not marked in AUTO mode! Please, close MANUAL window and proceed with AUTO mode to start laser marking..!",
                ], 404);
            }

            $characteristicsData = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            $remFields = ['id', 'plant_id', 'machine_id', 'item_id', 'gernr', 'zmm_codeclass', 'zmm_colour', 'zmm_grade', 'zmm_grwt_cable', 'zmm_grwt_pf', 'zmm_isivalve', 'zmm_isi_wc', 'zmm_length', 'zmm_license_cml_no', 'zmm_mfgmonyr', 'zmm_motoridentification', 'zmm_newt_cable', 'zmm_newt_pf', 'zmm_packtype', 'zmm_panel', 'zmm_pumpidentification', 'zmm_psettype', 'zmm_size', 'zmm_type', 'zmm_usp', 'created_at', 'updated_at', 'created_by', 'updated_by', 'deleted_at', 'is_stopped', 'stopped_datetime', 'stopped_by'];

            $filteredData = $characteristicsData->map(function ($char) use ($remFields) {
                $charArray = $char->toArray();

                // Unset only the columns present in $manFields
                foreach ($remFields as $field) {
                    unset($charArray[$field]);
                }
                // unset(
                //     $charArray['id'],
                //     $charArray['plant_id']
                // );

                $charArray['pending_released_status'] = (string) $charArray['pending_released_status'] ?? '';

                $charArray['marked_by'] = ($charArray['marked_by'] == 'Admin') ? 'jothi' : $charArray['marked_by'] ?? '';
                $charArray['man_marked_by'] = ($charArray['man_marked_by'] == 'Admin') ? 'jothi' : $charArray['man_marked_by'] ?? '';
                $charArray['motor_marked_by'] = ($charArray['motor_marked_by'] == 'Admin') ? 'jothi' : $charArray['motor_marked_by'] ?? '';
                $charArray['pump_marked_by'] = ($charArray['pump_marked_by'] == 'Admin') ? 'jothi' : $charArray['pump_marked_by'] ?? '';
                $charArray['name_plate_marked_by'] = ($charArray['name_plate_marked_by'] == 'Admin') ? 'jothi' : $charArray['name_plate_marked_by'] ?? '';

                foreach ($charArray as $key => $value) {
                    if ($value instanceof \Carbon\Carbon) {
                        $charArray[$key] = $value->timezone('Asia/Kolkata')->format('Y-m-d H:i:s');
                    } elseif (is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z$/', $value)) {
                        $charArray[$key] = \Carbon\Carbon::parse($value)
                            ->timezone('Asia/Kolkata')
                            ->format('Y-m-d H:i:s');
                    } elseif (is_null($value)) {
                        $charArray[$key] = '';
                    }
                }

                // return $charArray;
                return array_change_key_case($charArray, CASE_UPPER);
            });

            // $response = [
            //     'characteristics2' => $filteredData
            // ];
            // return response()->json($response);
            return response()->json([
                'characteristics' => $filteredData,
            ], 200);
        }
    }

    public function checkClassChar(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        $plantCode = $request->header('plant-code');

        $workCenter = $request->header('work-center');

        $jobNumber = $request->header('job-number');

        $itemCode = $request->header('item-code');

        $serialNumber = $request->header('serial-number');

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        } elseif (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 403);
        }

        $work = Machine::where('work_center', $workCenter)->first();

        if (! $work) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        if (($itemCode == '' || $itemCode == null) && ($serialNumber == '' || $serialNumber == null)) {
            if (! $jobNumber) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number can't be empty",
                ], 404);
            } elseif (Str::length($jobNumber) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should not begin with '0'!",
                ], 404);
            }

            $job = ClassCharacteristic::where('aufnr', $jobNumber)->first();

            if (! $job) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found!", // skip
                ], 404);
            }

            $jobPlant = ClassCharacteristic::where('aufnr', $jobNumber)->where('plant_id', $plantId)->first();

            if (! $jobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $jobWorkCenter = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $jobWorkCenter) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the work center '{$workCenter}'!",
                ], 404);
            } else {
                $itemId = $jobWorkCenter?->item_id;

                $item = Item::where('id', $itemId)->first();

                $itemCode = $item?->code;

                if (Str::contains($jobWorkCenter?->zmm_heading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $stick = StickerMaster::where('item_id', $itemId)->first();

                    if (! $stick) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                        ], 404);
                    }

                    $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                    if (! $stickPlant) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                        ], 404);
                    } else {
                        $curMvhs = trim($stickPlant?->laser_part_validation2);
                        if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                            ], 404);
                        } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'The MVHS master count should be between 1 to 9!',
                            ], 404);
                        }
                    }
                }
            }

            // $columnsToShow = ['mark_status', 'marked_datetime', 'marked_physical_count', 'marked_expected_time', 'marked_by', 'man_marked_status', 'man_marked_datetime', 'man_marked_by', 'motor_marked_status', 'motor_marked_physical_count', 'motor_expected_time', 'motor_marked_by', 'pump_marked_status', 'pump_marked_physical_count', 'pump_expected_time', 'pump_marked_by', 'name_plate_marked_status', 'name_plate_expected_time', 'name_plate_marked_by', 'motor_pump_pumpset_status', 'winded_serial_number', 'motor_machine_name', 'pump_machine_name', 'name_plate_machine_name', 'part_validation_1', 'part_validation_2', 'samlight_logged_name', 'pending_released_status', 'has_work_flow_id'];

            $characteristicsColumns = ['class', 'arbid', 'gamng', 'lmnga', 'zz1_cn_bill_ord', 'zmm_amps', 'zmm_brand', 'zmm_degreeofprotection', 'zmm_delivery', 'zmm_dir_rot', 'zmm_discharge', 'zmm_discharge_max', 'zmm_discharge_min', 'zmm_duty', 'zmm_eff_motor', 'zmm_eff_pump', 'zmm_frequency', 'zmm_head', 'zmm_heading', 'zmm_head_max', 'zmm_head_minimum', 'zmm_idx_eff_mtr', 'zmm_idx_eff_pump', 'zmm_kvacode', 'zmm_maxambtemp', 'zmm_mincoolingflow', 'zmm_motorseries', 'zmm_motor_model', 'zmm_outlet', 'zmm_phase', 'zmm_pressure', 'zmm_pumpflowtype', 'zmm_pumpseries', 'zmm_pump_model', 'zmm_ratedpower', 'zmm_region', 'zmm_servicefactor', 'zmm_servicefactormaximumamps', 'zmm_speed', 'zmm_suction', 'zmm_suctionxdelivery', 'zmm_supplysource', 'zmm_temperature', 'zmm_thrustload', 'zmm_volts', 'zmm_wire', 'zmm_package', 'zmm_pvarrayrating', 'zmm_isi', 'zmm_isimotor', 'zmm_isipump', 'zmm_isipumpset', 'zmm_pumpset_model', 'zmm_stages', 'zmm_headrange', 'zmm_overall_efficiency', 'zmm_connection', 'zmm_min_bore_size', 'zmm_isireference', 'zmm_category', 'zmm_submergence', 'zmm_capacitorstart', 'zmm_capacitorrun', 'zmm_inch', 'zmm_motor_type', 'zmm_dismantle_direction', 'zmm_eff_ovrall', 'zmm_bodymoc', 'zmm_rotormoc', 'zmm_dlwl', 'zmm_inputpower', 'zmm_imp_od', 'zmm_ambtemp', 'zmm_de', 'zmm_dischargerange', 'zmm_efficiency_class', 'zmm_framesize', 'zmm_impellerdiameter', 'zmm_insulationclass', 'zmm_maxflow', 'zmm_minhead', 'zmm_mtrlofconst', 'zmm_nde', 'zmm_powerfactor', 'zmm_tagno', 'zmm_year', 'zmm_laser_name', 'zmm_logo_cp', 'zmm_logo_ce', 'zmm_logo_nsf', 'zmm_logo_eac', 'zmm_grwt_motor', 'zmm_grwt_pump', 'zmm_grwt_pset', 'zmm_newt_motor', 'zmm_newt_pump', 'zmm_newt_pset', 'zmm_operating_range', 'zmm_intake_air', 'zmm_oxygen_transfer_rate', 'zmm_air_inlet_pipesize', 'zmm_sump_depth', 'zmm_poles', 'zmm_motor_heading', 'zmm_motor_speed', 'zmm_beenote', 'zmm_beenumber', 'zmm_beestar', 'zmm_eff_ttl', 'zmm_labelperiod', 'zmm_modelyear', 'zmm_performance_factor', 'zqmm_qty', 'zmm_operating_temperature', 'zmm_axial_force'];

            $characteristicsData = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->distinct()->get($characteristicsColumns); // ->get();

            if ($characteristicsData->isEmpty()) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'No characteristics data found for the provided Plant Code, Work Center, and Job Number!',
                ], 404);
            }

            // $serials = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('gernr')->get(array_merge(['gernr', 'item_id'], $columnsToShow)); //->get(array_merge(['gernr'], $columnsToShow));

            // $itemId = $serials->first()->item_id;
            // $itemcode = Item::where('id', $itemId)->value('code') ?? '';

            $markedSerials = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->get(['gernr', 'mark_status']);

            $allMarked = $markedSerials->every(function ($serial) {
                return strtolower($serial->mark_status) == 'marked';
            });

            if ($allMarked) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'All serial numbers are already marked!', // skip
                ], 404);
            } else {
                return response()->json([
                    'status_code' => 'SUCCESS',
                    'status_description' => 'Has some pending serial numbers to mark!',
                ], 200);
            }
        } elseif ((($itemCode != '' && $itemCode != null) || ($serialNumber != '' && $serialNumber != null)) && $jobNumber != '' && $jobNumber != null) {
            // return response()->json([
            //     'status_code' => "ERROR",
            //     'status_description' => "Item Code or Serial Number should be empty while checking job number characteristics!"
            // ], 404);
            if (! $jobNumber) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number can't be empty",
                ], 404);
            } elseif (Str::length($jobNumber) < 7) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain minimum 7 digits!",
                ], 404);
            } elseif (! is_numeric($jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should contain only numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9]\d{6,}$/', $jobNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' should not begin with '0'!",
                ], 404);
            }

            if (Str::length($serialNumber) < 9) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should contain minimum 9 digits!",
                ], 404);
            } elseif (! ctype_alnum($serialNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should contain only alpha-numeric values!",
                ], 404);
            } elseif (! preg_match('/^[1-9][a-zA-Z0-9]{8,}$/', $serialNumber)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' should not begin with '0'!",
                ], 404);
            }

            if (Str::length($itemCode) < 6) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'Item code should contain minimum 6 digits!',
                ], 404);
            } elseif (! ctype_alnum($itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
                ], 404);
            } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
                ], 404);
            }

            $job = ClassCharacteristic::where('aufnr', $jobNumber)->first();

            if (! $job) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found!", // skip
                ], 404);
            }

            $jobPlant = ClassCharacteristic::where('aufnr', $jobNumber)->where('plant_id', $plantId)->first();

            if (! $jobPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the plant code '{$plantCode}'!",
                ], 404);
            }

            $jobWorkCenter = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $jobWorkCenter) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Job number '{$jobNumber}' not found for the work center '{$workCenter}'!",
                ], 404);
            }

            $item = Item::where('code', $itemCode)->first();

            if (! $item) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found in items table!",
                ], 404);
            }

            $itemPlant = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

            if (! $itemPlant) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
                ], 404);
            }

            $itemId = $itemPlant->id; // Item::where('code', $itemCode)->where('plant_id', $plantId)->value('id');

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for plant code '{$plantCode}'!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found with the item code '{$itemCode}'!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for work center '{$workCenter}'!",
                ], 404);
            }

            $serialExists = ClassCharacteristic::where('gernr', $serialNumber)->where('item_id', $itemId)->where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $serialExists) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Serial number '{$serialNumber}' not found for job number '{$jobNumber}'!",
                ], 404);
            } else {
                if (Str::contains($serialExists?->zmm_heading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
                    $stick = StickerMaster::where('item_id', $itemId)->first();

                    if (! $stick) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found in sticker masters table!",
                        ], 404);
                    }

                    $stickPlant = StickerMaster::where('item_id', $itemId)->where('plant_id', $plantId)->first();

                    if (! $stickPlant) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in sticker masters table!",
                        ], 404);
                    } else {
                        $curMvhs = trim($stickPlant?->laser_part_validation2);
                        if ($curMvhs == null || $curMvhs == '' || ! is_numeric($curMvhs) || Str::length($curMvhs) <= 0) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'Invalid MVHS master count found in sticker masters table!',
                            ], 404);
                        } elseif (! preg_match('/^[1-9]$/', $curMvhs)) {
                            return response()->json([
                                'status_code' => 'ERROR',
                                'status_description' => 'The MVHS master count should be between 1 to 9!',
                            ], 404);
                        }
                    }
                }
            }

            $markedSerials = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->get(['gernr', 'mark_status']);

            $allMarked = $markedSerials->every(function ($serial) {
                return strtolower($serial->mark_status) == 'marked';
            });

            if ($allMarked) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'All serial numbers are already marked!', // skip
                ], 404);
            }

            // if ($serialExists->mark_status != 'Marked' && $serialExists->mark_status != 'marked')
            // {
            //     return response()->json([
            //         'status_code' => "ERROR",
            //         'status_description' => "Serial number '{$serialNumber}' does not marked in AUTO mode! Please, close MANUAL window and proceed with AUTO mode to start laser marking..!",
            //     ], 404);
            // }

            // $columnsToShow = ['mark_status', 'marked_datetime', 'marked_physical_count', 'marked_expected_time', 'marked_by', 'man_marked_status', 'man_marked_datetime', 'man_marked_by', 'motor_marked_status', 'motor_marked_physical_count', 'motor_expected_time', 'motor_marked_by', 'pump_marked_status', 'pump_marked_physical_count', 'pump_expected_time', 'pump_marked_by', 'name_plate_marked_status', 'name_plate_expected_time', 'name_plate_marked_by', 'motor_pump_pumpset_status', 'winded_serial_number', 'motor_machine_name', 'pump_machine_name', 'name_plate_machine_name', 'part_validation_1', 'part_validation_2', 'samlight_logged_name', 'pending_released_status', 'has_work_flow_id'];

            // $characteristicsColumns = ['class', 'arbid', 'gamng', 'lmnga', 'zz1_cn_bill_ord', 'zmm_amps', 'zmm_brand', 'zmm_degreeofprotection', 'zmm_delivery', 'zmm_dir_rot', 'zmm_discharge', 'zmm_discharge_max', 'zmm_discharge_min', 'zmm_duty', 'zmm_eff_motor', 'zmm_eff_pump', 'zmm_frequency', 'zmm_head', 'zmm_heading', 'zmm_head_max', 'zmm_head_minimum', 'zmm_idx_eff_mtr', 'zmm_idx_eff_pump', 'zmm_kvacode', 'zmm_maxambtemp', 'zmm_mincoolingflow', 'zmm_motorseries', 'zmm_motor_model', 'zmm_outlet', 'zmm_phase', 'zmm_pressure', 'zmm_pumpflowtype', 'zmm_pumpseries', 'zmm_pump_model', 'zmm_ratedpower', 'zmm_region', 'zmm_servicefactor', 'zmm_servicefactormaximumamps', 'zmm_speed', 'zmm_suction', 'zmm_suctionxdelivery', 'zmm_supplysource', 'zmm_temperature', 'zmm_thrustload', 'zmm_volts', 'zmm_wire', 'zmm_package', 'zmm_pvarrayrating', 'zmm_isi', 'zmm_isimotor', 'zmm_isipump', 'zmm_isipumpset', 'zmm_pumpset_model', 'zmm_stages', 'zmm_headrange', 'zmm_overall_efficiency', 'zmm_connection', 'zmm_min_bore_size', 'zmm_isireference', 'zmm_category', 'zmm_submergence', 'zmm_capacitorstart', 'zmm_capacitorrun', 'zmm_inch', 'zmm_motor_type', 'zmm_dismantle_direction', 'zmm_eff_ovrall', 'zmm_bodymoc', 'zmm_rotormoc', 'zmm_dlwl', 'zmm_inputpower', 'zmm_imp_od', 'zmm_ambtemp', 'zmm_de', 'zmm_dischargerange', 'zmm_efficiency_class', 'zmm_framesize', 'zmm_impellerdiameter', 'zmm_insulationclass', 'zmm_maxflow', 'zmm_minhead', 'zmm_mtrlofconst', 'zmm_nde', 'zmm_powerfactor', 'zmm_tagno', 'zmm_year', 'zmm_laser_name', 'zmm_logo_cp', 'zmm_logo_ce', 'zmm_logo_nsf', 'zmm_logo_eac', 'zmm_beenote', 'zmm_beenumber', 'zmm_beestar', 'zmm_codeclass', 'zmm_colour', 'zmm_grade', 'zmm_grwt_pset', 'zmm_grwt_cable', 'zmm_grwt_motor', 'zmm_grwt_pf', 'zmm_grwt_pump', 'zmm_isivalve', 'zmm_isi_wc', 'zmm_labelperiod', 'zmm_length', 'zmm_license_cml_no', 'zmm_mfgmonyr', 'zmm_modelyear', 'zmm_motoridentification', 'zmm_newt_pset', 'zmm_newt_cable', 'zmm_newt_motor', 'zmm_newt_pf', 'zmm_newt_pump', 'zmm_packtype', 'zmm_panel', 'zmm_performance_factor', 'zmm_pumpidentification', 'zmm_psettype', 'zmm_size', 'zmm_eff_ttl', 'zmm_type', 'zmm_usp', 'zmm_operating_range', 'zmm_intake_air', 'zmm_oxygen_transfer_rate', 'zmm_air_inlet_pipesize', 'zmm_sump_depth', 'zmm_poles', 'zmm_motor_heading', 'zmm_motor_speed', 'zqmm_qty', 'zmm_operating_temperature', 'zmm_axial_force'];

            // $characteristicsData = ClassCharacteristic::where('aufnr', $jobNumber)->where('machine_id', $machineId)->where('plant_id', $plantId)->distinct()->get($characteristicsColumns); // ->get();

            // if ($characteristicsData->isEmpty()) {
            //     return response()->json([
            //         'status_code' => "ERROR",
            //         'status_description' => 'No characteristics data found for the provided Plant Code, Work Center, and Job Number!'
            //     ], 404);
            // }

            return response()->json([
                'ZMM_HEADING' => $serialExists->zmm_heading ?? '',
                'MARK_STATUS' => $serialExists->mark_status ?? '',
                'MARKED_DATETIME' => $serialExists->marked_datetime ?? '',
                'MARKED_PHYSICAL_COUNT' => $serialExists->marked_physical_count ?? '0',
                'MARKED_EXPECTED_TIME' => $serialExists->marked_expected_time ?? '0',
                'MARKED_BY' => ($serialExists->marked_by == 'Admin') ? 'jothi' : $serialExists->marked_by ?? '',
                'MAN_MARKED_STATUS' => $serialExists->man_marked_status ?? '0',
                'MAN_MARKED_DATETIME' => $serialExists->man_marked_datetime ?? '',
                'MAN_MARKED_BY' => ($serialExists->man_marked_by == 'Admin') ? 'jothi' : $serialExists->man_marked_by ?? '',
                'MOTOR_MARKED_STATUS' => $serialExists->motor_marked_status ?? '',
                'MOTOR_MARKED_PHYSICAL_COUNT' => $serialExists->motor_marked_physical_count ?? '0',
                'MOTOR_EXPECTED_TIME' => $serialExists->motor_expected_time ?? '0',
                'MOTOR_MARKED_DATETIME' => $serialExists->motor_marked_datetime ?? '',
                'MOTOR_MARKED_BY' => ($serialExists->motor_marked_by == 'Admin') ? 'jothi' : $serialExists->motor_marked_by ?? '',
                'PUMP_MARKED_STATUS' => $serialExists->pump_marked_status ?? '',
                'PUMP_MARKED_PHYSICAL_COUNT' => $serialExists->pump_marked_physical_count ?? '0',
                'PUMP_EXPECTED_TIME' => $serialExists->pump_expected_time ?? '0',
                'PUMP_MARKED_DATETIME' => $serialExists->pump_marked_datetime ?? '',
                'PUMP_MARKED_BY' => ($serialExists->pump_marked_by == 'Admin') ? 'jothi' : $serialExists->pump_marked_by ?? '',
                'NAME_PLATE_MARKED_STATUS' => $serialExists->name_plate_marked_status ?? '',
                'NAME_PLATE_EXPECTED_TIME' => $serialExists->name_plate_expected_time ?? '0',
                'NAME_PLATE_MARKED_DATETIME' => $serialExists->name_plate_marked_datetime ?? '',
                'NAME_PLATE_MARKED_BY' => ($serialExists->name_plate_marked_by == 'Admin') ? 'jothi' : $serialExists->name_plate_marked_by ?? '',
                'MOTOR_PUMP_PUMPSET_STATUS' => $serialExists->motor_pump_pumpset_status ?? '',
                'WINDED_SERIAL_NUMBER' => $serialExists->winded_serial_number ?? '',
                'WINDED_REWORK_STATUS' => $serialExists->winded_rework_status ?? '0',
                'MOTOR_MACHINE_NAME' => $serialExists->motor_machine_name ?? '',
                'PUMP_MACHINE_NAME' => $serialExists->pump_machine_name ?? '',
                'NAME_PLATE_MACHINE_NAME' => $serialExists->name_plate_machine_name ?? '',
                'PART_VALIDATION_1' => $serialExists->part_validation_1 ?? '',
                'PART_VALIDATION_2' => $serialExists->part_validation_2 ?? '',
                'PENDING_RELEASED_STATUS' => (string) $serialExists->pending_released_status ?? '0',
                'SAMLIGHT_LOGGED_NAME' => $serialExists->samlight_logged_name ?? '',
                'HAS_WORK_FLOW_ID' => $serialExists->has_work_flow_id ?? '0',
            ], 200);
        }
    }

    public function getCharMaster(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');
        $header_auth = $request->header('Authorization');
        $expectedToken = $expectedUser.':'.$expectedPw;

        if ('Bearer '.$expectedToken != $header_auth) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $plantCode = $request->header('plant-code');
        $itemCode = $request->header('item-code');
        $lineName = $request->header('line-name');
        $workCenter = $request->header('work-center');

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        } elseif ($itemCode == null || $itemCode == '' || ! $itemCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        } elseif ($lineName == null || $lineName == '' || ! $lineName) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line name can't be empty!",
            ], 404);
        } elseif ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();

        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;
        $plantName = $plant->name;

        $item = Item::where('code', $itemCode)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item Code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();

        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item Code '{$itemCode}' not found for the plant name '{$plantName}' in items table!",
            ], 404);
        }

        $itemId = $item->id;

        $line = Line::where('name', $lineName)->first();

        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line name '{$lineName}' not found in lines table!",
            ], 404);
        }

        $line = Line::where('name', $lineName)->where('plant_id', $plantId)->first();

        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line name '{$lineName}' not found for the plant name '{$plantName}' in lines table!",
            ], 404);
        }

        $lineId = $line->id;

        $machine = Machine::where('work_center', $workCenter)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant name '{$plantName}' in machines table!",
            ], 404);
        }

        $machine = Machine::where('line_id', $lineId)->where('work_center', $workCenter)->where('plant_id', $plantId)->first();

        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' is not mapped for the given line name '{$lineName}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        // $description = $item ? $item->description : '';

        // $uom = $item ? $item->uom : '';

        // $category = $item ? $item->category : '';

        $charMasters = ProductCharacteristicsMaster::with('workGroupMaster')->where('item_id', $itemId)->where('line_id', $lineId)->where('machine_id', $machineId)->where('plant_id', $plantId)->get(); // ->select(['name', 'characteristics_type', 'inspection_type', 'lower', 'middle', 'upper', 'work_group_master_id'])

        if ($charMasters->count() <= 0) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Characteristics not found for the plant name '{$plantName}' in product master table!",
            ], 404);
        } else {
            if ($charMasters->count() == 1) {
                $charMasters = ProductCharacteristicsMaster::with('workGroupMaster')->where('item_id', $itemId)->where('line_id', $lineId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

                // $workGroup = WorkGroupMaster::find($charMasters->work_group_master_id);
                // $workGroupName = $workGroup?->name ?? '';

                $output = [
                    'work_group_master' => $charMasters?->workGroupMaster->name ?? '', // $workGroupName ?? '',
                    'name' => $charMasters?->name ?? '',
                    'characteristics_type' => $charMasters?->characteristics_type ?? '',
                    'inspection_type' => $charMasters?->inspection_type ?? '',
                    'lower' => (string) $charMasters?->lower ?? '',
                    'middle' => (string) $charMasters?->middle ?? '',
                    'upper' => (string) $charMasters?->upper ?? '',
                ];
            } else {
                $output = $charMasters->map(function ($charMast) {
                    $charMaster = [
                        'work_group_master' => $charMast?->workGroupMaster->name ?? '', // optional($charMast->workGroupMaster)->name ?? '',
                        'name' => $charMast?->name ?? '',
                        'characteristics_type' => $charMast?->characteristics_type ?? '',
                        'inspection_type' => $charMast?->inspection_type ?? '',
                        'lower' => (string) $charMast?->lower ?? '',
                        'middle' => (string) $charMast?->middle ?? '',
                        'upper' => (string) $charMast?->upper ?? '',
                    ];

                    return $charMaster;
                });
            }
        }

        return response()->json($output, 200);
    }

    public function storeCharValues(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');
        $headerAuth = $request->header('Authorization');
        $expectedToken = 'Bearer '.$expectedUser.':'.$expectedPw;

        if ($headerAuth != $expectedToken) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $plantCode = $request->header('plant-code');
        $itemCode = $request->header('item-code');
        $lineName = $request->header('line-name');
        $workCenter = $request->header('work-center');

        if ($plantCode == null || $plantCode == '' || ! $plantCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 400);
        } elseif (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        $plant = Plant::where('code', $plantCode)->first();
        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;
        $plantName = $plant->name;

        if ($lineName == null || $lineName == '' || ! $lineName) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line name can't be empty!",
            ], 404);
        }

        $line = Line::where('name', $lineName)->first();
        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line '{$lineName}' not found in lines table!",
            ], 404);
        }

        $line = Line::where('name', $lineName)->where('plant_id', $plantId)->first();
        if (! $line) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Line '{$lineName}' not found for the plant name '{$plantName}' in lines table!",
            ], 404);
        }

        $lineId = $line->id;

        if ($itemCode == null || $itemCode == '' || ! $itemCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->first();
        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item Code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();
        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant name '{$plantName}' in items table!",
            ], 404);
        }

        $itemId = $item->id;

        if ($workCenter == null || $workCenter == '' || ! $workCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant name '{$plantName}' in machines table!",
            ], 404);
        }

        $machine = Machine::where('line_id', $lineId)->where('work_center', $workCenter)->where('plant_id', $plantId)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' is not mapped for the given line name '{$lineName}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        $data = $request->all();

        $processOrder = $data['process_order'] ?? '';
        $coilNo = $data['coil_number'] ?? '';
        $status = $data['status'] ?? '';
        $obsValue = $data['observed_value'] ?? '';
        $createdBy = $data['created_by'] ?? '';

        if ($processOrder == null || $processOrder == '' || ! $processOrder) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Process order can't be empty!",
            ], 404);
        } elseif (Str::length($processOrder) < 9) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Process order '{$processOrder}' should contain minimum 9 digits!",
            ], 404);
        }

        if ($coilNo == null || $coilNo == '' || ! $coilNo) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Coil number can't be empty!",
            ], 404);
        } elseif (! is_numeric($coilNo)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Coil number '{$coilNo}' should contain only numeric values!",
            ], 404);
        } elseif (Str::length($coilNo) > 1 && ! Str::contains($coilNo, '.') && ! preg_match('/^[1-9][0-9]*$/', $coilNo)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Coil number '{$coilNo}' should not begin with '0'!",
            ], 404);
        }

        if ($status == null || $status == '' || ! $status) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Status can't be empty!",
            ], 404);
        } elseif (! in_array($status, ['Ok', 'NotOk'], true)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Status must be either 'Ok' or 'NotOk'!",
            ], 404);
        }

        if ($obsValue == null || $obsValue == '' || ! $obsValue) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Observed value can't be empty!",
            ], 404);
        }

        if ($createdBy == null || $createdBy == '' || ! $createdBy) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Created by can't be empty!",
            ], 404);
        }

        $existing = CharacteristicValue::where('process_order', $processOrder)->where('item_id', '!=', $itemId)->where('plant_id', $plantId)->first();

        if ($existing) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Process order '{$processOrder}' already has item_code '{$existing->item->code}' for the plant name '{$plantName}'!",
            ], 404);
        }

        $existing = CharacteristicValue::where('process_order', $processOrder)->where('coil_number', $coilNo)->where('plant_id', $plantId)->first();

        if ($existing) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Process order '{$processOrder}' with coil number '{$coilNo}' already exist for the plant name '{$plantName}'!",
            ], 404);
        }

        CharacteristicValue::create([
            'plant_id' => $plantId,
            'line_id' => $lineId,
            'item_id' => $itemId,
            'machine_id' => $machineId,
            'process_order' => $processOrder,
            'coil_number' => $coilNo,
            'status' => $status,
            'observed_value' => $obsValue,
            'created_by' => $createdBy,
        ]);

        return response()->json([
            'status_code' => 'SUCCESS',
            'status_description' => 'Characteristics values inserted successfully.',
        ], 200);
    }

    /**
     * Display the specified resource from storage.
     */
    public function test(Request $request)
    {
        return response('Laser Routing Data Updated.', 200)
            ->header('Content-Type', 'text/plain');
    }

    public function storeLaserRequestChar(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $headerAuth = $request->header('Authorization');
        $expectedToken = 'Bearer '.$expectedUser.':'.$expectedPw;

        if ($headerAuth != $expectedToken) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');

        $charField = $request->header('characteristic-field');

        $file = $request->file('file');
        $json = $request->input('data');
        $data = json_decode($json, true);

        $plantCode = $data['plant_code'] ?? '';
        $workCenter = $data['work_center'] ?? '';
        $machineName = $data['machine_name'] ?? '';
        $jobNo = $data['aufnr'] ?? '';
        $itemCode = $data['item_code'] ?? '';
        $characteristics = $data['requested_characteristics'] ?? [];
        $templateCharacteristics = $data['template_characteristics'] ?? [];
        // $requested = $data['requested_characteristics'][0] ?? [];
        $modelType = strtoupper($request->header('model-type'));
        $modelHeading = $request->header('model-heading');
        $requestType = $request->header('request-type');

        Log::info("Request {$requestType} POST API >>", ['user-name' => $userName, 'characteristic-field' => $charField, 'post-data' => $data]);

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        if (! $plantCode || $plantCode == null || $plantCode == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 404);
        } elseif (! $itemCode || $itemCode == null || $itemCode == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (! $workCenter || $workCenter == null || $workCenter == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (! $jobNo || $jobNo == null || $jobNo == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number can't be empty!",
            ], 404);
        } elseif (! $machineName || $machineName == null || $machineName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name can't be empty!",
            ], 404);
        } elseif (! $modelType || $modelType == null || $modelType == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model type can't be empty!",
            ], 404);
        } elseif (! $modelHeading || $modelHeading == null || $modelHeading == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model heading can't be empty!",
            ], 404);
        } elseif (! $requestType || $requestType == null || $requestType == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Request type can't be empty!",
            ], 404);
        }

        if ($charField == null || $charField == '' || $charField == 'nil') {
            $charField = 'NIL';
        }

        if (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        }

        if (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        if (Str::length($jobNo) < 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' should contain minimum 7 digits!",
            ], 404);
        } elseif (! is_numeric($jobNo)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' should contain only numeric values!",
            ], 404);
        }

        if ($requestType != 'Characteristic' && $requestType != 'Quality') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown request type '{$requestType}' found!",
            ], 404);
        } elseif ($requestType == 'Characteristic') {
            if ($request->hasFile('file')) {
                $extension = strtolower($file->getClientOriginalExtension());

                if ($extension != 'pdf' && $extension != 'PDF') {
                    return response()->json([
                        'status' => 'ERROR',
                        'status_description' => "Only .PDF files are allowed for request type '{$requestType}'!",
                    ], 404);
                } elseif ($file && $file->getSize() > 1024 * 1024) {  // 1 MB in bytes
                    return response()->json([
                        'status' => 'ERROR',
                        'status_description' => 'File size must not exceed 1 MB (Megabyte).',
                    ], 404);
                }
            }
        } elseif ($requestType == 'Quality') {
            if ($request->hasFile('file')) {
                $extension = strtolower($file->getClientOriginalExtension());

                if ($extension != 'png' && $extension != 'PNG') {
                    return response()->json([
                        'status' => 'ERROR',
                        'status_description' => "Only .PNG files are allowed for request type '{$requestType}'!",
                    ], 404);
                } elseif ($file && $file->getSize() > 50 * 1024) {
                    return response()->json([
                        'status' => 'ERROR',
                        'status_description' => 'File size must not exceed 50 KB (Kilobyte).',
                    ], 404);
                }
            } else {
                return response()->json([
                    'status' => 'ERROR',
                    'status_description' => 'Quality approval image (.png) not found!',
                ], 404);
            }
        }

        if ($modelType != 'MOTOR' && $modelType != 'PUMP' && $modelType != 'NAME_PLATE') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown model type '{$modelType}' found!",
            ], 404);
        }

        $typesToCreate = [];

        if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
            $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
        } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
            $typesToCreate = ['MOTOR', 'PUMP'];
        } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
            $typesToCreate = ['PUMP'];
        } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
            $typesToCreate = ['MOTOR'];
        } else {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
            ], 404);
        }

        if (! in_array($modelType, $typesToCreate, true)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model type '{$modelType}' does not match with the model heading '{$modelHeading}'!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();
        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 403);
        }

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 403);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' does not have rights!",
            ], 403);
        }

        $machine = Machine::where('work_center', $workCenter)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        $iCode = Item::where('code', $itemCode)->first();
        if (! $iCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();
        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
            ], 404);
        }

        $itemId = $item->id;

        $pCode = CharacteristicApproverMaster::where('plant_id', $plantId)->first();
        if (! $pCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in approver master!",
            ], 404);
        }

        $wCenter = CharacteristicApproverMaster::where('machine_id', $machineId)->first();
        if (! $wCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in approver master!",
            ], 404);
        }

        $wCenterAgaPlant = CharacteristicApproverMaster::where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $wCenterAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $mName = CharacteristicApproverMaster::where('machine_name', $machineName)->first();
        if (! $mName) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' not found in approver master!",
            ], 404);
        }

        $mNameAgaPlant = CharacteristicApproverMaster::where('machine_name', $machineName)->where('plant_id', $plantId)->first();
        if (! $mNameAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cField = CharacteristicApproverMaster::where('characteristic_field', $charField)->first();
        if (! $cField) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found in approver master!",
            ], 404);
        }

        $cFieldAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('plant_id', $plantId)->first();
        if (! $cFieldAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $mNameAndWorkCenter = CharacteristicApproverMaster::where('machine_name', $machineName)->where('machine_id', $machineId)->first();
        if (! $mNameAndWorkCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' and work center '{$workCenter}' not found in approver master!",
            ], 404);
        }

        $mNameAndWorkCenterAgaPlant = CharacteristicApproverMaster::where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $mNameAndWorkCenterAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' and work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCent = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_id', $machineId)->first();
        if (! $cFieldAndWorkCent) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the work center '{$workCenter}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCentAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $cFieldAndWorkCentAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' and work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndMach = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->first();
        if (! $cFieldAndMach) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the machine name '{$machineName}' in approver master!",
            ], 404);
        }

        $cFieldAndMachAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->where('plant_id', $plantId)->first();
        if (! $cFieldAndMachAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' and machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCentAndMachAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $cFieldAndWorkCentAndMachAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', and machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $classRow = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

        if ($classRow) {
            $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Characteristic');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            $requestQual = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Quality');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();

            foreach ($requestQual as $row) {
                $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved') ? '0' : '1';

                TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $workFlowStatus,
                        'updated_by' => $userName,
                    ]);
            }

            $tempClassChars = TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            if (! $requestChars->isEmpty()) {
                $hasCharPending = false;
                $hasQualPending = false;
                $allCharApproved = true;
                $allQualApproved = true;

                foreach ($requestChars as $row) {
                    $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                    if (! $isApproved) {
                        $allCharApproved = false;
                        $hasCharPending = true;
                        break;
                    }
                }

                if ($hasCharPending) {
                    $newValue = '3';
                    TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();
                    foreach ($typesToCreate as $type) {
                        TempClassCharacteristic::create([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '2',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ]);
                    }
                } elseif (! $tempClassChars->isEmpty()) {
                    foreach ($tempClassChars as $temp) {
                        if ($temp->has_work_flow_id == '1' || $temp->has_work_flow_id == '2') {
                            $hasQualPending = true;
                            $allQualApproved = false;
                            break;
                        }

                        if ($temp->has_work_flow_id == '0') {
                            $allQualApproved = true;
                        }
                    }

                    if ($hasQualPending) {
                        $newValue = '2';
                    } elseif ($allQualApproved) {
                        $newValue = '0';
                    }
                } elseif ($allCharApproved) {
                    $newValue = '0';
                }

                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $newValue,
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);

                if ($requestType == 'Quality' && $hasCharPending) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Characteristic approval is already pending for the job number '{$jobNo}'!",
                    ], 404);
                }
            } elseif (! $tempClassChars->isEmpty()) {
                $hasQualPending = false;
                $allQualApproved = true;

                foreach ($tempClassChars as $temp) {
                    if ($temp->has_work_flow_id == '1' || $temp->has_work_flow_id == '2') {
                        $hasQualPending = true;
                        $allQualApproved = false;
                        break;
                    }

                    if ($temp->has_work_flow_id == '0') {
                        $allQualApproved = true;
                    }
                }

                if ($hasQualPending) {
                    $newValue = '2';
                } elseif ($allQualApproved) {
                    $newValue = '0';
                }

                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $newValue,
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);
            } else {
                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => '0',
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);
            }
        } else {
            $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Characteristic');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            $requestQual = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Quality');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();

            foreach ($requestQual as $row) {
                $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved') ? '0' : '1';

                TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $workFlowStatus,
                        'updated_by' => $userName,
                    ]);
            }

            if (! $requestChars->isEmpty()) {
                $hasCharPending = false;

                foreach ($requestChars as $row) {
                    $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                    if (! $isApproved) {
                        $hasCharPending = true;
                        break;
                    }
                }

                if ($hasCharPending) {
                    TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                    foreach ($typesToCreate as $type) {
                        TempClassCharacteristic::create([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '2',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ]);
                    }

                    if ($requestType == 'Quality') {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Characteristic approval is already pending for the job number '{$jobNo}'!",
                        ], 404);
                    }
                }
            }
        }

        $pendingCharacteristics = [];
        $unknownCharacteristics = [];
        $appTypExist = null;

        if (! empty($characteristics)) {
            $appTypExist = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('approver_type', $requestType)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            if (! $appTypExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', machine name '{$machineName}', and plant code '{$plantCode}' not found for the approver type 'Characteristic' in approver master!",
                ], 404);
            }

            $charId = $appTypExist->id;
            $columns = Schema::getColumnListing('class_characteristics');

            foreach ($characteristics as $char) {
                $charNameUpp = strtoupper($char['characteristic_name']) ?? null;
                $charNameLow = strtolower($char['characteristic_name']) ?? null;
                $pendingExists = RequestCharacteristic::where('aufnr', $jobNo)->where('characteristic_name', $charNameUpp)
                    ->whereHas('approver', function ($query) use ($requestType) {
                        $query->where('approver_type', $requestType);
                    })->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

                if (! in_array($charNameLow, $columns, true)) {
                    $unknownCharacteristics[] = $charNameUpp;
                }

                if ($pendingExists) {

                    $app1 = $pendingExists->approver_status1 ?? null;
                    $app2 = $pendingExists->approver_status2 ?? null;
                    $app3 = $pendingExists->approver_status3 ?? null;

                    if ($app1 != 'Approved' && $app2 != 'Approved' && $app3 != 'Approved' && $app1 != 'Rejected' && $app2 != 'Rejected' && $app3 != 'Rejected') {
                        $pendingCharacteristics[] = $charNameUpp;
                    }
                }
            }

            $uniquePendChars = array_unique($pendingCharacteristics);

            if (! empty($uniquePendChars)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'Characteristic approval is already pending for the following request characteristics : '.implode(', ', $uniquePendChars).'.', // skip
                ], 404);
            }

            $uniqueUnkChars = array_unique($unknownCharacteristics);

            if (! empty($uniqueUnkChars)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => 'Unknown characteristic fields found : '.implode(', ', $uniqueUnkChars).'.',
                ], 404);
            }

            try {
                $workFlowIds = [];

                $year = now()->format('y');
                $month = now()->format('m');
                $date = now()->format('d');
                $prefix = "WF-{$year}{$month}{$date}-";

                $lastWorkflow = RequestCharacteristic::where('work_flow_id', 'like', "{$prefix}%")->orderByDesc('work_flow_id')->first(); // ->where('machine_id', $machineId)->where('plant_id', $plantId)

                if ($lastWorkflow) {
                    $lastSerial = substr($lastWorkflow->work_flow_id, strlen($prefix));
                    $nextSerial = str_pad(
                        intval($lastSerial) + 1,
                        4,
                        '0',
                        STR_PAD_LEFT
                    );
                } else {
                    $nextSerial = '0001';
                }

                $workflowId = "{$prefix}{$nextSerial}";

                foreach ($characteristics as $char) {
                    $charNameUpp = strtoupper($char['characteristic_name']) ?? null;
                    RequestCharacteristic::create([
                        'plant_id' => $plantId,
                        'machine_id' => $machineId,
                        'item_id' => $itemId,
                        'model_type' => $modelType,
                        'characteristic_approver_master_id' => $charId,
                        'aufnr' => $jobNo,
                        'characteristic_name' => $charNameUpp, // strtolower
                        'current_value' => $char['current_value'],
                        'update_value' => $char['update_value'],
                        'created_by' => $userName,
                        'work_flow_id' => $workflowId,
                    ]);

                    $workFlowIds[$charNameUpp] = (string) $workflowId; // $record->work_flow_id;
                }

                TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                foreach ($typesToCreate as $type) {
                    TempClassCharacteristic::create([
                        'plant_id' => $plantId,
                        'machine_id' => $machineId,
                        'item_id' => $itemId,
                        'aufnr' => $jobNo,
                        'model_type' => $type,
                        'has_work_flow_id' => '2',
                        'created_by' => $userName,
                        'updated_by' => $userName,
                    ]);
                }

                $classChar = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

                if ($classChar) {
                    ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                        ->update([
                            'has_work_flow_id' => '3',
                            'updated_at' => now(),
                            'updated_by' => $userName,
                        ]);
                }

                if ($request->hasFile('file')) {
                    $extension = strtolower($file->getClientOriginalExtension());
                    $filename = $workflowId.'.'.$extension;

                    // if ($extension != 'pdf' && $extension != 'PDF') {
                    //     return response()->json([
                    //         'status' => 'ERROR',
                    //         'status_description' => 'Only .PDF files are allowed.',
                    //     ], 404);
                    // } elseif ($file && $file->getSize() > 1024 * 1024) {  // 1 MB in bytes
                    //     return response()->json([
                    //         'status' => 'ERROR',
                    //         'status_description' => 'File size must not exceed 1 MB',
                    //     ], 404);
                    // }

                    $filePath = $file->storeAs(
                        'uploads/LaserDocs',
                        $filename,
                        'local'
                    );

                    $filePath = "uploads/LaserDocs/{$filename}";

                    if (! Storage::disk('local')->exists($filePath)) {
                        RequestCharacteristic::where('work_flow_id', $workflowId)->where('plant_id', $plantId)->forceDelete();

                        return response()->json([
                            'status' => 'ERROR',
                            'status_description' => "Document upload failed for Characteristic Work Flow ID : '{$workflowId}'",
                        ], 404);
                    }
                }

                return response()->json([
                    'work_flow_ids' => [$workFlowIds],
                ], 200);

            } catch (\Exception $e) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => $e->getMessage(),
                ], 500);
            }
        } else {
            $appTypExist = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('approver_type', $requestType)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            if (! $appTypExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', machine name '{$machineName}', and plant code '{$plantCode}' not found for the approver type 'Quality' in approver master!",
                ], 404);
            }

            $charId = $appTypExist->id;

            $pendingExists = RequestCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) use ($requestType) {
                    $query->where('approver_type', $requestType);
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();
            // ->where(function ($query) {
            //     $query->whereNull('characteristic_name')->orWhere('characteristic_name', '');
            // })

            if ($pendingExists) {
                $app1 = $pendingExists->approver_status1 ?? null;
                $app2 = $pendingExists->approver_status2 ?? null;
                $app3 = $pendingExists->approver_status3 ?? null;

                if ($app1 != 'Approved' && $app2 != 'Approved' && $app3 != 'Approved' && $app1 != 'Rejected' && $app2 != 'Rejected' && $app3 != 'Rejected') {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Quality Approval is already pending for the job number : '{$jobNo}' and Model Type : '{$modelType}'", // skip
                        // 'status_error' => $pendingExists,
                    ], 404);
                }
            }

            if (empty($templateCharacteristics)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Template characteristics can't be empty!",
                ], 404);
            }

            $tempCharacteristics = TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

            $columns = Schema::getColumnListing('temp_class_characteristics');

            if (! $tempCharacteristics) {
                $templateData = [];
                $unknownCharacteristics = [];

                TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                foreach ($templateCharacteristics as $item) {
                    foreach ($item as $key => $value) {
                        $key = strtolower($key) ?? null;
                        // if (Schema::hasColumn('temp_class_characteristics', $key)) {
                        //     $templateData[$key] = $value;
                        // }
                        if (in_array($key, $columns, true)) {
                            $templateData[$key] = $value;
                        } else {
                            $unknownCharacteristics[] = $key;
                        }
                    }
                }

                $uniqueUnkChars = array_unique($unknownCharacteristics);

                if (! empty($uniqueUnkChars)) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'Unknown characteristic fields found : '.implode(', ', $uniqueUnkChars).'.',
                    ], 404);
                }

                foreach ($typesToCreate as $type) {
                    if ($modelType == $type) {
                        TempClassCharacteristic::create(array_merge([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '1',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ], $templateData));
                    } else {
                        TempClassCharacteristic::create([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '2',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ]);
                    }
                }
            } else {
                $templateData = [];
                $unknownCharacteristics = [];

                foreach ($templateCharacteristics as $item) {
                    foreach ($item as $key => $value) {
                        $key = strtolower($key) ?? null;
                        if (in_array($key, $columns, true)) {
                            $templateData[$key] = $value;
                        } else {
                            $unknownCharacteristics[] = $key;
                        }
                    }
                }

                $uniqueUnkChars = array_unique($unknownCharacteristics);

                if (! empty($uniqueUnkChars)) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => 'Unknown characteristic fields found : '.implode(', ', $uniqueUnkChars).'.',
                    ], 404);
                }

                $fixedColumns = ['id', 'plant_id', 'item_id', 'machine_id', 'aufnr', 'model_type', 'has_work_flow_id', 'created_at', 'created_by', 'updated_at', 'updated_by', 'deleted_at'];
                $dynamicColumns = array_diff($columns, $fixedColumns);

                $incomingKeys = array_keys($templateData);
                $columnsToClear = array_diff($dynamicColumns, $incomingKeys);

                $clearData = [];
                foreach ($columnsToClear as $col) {
                    $clearData[$col] = null;
                }

                $finalData = array_merge($clearData, $templateData);

                TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update(array_merge([
                        'has_work_flow_id' => '1',
                        'updated_by' => $userName,
                    ], $finalData)); // ->where('item_id', $itemId)
            }

            try {
                $approvalId = [];

                $year = now()->format('y');
                $month = now()->format('m');
                $date = now()->format('d');
                $prefix = "WF-{$year}{$month}{$date}-";

                $lastWorkflow = RequestCharacteristic::where('work_flow_id', 'like', "{$prefix}%")
                    ->orderByDesc('work_flow_id')
                    ->first();

                if ($lastWorkflow) {
                    $lastSerial = substr($lastWorkflow->work_flow_id, strlen($prefix));
                    $nextSerial = str_pad(
                        intval($lastSerial) + 1,
                        4,
                        '0',
                        STR_PAD_LEFT
                    );
                } else {
                    $nextSerial = '0001';
                }

                $workflowId = "{$prefix}{$nextSerial}";

                RequestCharacteristic::create([
                    'plant_id' => $plantId,
                    'machine_id' => $machineId,
                    'item_id' => $itemId,
                    'model_type' => $modelType,
                    'characteristic_approver_master_id' => $charId,
                    'aufnr' => $jobNo,
                    'characteristic_name' => '',
                    'current_value' => '',
                    'update_value' => '',
                    'created_by' => $userName,
                    'work_flow_id' => $workflowId,
                ]);

                $approvalId["{$modelType}_APPROVAL_ID"] = $workflowId;

                $classRow = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

                if ($classRow) {
                    $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                        ->whereHas('approver', function ($query) {
                            $query->where('approver_type', 'Characteristic');
                        })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

                    $hasCharPending = false;
                    if (! $requestChars->isEmpty()) {
                        foreach ($requestChars as $row) {
                            $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                            if (! $isApproved) {
                                $hasCharPending = true;
                                break;
                            }
                        }
                    }

                    if ($hasCharPending) {
                        $newValue = '3';
                        TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                        foreach ($typesToCreate as $type) {
                            TempClassCharacteristic::create([
                                'plant_id' => $plantId,
                                'machine_id' => $machineId,
                                'item_id' => $itemId,
                                'aufnr' => $jobNo,
                                'model_type' => $type,
                                'has_work_flow_id' => '2',
                                'created_by' => $userName,
                                'updated_by' => $userName,
                            ]);
                        }

                        RequestCharacteristic::where('work_flow_id', $workflowId)->where('plant_id', $plantId)->forceDelete();
                    } else {
                        $newValue = '2';
                    }

                    ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                        ->update([
                            'has_work_flow_id' => $newValue,
                            'updated_at' => now(),
                            'updated_by' => $userName,
                        ]);

                    if ($hasCharPending) {
                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Characteristic approval is already pending for the job number '{$jobNo}'!",
                        ], 404);
                    }
                } else {
                    $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                        ->whereHas('approver', function ($query) {
                            $query->where('approver_type', 'Characteristic');
                        })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

                    $hasCharPending = false;
                    if (! $requestChars->isEmpty()) {
                        foreach ($requestChars as $row) {
                            $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                            if (! $isApproved) {
                                $hasCharPending = true;
                                break;
                            }
                        }
                    }

                    if ($hasCharPending) {
                        TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                        foreach ($typesToCreate as $type) {
                            TempClassCharacteristic::create([
                                'plant_id' => $plantId,
                                'machine_id' => $machineId,
                                'item_id' => $itemId,
                                'aufnr' => $jobNo,
                                'model_type' => $type,
                                'has_work_flow_id' => '2',
                                'created_by' => $userName,
                                'updated_by' => $userName,
                            ]);
                        }

                        RequestCharacteristic::where('work_flow_id', $workflowId)->where('plant_id', $plantId)->forceDelete();

                        return response()->json([
                            'status_code' => 'ERROR',
                            'status_description' => "Characteristic approval is already pending for the job number '{$jobNo}'!",
                        ], 404);
                    }
                }

                $extension = strtolower($file->getClientOriginalExtension());
                $filename = $workflowId.'.'.$extension;

                $filePath = $file->storeAs(
                    'uploads/LaserDocs',
                    $filename,
                    'local'
                );

                $filePath = "uploads/LaserDocs/{$filename}";

                if (! Storage::disk('local')->exists($filePath)) {
                    RequestCharacteristic::where('work_flow_id', $workflowId)->where('plant_id', $plantId)->forceDelete();

                    return response()->json([
                        'status' => 'ERROR',
                        'status_description' => "Document upload failed for Quality Work Flow ID : '{$workflowId}'",
                    ], 404);
                }

                return response()->json([
                    'work_flow_ids' => [$approvalId],
                ], 200);
            } catch (\Exception $e) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => $e->getMessage(),
                ], 500);
            }
        }
    }

    public function getLaserRequestChar(Request $request)
    {
        $expectedUser = env('API_AUTH_USER');
        $expectedPw = env('API_AUTH_PW');

        $headerAuth = $request->header('Authorization');
        $expectedToken = 'Bearer '.$expectedUser.':'.$expectedPw;

        if ($headerAuth != $expectedToken) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => 'Invalid authorization token!',
            ], 401);
        }

        $userName = $request->header('user-name');
        $charField = $request->header('characteristic-field');
        $plantCode = $request->header('plant-code');
        $workCenter = $request->header('work-center');
        $machineName = $request->header('machine-name');
        $jobNo = $request->header('aufnr');
        $itemCode = $request->header('item-code');
        $workFlowId = $request->header('work-flow-id');
        $workFlowId = strtoupper($workFlowId);
        $modelType = strtoupper($request->header('model-type'));
        $modelHeading = $request->header('model-heading');
        $requestType = $request->header('request-type');

        Log::info("Request {$requestType} POST API >>", ['user-name' => $userName, 'characteristic-field' => $charField, 'plant-code' => $plantCode, 'work-center' => $workCenter, 'machine-name' => $machineName, 'aufnr' => $jobNo, 'item-code' => $itemCode, 'work-flow-id' => $workFlowId]);

        if (! $userName || $userName == null || $userName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name can't be empty!",
            ], 404);
        } elseif ($userName == 'jothi') {
            $userName = 'Admin';
        }

        if (! $plantCode || $plantCode == null || $plantCode == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code can't be empty!",
            ], 404);
        } elseif (! $itemCode || $itemCode == null || $itemCode == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code can't be empty!",
            ], 404);
        } elseif (! $workCenter || $workCenter == null || $workCenter == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center can't be empty!",
            ], 404);
        } elseif (! $jobNo || $jobNo == null || $jobNo == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number can't be empty!",
            ], 404);
        } elseif (! $machineName || $machineName == null || $machineName == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name can't be empty!",
            ], 404);
        } elseif (! $modelType || $modelType == null || $modelType == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model type can't be empty!",
            ], 404);
        } elseif (! $modelHeading || $modelHeading == null || $modelHeading == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model heading can't be empty!",
            ], 404);
        } elseif (! $requestType || $requestType == null || $requestType == '') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Request type can't be empty!",
            ], 404);
        }

        if ($charField == null || $charField == '' || $charField == 'nil') {
            $charField = 'NIL';
        }

        if (! is_numeric($plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' should contain only numeric values!",
            ], 400);
        } elseif (Str::length($plantCode) < 4 || Str::length($plantCode) > 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' must be between 4 and 7 digits only!",
            ], 400);
        } elseif (! preg_match('/^[1-9]\d{3,6}$/', $plantCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Invalid plant code '{$plantCode}' found!",
            ], 400);
        }

        if (Str::length($itemCode) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain minimum 6 digits!",
            ], 404);
        } elseif (! ctype_alnum($itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should contain only alpha-numeric values!",
            ], 404);
        } elseif (! preg_match('/^[a-zA-Z1-9][a-zA-Z0-9]{5,}$/', $itemCode)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' should not begin with '0'!",
            ], 404);
        }

        if (Str::length($workCenter) < 6) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain minimum 6 characters!",
            ], 404);
        } elseif (! ctype_alnum($workCenter)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' should contain only alpha-numeric values!",
            ], 404);
        }

        if (Str::length($jobNo) < 7) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' should contain minimum 7 digits!",
            ], 404);
        } elseif (! is_numeric($jobNo)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' should contain only numeric values!",
            ], 404);
        }

        if ($requestType != 'Characteristic' && $requestType != 'Quality') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown request type '{$requestType}' found!",
            ], 404);
        }

        if ($modelType != 'MOTOR' && $modelType != 'PUMP' && $modelType != 'NAME_PLATE') {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown model type '{$modelType}' found!",
            ], 404);
        }

        $typesToCreate = [];

        if (Str::contains($modelHeading, 'PRESSURE BOOSTER SYSTEM', ignoreCase: true)) {
            $typesToCreate = ['MOTOR', 'PUMP', 'NAME_PLATE'];
        } elseif (Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) || Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
            $typesToCreate = ['MOTOR', 'PUMP'];
        } elseif (Str::contains($modelHeading, 'PUMP', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMP SET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPSET', ignoreCase: true) && ! Str::contains($modelHeading, 'PUMPS', ignoreCase: true)) {
            $typesToCreate = ['PUMP'];
        } elseif (Str::contains($modelHeading, 'MOTOR', ignoreCase: true)) {
            $typesToCreate = ['MOTOR'];
        } else {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Unknown ZMM_HEADING : '{$modelHeading}' found!",
            ], 404);
        }

        if (! in_array($modelType, $typesToCreate, true)) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Model type '{$modelType}' does not match with the model heading '{$modelHeading}'!",
            ], 404);
        }

        $plant = Plant::where('code', $plantCode)->first();
        if (! $plant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in plants table!",
            ], 404);
        }

        $plantId = $plant->id;

        $user = User::where('name', $userName)->first();

        if (! $user) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found in users table!",
            ], 404);
        }

        $userPlant = User::where('name', $userName)->where('plant_id', $plantId)->first();

        if (! $userPlant && ! $user->hasRole('Super Admin')) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User name '{$userName}' not found for the plant code '{$plantCode}' in users table!",
            ], 404);
        } elseif (! $user->hasRole(['Super Admin', 'Laser Manager', 'Laser Supervisor', 'Laser Employee'])) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "User '{$userName}' does not have rights!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in machines table!",
            ], 404);
        }

        $machine = Machine::where('work_center', $workCenter)->where('plant_id', $plantId)->first();
        if (! $machine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in machines table!",
            ], 404);
        }

        $machineId = $machine->id;

        $iCode = Item::where('code', $itemCode)->first();
        if (! $iCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found in items table!",
            ], 404);
        }

        $item = Item::where('code', $itemCode)->where('plant_id', $plantId)->first();
        if (! $item) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Item code '{$itemCode}' not found for the plant code '{$plantCode}' in items table!",
            ], 404);
        }

        $itemId = $item->id;

        $pCode = CharacteristicApproverMaster::where('plant_id', $plantId)->first();
        if (! $pCode) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Plant code '{$plantCode}' not found in approver master!",
            ], 404);
        }

        $wCenter = CharacteristicApproverMaster::where('machine_id', $machineId)->first();
        if (! $wCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found in approver master!",
            ], 404);
        }

        $wCenterAgaPlant = CharacteristicApproverMaster::where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $wCenterAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $mName = CharacteristicApproverMaster::where('machine_name', $machineName)->first();
        if (! $mName) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' not found in approver master!",
            ], 404);
        }

        $mNameAgaPlant = CharacteristicApproverMaster::where('machine_name', $machineName)->where('plant_id', $plantId)->first();
        if (! $mNameAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cField = CharacteristicApproverMaster::where('characteristic_field', $charField)->first();
        if (! $cField) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found in approver master!",
            ], 404);
        }

        // Master characteristic field value 'NIL' not found in approver master!
        $cFieldAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('plant_id', $plantId)->first();
        if (! $cFieldAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $mNameAndWorkCenter = CharacteristicApproverMaster::where('machine_name', $machineName)->where('machine_id', $machineId)->first();
        if (! $mNameAndWorkCenter) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' and work center '{$workCenter}' not found in approver master!",
            ], 404);
        }

        $mNameAndWorkCenterAgaPlant = CharacteristicApproverMaster::where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $mNameAndWorkCenterAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Machine name '{$machineName}' and work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCent = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_id', $machineId)->first();
        if (! $cFieldAndWorkCent) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the work center '{$workCenter}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCentAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $cFieldAndWorkCentAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' and work center '{$workCenter}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndMach = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->first();
        if (! $cFieldAndMach) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' not found for the machine name '{$machineName}' in approver master!",
            ], 404);
        }

        $cFieldAndMachAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->where('plant_id', $plantId)->first();
        if (! $cFieldAndMachAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}' and machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $cFieldAndWorkCentAndMachAgaPlant = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $cFieldAndWorkCentAndMachAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', and machine name '{$machineName}' not found for the plant code '{$plantCode}' in approver master!",
            ], 404);
        }

        $job = RequestCharacteristic::where('aufnr', $jobNo)->first();
        if (! $job) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' not found in request approval table!",
            ], 404);
        }

        $jobAgaPlant = RequestCharacteristic::where('aufnr', $jobNo)->where('plant_id', $plantId)->first();
        if (! $jobAgaPlant) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' not found for the plant code '{$plantCode}' in request approval table!",
            ], 404);
        }

        $jobAgaPlantItem = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('plant_id', $plantId)->first();
        if (! $jobAgaPlantItem) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '{$jobNo}' not found with the item code '{$itemCode}' in request approval table!",
            ], 404);
        }

        $jobAgaPlantMachine = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
        if (! $jobAgaPlantMachine) {
            return response()->json([
                'status_code' => 'ERROR',
                'status_description' => "Job number '$jobNo' not found for the work center '$workCenter' in request approval table!",
            ], 404);
        }

        if ($requestType == 'Characteristic') {
            $appTypExist = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('approver_type', $requestType)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
            if (! $appTypExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', machine name '{$machineName}', and plant code '{$plantCode}' not found for the approver type 'Characteristic' in approver master!",
                ], 404);
            }

            $reqCharExist = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)
                ->whereHas('approver', function ($query) use ($requestType) {
                    $query->where('approver_type', $requestType);
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $reqCharExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Request characteristic approvals not found for the Job number '{$jobNo}', item code '{$itemCode}', work center '{$workCenter}',  model type '{$modelType}' and plant code '{$plantCode}'!",
                ], 404);
            }

            if ($workFlowId) {
                $charWfIdExist = RequestCharacteristic::where('work_flow_id', $workFlowId)->first();
                if (! $charWfIdExist) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Characteristic approval 'Work Flow ID' not found in database!",
                    ], 404);
                }

                $charWfIdExist = RequestCharacteristic::where('work_flow_id', $workFlowId)
                    ->whereHas('approver', function ($query) use ($requestType) {
                        $query->where('approver_type', $requestType);
                    })
                    ->first();
                if (! $charWfIdExist) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Quality approval Work Flow ID : '{$workFlowId}' found!",
                    ], 404);
                }
            }
        } else {
            $appTypExist = CharacteristicApproverMaster::where('characteristic_field', $charField)->where('approver_type', $requestType)->where('machine_name', $machineName)->where('machine_id', $machineId)->where('plant_id', $plantId)->first();
            if (! $appTypExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Master characteristic field value '{$charField}', work center '{$workCenter}', machine name '{$machineName}', and plant code '{$plantCode}' not found for the approver type 'Quality' in approver master!",
                ], 404);
            }

            $reqCharExist = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) use ($requestType) {
                    $query->where('approver_type', $requestType);
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->first();

            if (! $reqCharExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Request quality approvals not found for the Job number '{$jobNo}', item code '{$itemCode}', work center '{$workCenter}',  model type '{$modelType}' and plant code '{$plantCode}'!",
                ], 404);
            }

            if ($workFlowId) {
                $qualWfIdExist = RequestCharacteristic::where('work_flow_id', $workFlowId)->first();
                if (! $qualWfIdExist) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Quality approval 'Work Flow ID' not found in database!",
                    ], 404);
                }

                $qualWfIdExist = RequestCharacteristic::where('work_flow_id', $workFlowId)
                    ->whereHas('approver', function ($query) use ($requestType) {
                        $query->where('approver_type', $requestType);
                    })
                    ->first();
                if (! $qualWfIdExist) {
                    return response()->json([
                        'status_code' => 'ERROR',
                        'status_description' => "Characteristic approval Work Flow ID : '{$workFlowId}' found!",
                    ], 404);
                }
            }
        }

        $classRow = ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->latest()->first();

        if ($classRow) {
            $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Characteristic');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            $requestQual = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Quality');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();

            foreach ($requestQual as $row) {
                $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved') ? '0' : '1';

                TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $workFlowStatus,
                        'updated_by' => $userName,
                    ]);
            }

            $tempClassChars = TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            if (! $requestChars->isEmpty()) {
                $hasCharPending = false;
                $hasQualPending = false;
                $allCharApproved = true;
                $allQualApproved = true;

                foreach ($requestChars as $row) {
                    $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                    if (! $isApproved) {
                        $allCharApproved = false;
                        $hasCharPending = true;
                        break;
                    }
                }

                if ($hasCharPending) {
                    $newValue = '3';
                    TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                    foreach ($typesToCreate as $type) {
                        TempClassCharacteristic::create([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '2',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ]);
                    }
                } elseif (! $tempClassChars->isEmpty()) {
                    foreach ($tempClassChars as $temp) {
                        if ($temp->has_work_flow_id == '1' || $temp->has_work_flow_id == '2') {
                            $hasQualPending = true;
                            $allQualApproved = false;
                            break;
                        }

                        if ($temp->has_work_flow_id == '0') {
                            $allQualApproved = true;
                        }
                    }

                    if ($hasQualPending) {
                        $newValue = '2';
                    } elseif ($allQualApproved) {
                        $newValue = '0';
                    }
                } elseif ($allCharApproved) {
                    $newValue = '0';
                }

                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $newValue,
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);
            } elseif (! $tempClassChars->isEmpty()) {
                $hasQualPending = false;
                $allQualApproved = true;

                foreach ($tempClassChars as $temp) {
                    if ($temp->has_work_flow_id == '1' || $temp->has_work_flow_id == '2') {
                        $hasQualPending = true;
                        $allQualApproved = false;
                        break;
                    }

                    if ($temp->has_work_flow_id == '0') {
                        $allQualApproved = true;
                    }
                }

                if ($hasQualPending) {
                    $newValue = '2';
                } elseif ($allQualApproved) {
                    $newValue = '0';
                }

                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $newValue,
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);
            } else {
                ClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => '0',
                        'updated_at' => now(),
                        'updated_by' => $userName,
                    ]);
            }
        } else {
            $requestChars = RequestCharacteristic::where('aufnr', $jobNo)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Characteristic');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->get();

            $requestQual = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                ->whereHas('approver', function ($query) {
                    $query->where('approver_type', 'Quality');
                })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();

            foreach ($requestQual as $row) {
                $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved') ? '0' : '1';

                TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    ->update([
                        'has_work_flow_id' => $workFlowStatus,
                        'updated_by' => $userName,
                    ]);
            }

            if (! $requestChars->isEmpty()) {
                $hasCharPending = false;

                foreach ($requestChars as $row) {
                    $isApproved = ($row->approver_status1 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Approved' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Approved' || $row->approver_status3 == 'Rejected');

                    if (! $isApproved) {
                        $hasCharPending = true;
                        break;
                    }
                }

                if ($hasCharPending) {
                    TempClassCharacteristic::where('aufnr', $jobNo)->where('machine_id', $machineId)->where('plant_id', $plantId)->forceDelete();

                    foreach ($typesToCreate as $type) {
                        TempClassCharacteristic::create([
                            'plant_id' => $plantId,
                            'machine_id' => $machineId,
                            'item_id' => $itemId,
                            'aufnr' => $jobNo,
                            'model_type' => $type,
                            'has_work_flow_id' => '2',
                            'created_by' => $userName,
                            'updated_by' => $userName,
                        ]);
                    }
                }
            }
        }

        if (! $workFlowId) {
            $records = null;

            if ($requestType == 'Characteristic') {
                $records = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)
                    ->whereHas('approver', function ($query) use ($requestType) {
                        $query->where('approver_type', $requestType);
                    })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();
            } else {
                $records = RequestCharacteristic::where('aufnr', $jobNo)->where('item_id', $itemId)->where('model_type', $modelType)
                    ->whereHas('approver', function ($query) use ($requestType) {
                        $query->where('approver_type', $requestType);
                    })->where('machine_id', $machineId)->where('plant_id', $plantId)->orderBy('id')->get();
            }

            $response = [];

            foreach ($records as $row) {
                if ($requestType == 'Characteristic') {
                    $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved' || $row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Rejected') ? '0' : '1';

                    // if ($row->approver?->approver_type != 'Characteristic' || ! $row->characteristic_name) {
                    //     continue;
                    // }

                    $response[] = [
                        'work_flow_id' => (string) $row->work_flow_id,
                        'work_flow_status' => $workFlowStatus,
                        'model_type' => strtoupper($row->model_type) ?? '',
                        'characteristic_name' => strtoupper($row->characteristic_name) ?? '',
                        'current_value' => $row->current_value ?? '',
                        'update_value' => $row->update_value ?? '',
                        //  'approver_name_1' => $row->approver_name1 ?? '',
                        'approver_name_1' => $row->approver?->name1 ?? '',
                        'approver_status_1' => $row->approver_status1 ?? '',
                        'approver_remark_1' => $row->approver_remark1 ?? '',
                        'approved_at_1' => $row->approved1_at ?? '', // ? $row->approved1_at->format('d-m-Y H:i:s') : '',
                        'approver_name_2' => $row->approver?->name2 ?? '',
                        'approver_status_2' => $row->approver_status2 ?? '',
                        'approver_remark_2' => $row->approver_remark2 ?? '',
                        'approved_at_2' => $row->approved2_at ?? '', // ? $row->approved2_at->format('d-m-Y H:i:s') : '',
                        'approver_name_3' => $row->approver?->name3 ?? '',
                        'approver_status_3' => $row->approver_status3 ?? '',
                        'approver_remark_3' => $row->approver_remark3 ?? '',
                        'approved_at_3' => $row->approved3_at ?? '', // ? $row->approved3_at->format('d-m-Y H:i:s') : '',
                        'mail_status' => ($row->mail_status == 'Sent') ? 'Sent-M1' : (($row->mail_status == 'Sent-Mail2') ? 'Sent-M2' : (($row->mail_status == 'Sent-Mail3') ? 'Sent-M3' : '-')),
                        'triggered_at' => $row->trigger_at ?? '',
                        'requested_by' => ($row->created_by == 'Admin') ? 'jothi' : $row->created_by ?? '',
                        'requested_at' => $row->created_at ? $row->created_at->format('Y-m-d H:i:s') : '',
                    ];
                } else {
                    $workFlowStatus = ($row->approver_status1 == 'Approved' || $row->approver_status2 == 'Approved' || $row->approver_status3 == 'Approved') ? '0' : '1';

                    // / TempClassCharacteristic::where('aufnr', $jobNo)->where('model_type', $modelType)->where('machine_id', $machineId)->where('plant_id', $plantId)
                    // /     ->update([
                    // /         'has_work_flow_id' => $workFlowStatus,
                    // /         'updated_by' => $userName,
                    // /     ]);

                    if ($workFlowStatus == '1') {
                        $workFlowStatus = ($row->approver_status1 == 'Rejected' || $row->approver_status2 == 'Rejected' || $row->approver_status3 == 'Rejected') ? '2' : '1';
                    }

                    // if ($row->approver?->approver_type != 'Quality' || $row->characteristic_name) {
                    //     continue;
                    // }

                    $response[] = [
                        'work_flow_id' => (string) $row->work_flow_id,
                        'work_flow_status' => $workFlowStatus,
                        'model_type' => strtoupper($row->model_type) ?? '',
                        // 'approver_name_1' => $row->approver_name1 ?? '',
                        'approver_name_1' => $row->approver?->name1 ?? '',
                        'approver_status_1' => $row->approver_status1 ?? '',
                        'approver_remark_1' => $row->approver_remark1 ?? '',
                        'approved_at_1' => $row->approved1_at ?? '', // ? $row->approved1_at->format('d-m-Y H:i:s') : '',
                        'approver_name_2' => $row->approver?->name2 ?? '',
                        'approver_status_2' => $row->approver_status2 ?? '',
                        'approver_remark_2' => $row->approver_remark2 ?? '',
                        'approved_at_2' => $row->approved2_at ?? '', // ? $row->approved2_at->format('d-m-Y H:i:s') : '',
                        'approver_name_3' => $row->approver?->name3 ?? '',
                        'approver_status_3' => $row->approver_status3 ?? '',
                        'approver_remark_3' => $row->approver_remark3 ?? '',
                        'approved_at_3' => $row->approved3_at ?? '', // ? $row->approved3_at->format('d-m-Y H:i:s') : '',
                        'mail_status' => ($row->mail_status == 'Sent') ? 'Sent-M1' : (($row->mail_status == 'Sent-Mail2') ? 'Sent-M2' : (($row->mail_status == 'Sent-Mail3') ? 'Sent-M3' : '-')),
                        'triggered_at' => $row->trigger_at ?? '',
                        'requested_by' => ($row->created_by == 'Admin') ? 'jothi' : $row->created_by ?? '',
                        'requested_at' => $row->created_at ? $row->created_at->format('Y-m-d H:i:s') : '',
                    ];
                }
            }

            return response()->json([
                'requested_characteristics' => $response,
            ], 200);
        } else {
            $extension = ($requestType == 'Characteristic') ? 'pdf' : 'png';
            $filePath = "uploads/LaserDocs/{$workFlowId}.{$extension}";
            $filename = "{$workFlowId}.{$extension}";

            $workFlowIdExist = RequestCharacteristic::where('work_flow_id', $workFlowId)->first();

            if (! $workFlowIdExist) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => "Work Flow ID '{$workFlowId}' not found in request approval table!",
                ], 404);
            }

            // if (! str_ends_with(strtolower($filename), '.pdf')) {
            //     $filename .= '.pdf';
            // }

            if (! Storage::disk('local')->exists($filePath)) {
                return response()->json([
                    'status_code' => 'ERROR',
                    'status_description' => ($requestType == 'Characteristic') ? "Characteristic approval document (.PDF) not found for the Work Flow ID '{$workFlowId}'!" : "Quality approval document (.PNG) not found for the Work Flow ID '{$workFlowId}'!",
                ], 404);
            }

            $file = Storage::disk('local')->get($filePath);
            $mimeType = Storage::disk('local')->mimeType($filePath);

            return Response::make($file, 200, [
                'Content-Type' => $mimeType,
                'Content-Disposition' => 'inline; filename="'.$filename.'"',
            ]);
        }
    }

    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
