<?php

namespace App\Http\Controllers\Api\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Log;
use App\Models\Production;
use App\Models\ProductionOperation;
use App\Models\ProductionQuantity;
use App\Models\ProductionPackage;
use App\Models\ProductionScrap;
use App\Models\Item;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\ManufacturingStore;
use App\Models\ProductionDamagedGood;
use App\Models\ProductionFinishedGood;
use App\Service\StockEntryService;
use App\Service\StaticMaster;
use App\Service\SequenceService;
use Carbon\Carbon;

class ProductionController extends Controller
{
    public function index(Request $request)
    {
        $production = Production::where('rolledback',0)->with('bom','item','order','entry_by','bom.item');

        // Apply filters based on request parameters
        if ($request->has('search')) {
            $search = $request->input('search');

            $production->where(function ($q) use ($search) {
                $q->where('production_id','LIKE', "%$search%")
                  ->orWhere('date_time', 'LIKE', "%$search%")
                  ->orWhereHas('item',function($q) use ($search){
                        $q->where('name', 'LIKE', "%$search%");
                  })
                  ->orWhereHas('order',function($q) use ($search){
                        $q->where('order_id', 'LIKE', "%$search%");
                  })
                  ->orWhere('quantity',$search);
            });
        }

        if ($request['status']!='' && isset($request['status'])) {
            $production=$production->where('status',$request['status']);
        }

        if ($request['statuses']!='' && isset($request['statuses'])) {
            $production=$production->whereIn('status',$request['statuses']);
        }

        if ($request['custom_date']!='' && isset($request['custom_date'])) {

            $customDate = $request->custom_date;

            $production = $production->whereDate('date_time', $customDate);

        }

        if ($request['from_date']!='' && isset($request['to_date'])) {

            $fromDate = $request->from_date;

            $toDate = $request->to_date;

            // 'fromDate' and 'toDate'
            $production = $production->whereBetween('date_time', [$fromDate, $toDate]);

        }

        $count=$production->count();

        if(isset($request['sort_by']) && $request['sort_by']!='' && $request['sort_by']!=null){
                
            $sort_order=$request['sort_order']==1?'asc':'desc';

            $production = $production->orderby($request['sort_by'],$sort_order);

        }else{
            $production = $production->orderby('id','desc');
        }

        if(isset($request['sort_by']) && $request['sort_by'] != '' && $request['sort_by'] != null) {
    
            $sort_order = $request['sort_order'] == 1 ? 'asc' : 'desc';
            $sort_by = $request['sort_by'];
        
            // Sorting by 'transaction_date' from 'grn' relation
            if ($sort_by == 'order_id') {
                $production = $production->orderBy(
                    Order::select('order_id')
                        ->whereColumn('orders.id', 'productions.order_id'), 
                    $sort_order
                );
    
            
            } 
            else {
                // Sort by columns from productions table
                $production = $production->orderBy($sort_by, $sort_order);
            }
        
        } else {
            // Default sorting if no 'sort_by' is provided
            $production = $production->orderBy('id', 'desc');
        }
          
        
        $production=$production->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                // ->orderBy('id','desc')
                ->get();

        //show production finished goods quantity
        foreach ($production as $prod) {
            $prod->finished_goods_quantity = ProductionFinishedGood::where('production_id', $prod->id)
                ->where('action_type', 'add')
                ->sum('quantity');
        }

        return $response=[
            'success'=>true,
            'total'=>$count,
            'production'=>$production,
            'message'=>'Production data Listed Successfully'
        ];
    }

    // Store a newly created requisition
    public function store(Request $request)
    {

        $validator=validator($request->all(),[

            'production_id'=>'required',
            'date_time'=>'required',
            'order_id'=>'required|integer',
            'item_id'=>'required|integer',
            'bom_id'=>'required|integer',
            'quantity'=>'required|integer',
            'batch_id'=>'required|integer',

        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try {
                $obj['production_id'] = $request['production_id'];
                $obj['date_time'] = $request['date_time'];
                $obj['order_id'] = $request['order_id'] ?? 0;
                $obj['item_id'] = $request['item_id'] ?? 0;
                $obj['bom_id'] = $request['bom_id'] ?? 0;
                $obj['batch_id'] = $request['batch_id'] ?? 0;
                $obj['quantity'] = $request['quantity'] ?? 0;
                $obj['notes'] = $request['notes'];
                $obj['attachments'] = $request['attachments'];
            

                // Update Production with production id
                if ($request['id'] > 0) {
                    $production = Production::where('id', $request['id'])->first();
                    $production->update($obj);

                    return response()->json(['success' => true, 'message' => 'Production updated successfully', 'production' => $production], 200);

                } else {
                    // Creating new Production
                    $production = Production::create($obj);

                    // Update Production Order Status
                    $order = Order::where('id', $request['order_id'])->first();
                    if ($order) {
                        $order->status = 1; // Assuming 1 is the status for 'In Production'
                        $order->save();
                    }

                    $module='production';

                    // Update Sequence
                    $sequence=new SequenceService;
                    $sequence->updateSequence($module);

                    return response()->json(['success' => true, 'message' => 'Production created successfully', 'production' => $production], 200);

                }
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Failed to create production', 'error' => $e->getMessage()], 500);
            }
            
        }
    }
    
    
    // Retrieve BOM details by BOM ID
    public function show(Request $request)
    {
        $validator=validator($request->all(),[
            'production_id'=>'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            $production_id = $request->production_id;

            $production =  Production::where('rolledback',0)
                ->with('bom','item','order','batch','order.items',
                    'bom.charges','bom.operations','bom.raw_materials','bom.raw_materials.item:id,name,manufacturing_store',
                    'bom.packagings','bom.packagings.item:id,name,manufacturing_store',
                    'bom.scraps','bom.scraps.item:id,name,manufacturing_store',
                    'bom.bom_outcomes','bom.bom_outcomes.item:id,name',
                    'quality_check',
                    'quality_check.quality_items','bom.item')
                ->where('id', $production_id)
                ->first();

            $response = [
                'message'=>'Details Listed Successfully',
                'success'=>true,
                'production' => $production
            ];

            return response()->json($response, 200);
        }
    }
    
    
    // Production Operations
    public function record_operation(Request $request){

        $validator=validator($request->all(),[
            'operation_id' => 'required',
            'production_id' => 'required',
            'workstation_id' => 'required',
            'machinery_id' => 'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            // Record operation
            $obj['date']=$request['date'];
            $obj['production_id']=$request['production_id']??0;
            $obj['operation_id']=$request['operation_id']??0;
            $obj['workstation_id']=$request['workstation_id']??0;
            $obj['machinery_id']=$request['machinery_id']??0;
            $obj['start_datetime']=$request['start_datetime'];
            $obj['end_datetime']=$request['end_datetime'];
            $obj['notes']=$request['notes'];
            $obj['attachments']=$request['attachments'];

            if($request['id']>0){
                $production_operation=ProductionOperation::where('id',$request['id'])->first();
                $production_operation->update($obj);

                $response=[
                    'success'=>true,
                    'message'=>'Operation updated successfully',
                    'operation'=>$production_operation
                ];

            }else{

                $production_operation=ProductionOperation::create($obj);

                // Update Production Status
                $production = Production::where('id', $request['production_id'])->first();
                if ($production) {
                    $production->status = 1; // Assuming 1 is the status for 'In Production'
                    $production->save();
                }

                $response=[
                    'success'=>true,
                    'message'=>'Production Operation Recorded successfully',
                    'operation'=>$production_operation
                ];
            }

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

    }

    public function operations_list(Request $request){

        $validator=validator($request->all(),[
            'production_operation_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_operation=ProductionOperation::where('production_id',$request['production_id'])
                    ->where('operation_id',$request['production_operation_id'])
                    ->with('workstation','machinery')->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Operation not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'production_operation'=>$production_operation,
                'message'=>'Production Operations List Fetch Successfully'
            ];

            return response()->json($response, 200);
        }
    }
    
    // Raw Materials
    public function record_quantity(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required',
            'item_id' => 'required',
            'date' => 'required',
            'quantity' => 'required|numeric'
            // 'logistic_type' => 'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            // Record operation
            $obj['production_id']=$request['production_id']??0;
            $obj['item_id']=$request['item_id']??0;
            $obj['date']=$request['date'];
            $obj['quantity']=$request['quantity']??0;
            $obj['logistic_type']=$request['logistic_type'];
            $obj['store_type']=$request['store_type'];
            $obj['notes']=$request['notes'];
            $obj['attachments']=$request['attachments'];

            if($request['id']>0){
                $production_operation=ProductionQuantity::where('id',$request['id'])->first();
                $production_operation->update($obj);

                $response=[
                    'success'=>true,
                    'message'=>'Raw Materials updated successfully',
                    'operation'=>$production_operation
                ];

            }else{

                $production_operation=ProductionQuantity::create($obj);

                //We are treating item level wise from requestion item table
                $obj1['transaction_date']=$request['date']??Carbon::today()->format('Y-m-d');
                $obj1['transaction_id']=$production_operation['id']??0;
                $obj1['item_id']=$request['item_id']??0;
                $obj1['unit_id']=$request['unit_id']??0;
                $obj1['store_id']=1;    //default store 
                $obj1['fy']=$request['fy']??Carbon::now()->format('Y');
                $obj1['quantity']=$request['quantity']??0;
                $obj1['transaction_type']=StaticMaster::$PRODUCTION_RAW;
                $obj1['taken_by']=$request['taken_by'];
                $obj1['issued_by']=$request['issued_by'];
                $obj1['vehicle_no']=$request['vehicle_no'];
                $obj1['driver_name']=$request['driver_name'];
                $obj1['driver_contact']=$request['driver_contact'];
                $obj1['attachments']=$request['attachments'];
                $obj1['notes']=$request['notes'];
                $obj1['inout']=2;

                // Stock added in store
                $store=ManufacturingStore::create($obj1);

                 // Updating Store quantity in item table
                $item=Item::where('id',$request['item_id'])->lockForUpdate()->first();

                if($item){
                    $item['manufacturing_store']=$item['manufacturing_store']-$request['quantity'];

                    $item->update();

                }

                $response=[
                    'success'=>true,
                    'message'=>'Raw Materials Recorded successfully',
                    'operation'=>$production_operation
                ];
            }

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

    }

    public function raw_material_list(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_operation=ProductionQuantity::where('production_id',$request['production_id'])
                    ->with('item')->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Raw not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'production_raw'=>$production_operation,
                'message'=>'Production Raw List Fetch Successfully'
            ];

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

    // Packagings
    public function packaging_Create(Request $request)
    {
        $validator=validator($request->all(),[
            'production_id' => 'required',
            'item_id' => 'required',
            'date' => 'required',
            'quantity' => 'required|numeric',
            // 'logistic_type' => 'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            // Record Packagings
            $obj['production_id']=$request['production_id']??0;
            $obj['item_id']=$request['item_id']??0;
            $obj['date']=$request['date'];
            $obj['quantity']=$request['quantity']??0;
            $obj['logistic_type']=$request['logistic_type'];
            $obj['store_type']=$request['store_type'];
            $obj['notes']=$request['notes'];
            $obj['attachments']=$request['attachments'];

            if($request['id']>0){
                $production_operation=ProductionPackage::where('id',$request['id'])->first();
                $production_operation->update($obj);

                $response=[
                    'success'=>true,
                    'message'=>'Production Package updated successfully',
                    'operation'=>$production_operation
                ];

            }else{

                $production_operation=ProductionPackage::create($obj);

                //We are treating item level wise from requestion item table
                $obj1['transaction_date']=$request['date']??Carbon::today()->format('Y-m-d');
                $obj1['transaction_id']=$production_operation['id']??0;
                $obj1['item_id']=$request['item_id']??0;
                $obj1['unit_id']=$request['unit_id']??0;
                $obj1['store_id']=1;    //default store 
                $obj1['fy']=$request['fy']??2024;
                $obj1['quantity']=$request['quantity']??0;
                $obj1['transaction_type']=StaticMaster::$PRODUCTION_PACKAGING;
                $obj1['taken_by']=$request['taken_by'];
                $obj1['issued_by']=$request['issued_by'];
                $obj1['vehicle_no']=$request['vehicle_no'];
                $obj1['driver_name']=$request['driver_name'];
                $obj1['driver_contact']=$request['driver_contact'];
                $obj1['attachments']=$request['attachments'];
                $obj1['notes']=$request['notes'];

                // Stock added in store
                $store=ManufacturingStore::create($obj1);

                 // Updating Store quantity in item table
                $item=Item::where('id',$request['item_id'])->lockForUpdate()->first();

                if($item){
                    $item['manufacturing_store']=$item['manufacturing_store']-$request['quantity'];

                    $item->save();
                }

                $response=[
                    'success'=>true,
                    'message'=>'Production Package Recorded successfully',
                    'operation'=>$production_operation
                ];
            }

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

    }

    public function packagings_list(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_operation=ProductionPackage::where('production_id',$request['production_id'])
                    ->with('item')->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Raw not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'production_packagings'=>$production_operation,
                'message'=>'Production Raw List Fetch Successfully'
            ];

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


    //  create scrap record
    public function scrap_create(Request $request){

        $validator=validator($request->all(),[
            'quantity'=>'required|integer',
            'quantity'=>'required|integer',
            'action_type'=>'required',
            'date'=>'required',
            'production_id'=>'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try {

                $obj['production_id'] = $request['production_id'];
                $obj['item_id'] = $request['item_id'];
                $obj['item_name'] = $request['item_name'];
                $obj['date'] = $request['date'];
                $obj['action_type'] = $request['action_type'];   //Add and Move
                $obj['warehouse_id'] = $request['warehouse_id'] ?? 0;
                $obj['zone_id'] = $request['zone_id'] ?? 0;
                $obj['rack_id'] = $request['rack_id'] ?? 0;
                $obj['bin_id'] = $request['bin_id'] ?? 0;
                $obj['quantity'] = $request['quantity'] ?? 0;
                $obj['notes'] = $request['notes'];
                $obj['attachments'] = $request['attachments'];
            
                // Update Production with production scrap id
                if ($request['id'] > 0) {
                    $production_scrap = ProductionScrap::where('id', $request['id'])->first();

                    if($request['action_type']=='add'){

                        $production_scrap->update($obj);

                        return response()->json(['success' => true, 'message' => 'Production Scrap updated successfully', 'production_scrap' => $production_scrap], 200);

                    }else{

                        return response()->json(['success' => false, 'message' => 'Production Scrap will not be update on move action type', 'production_scrap' => $production_scrap], 200);
                    }

                } else {
                    // Creating new ProductionScrap
                    $production_scrap = ProductionScrap::create($obj);

                    if($request['action_type']=='move'){
                        $stock=new StockEntryService;
                        $stock->mannualStockMove($request,$production_scrap,StaticMaster::$PRODUCTION_SCRAP,1);
                    }

                    return response()->json(['success' => true, 'message' => 'Production Scrap created successfully', 'production_scrap' => $production_scrap], 200);

                }
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Failed to create production scrap', 'error' => $e->getMessage()], 500);
            }
            
        }
    }
    
    public function scrap_list(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_scrap=ProductionScrap::with('warehouse')->where('production_id',$request['production_id']);
                // ->where('is_disabled',0);
 
                if($request['search']!=null && $request['search']!=''){

                    $production_scrap = $production_scrap->where('action_type', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('warehouse_id', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('notes', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('quantity', 'LIKE', '%' . $request['search'] . '%');
                }

                    // get custom_date 
                if ($request['custom_date']!='' && isset($request['custom_date'])) {
                    $customDate = $request->custom_date;
                    $production_scrap = $production_scrap->whereDate('created_at', $customDate);
                }

                // Count all the items
                $production_count=$production_scrap->count();

                // Pagination
                $production_scrap=$production_scrap->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->orderBy('id','desc')
                    ->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Scrap Raw not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'count'=>$production_count,
                'production_scrap'=>$production_scrap,
                'message'=>'Production Scrap List Fetch Successfully'
            ];

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

    //  create Damaged good record
    public function damaged_create(Request $request)
    {

        $validator=validator($request->all(),[
            'production_id'=>'required|integer',
            'item_id'=>'required|integer',
            // 'quantity'=>'required',
            // 'action_type'=>'required',
            // 'warehouse_id'=>'required|integer',
            'date'=>'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try {
                $obj['production_id'] = $request['production_id'];
                $obj['parent_id'] = $request['id']??0;
                $obj['date'] = $request['date'];
                $obj['action_type'] = $request['action_type'];   //Add or Move
                $obj['goods_condition_type'] = $request['goods_condition_type'];    //From the masters Damage
                $obj['warehouse_id'] = $request['warehouse_id'] ?? 0;
                $obj['zone_id'] = $request['zone_id'] ?? 0;
                $obj['rack_id'] = $request['rack_id'] ?? 0;
                $obj['bin_id'] = $request['bin_id'] ?? 0;
                $obj['item_id'] = $request['item_id'] ?? 0;
                $obj['item_name'] = $request['item_name'];
                $obj['quantity'] = $request['quantity'] ?? 0;
                $obj['notes'] = $request['notes'];
                $obj['attachments'] = $request['attachments'];
            
                
                // Update Production with Production Damaged id
                if ($request['id'] > 0) {

                    // Creating new ProductionScrap
                    $production_damaged = ProductionDamagedGood::create($obj);

                    if($request['action_type']=='move'){

                        // Adding Stock in Warehouse
                        $stock=new StockEntryService;
                        $stock->mannualStockMove($request,$production_damaged,StaticMaster::$PRODUCTION_DAMAGE,1);
                    }

                    return response()->json(['success' => true, 'message' => 'Production Damaged Action Created successfully', 'production_damaged' => $production_damaged], 200);

                } else {
                    // Creating new ProductionScrap
                    $production_damaged = ProductionDamagedGood::create($obj);

                    return response()->json(['success' => true, 'message' => 'Production Damaged Item created successfully', 'production_damaged' => $production_damaged], 200);

                }
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Failed to Create Production Damage Goods', 'error' => $e->getMessage()], 500);
            }
            
        }
    }
    
    public function damaged_list(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_damaged=ProductionDamagedGood::with('warehouse','actions')->where('production_id',$request['production_id'])
                ->where('parent_id',0);

                if($request['search']!=null && $request['search']!=''){

                    $production_damaged = $production_damaged->where('action_type', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('goods_type', 'LIKE', '%' . $request['search'] . '%')
                        // ->orWhere('warehouse_id', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('notes', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('quantity', 'LIKE', '%' . $request['search'] . '%');
                }

                    // get custom_date 
                if ($request['custom_date']!='' && isset($request['custom_date'])) {
                    $customDate = $request->custom_date;
                    $production_damaged = $production_damaged->whereDate('created_at', $customDate);
                }

                // Count all the items
                $production_damaged_count=$production_damaged->count();

                // Pagination
                $production_damaged=$production_damaged->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->orderBy('id','desc')
                    ->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Damaged Raw not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'count'=>$production_damaged_count,
                'production_damaged'=>$production_damaged,
                'message'=>'Production Damaged List Fetch Successfully'
            ];

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

    //  create FinishedGood record
    public function finished_create(Request $request)
    {

        $validator=validator($request->all(),[
            'production_id'=>'required|integer',
            'item_id'=>'required|integer',
            'quantity'=>'required|integer',
            'action_type'=>'required',
            'date'=>'required',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];       

        } else {

            try {

                $obj['production_id'] = $request['production_id'];
                $obj['item_id'] = $request['item_id'];
                $obj['item_name'] = $request['item_name'];
                $obj['action_type'] = $request['action_type'];   //Add or Move
                $obj['date'] = $request['date'];
                $obj['warehouse_id'] = $request['warehouse_id']??0;
                $obj['zone_id'] = $request['zone_id']??0;
                $obj['rack_id'] = $request['rack_id']??0;
                $obj['bin_id'] = $request['bin_id']??0;
                $obj['quantity'] = $request['quantity'] ?? 0;
                $obj['notes'] = $request['notes'];
                $obj['attachments'] = $request['attachments'];
            
                
                // Update Production with ProductionFinishedGood id
                if ($request['id'] > 0) {

                    $production_finished = ProductionFinishedGood::where('id', $request['id'])->first();

                    if($request['action_type']=='add'){

                        $production_finished->update($obj);

                        return response()->json(['success' => true, 'message' => 'Production Finished updated successfully', 'production_finished' => $production_finished], 200);

                    }else{
                        return response()->json(['success' => false, 'message' => 'Production Finished can not update on move quantity']);
                    }

                    
                } else {
                    // Creating new ProductionScrap
                    $production_finished = ProductionFinishedGood::create($obj);

                    if($request['action_type']=='move'){

                        $stock=new StockEntryService;
                        $stock->mannualStockMove($request,$production_finished,StaticMaster::$PRODUCTION_FINISHED_GOODS,1);

                        //Creating Manufacturing Store Entry
                        $obj1['transaction_date']=$request['date']??Carbon::today()->format('Y-m-d');
                        $obj1['transaction_id']=$production_finished['id']??0;
                        $obj1['item_id']=$request['item_id']??0;
                        $obj1['unit_id']=$request['unit_id']??0;
                        $obj1['store_id']=1;    //default store 
                        $obj1['fy']=$request['fy']??2025;
                        $obj1['quantity']=$request['quantity']??0;
                        $obj1['transaction_type']=StaticMaster::$PRODUCTION_FINISHED_GOODS;
                        $obj1['taken_by']=$request['taken_by']??null;
                        $obj1['issued_by']=$request['issued_by']??null;
                        $obj1['vehicle_no']=$request['vehicle_no']??null;
                        $obj1['driver_name']=$request['driver_name']??null;
                        $obj1['driver_contact']=$request['driver_contact']??null;
                        $obj1['attachments']=$request['attachments']??null;
                        $obj1['notes']=$request['notes']??null;
                        $obj1['inout']=2;

                        // Stock added in store
                        $store=ManufacturingStore::create($obj1);

                        // Updating Store quantity in item table
                        $item=Item::where('id',$request['item_id'])->lockForUpdate()->first();

                        if($item){
                            $item['manufacturing_store']=$item['manufacturing_store']-$request['quantity'];

                            $item->save();
                        }

                    }else{
                         //We are treating item level wise from requestion item table
                        $obj1['transaction_date']=$request['date']??Carbon::today()->format('Y-m-d');
                        $obj1['transaction_id']=$production_finished['id']??0;
                        $obj1['item_id']=$request['item_id']??0;
                        $obj1['unit_id']=$request['unit_id']??0;
                        $obj1['store_id']=1;    //default store 
                        $obj1['fy']=$request['fy']??2025;
                        $obj1['quantity']=$request['quantity']??0;
                        $obj1['transaction_type']=StaticMaster::$PRODUCTION_FINISHED_GOODS;
                        $obj1['taken_by']=$request['taken_by']??null;
                        $obj1['issued_by']=$request['issued_by']??null;
                        $obj1['vehicle_no']=$request['vehicle_no']??null;
                        $obj1['driver_name']=$request['driver_name']??null;
                        $obj1['driver_contact']=$request['driver_contact']??null;
                        $obj1['attachments']=$request['attachments']??null;
                        $obj1['notes']=$request['notes']??null;
                        $obj1['inout']=1;

                        // Stock added in store
                        $store=ManufacturingStore::create($obj1);

                        // Updating Store quantity in item table
                        $item=Item::where('id',$request['item_id'])->lockForUpdate()->first();

                        if($item){
                            $item['manufacturing_store']=$item['manufacturing_store']+$request['quantity'];

                            $item->save();
                        }
                    }

                    // Update Production Status
                    $production = Production::where('id', $request['production_id'])->first();

                    // Working on Status of Production
                    if ($production) {
                        //check Production Finished Goods quantity
                        $finishedGoodsCount = ProductionFinishedGood::where('production_id', $request['production_id'])->sum('quantity');
                        if ($finishedGoodsCount >= $production->quantity) {
                            $production->status = 3; // Assuming 3 is the status for 'Finished'

                            // Update Order Status to Finished
                            $order = Order::where('id', $production['order_id'])->first();
                            if ($order) {
                                $order->status = 3; // Assuming 3 is the status for 'Finished'
                                $order->save();
                            }

                            //Update Order Production Items Status 
                            $orderItems = OrderItem::where('order_id', $production['order_id'])
                                ->where('item_id', $production['item_id'])
                                ->first();

                            if ($orderItems) {
                                $orderItems->status = 'Completed'; // Assuming 3 is the status for 'Finished'
                                $orderItems->save();
                            }
                        } else {
                            $production->status = 2; // Assuming 2 is the status for 'Partially Finished'

                            // Update Order Status to In Production
                            $order = Order::where('id', $production['order_id'])->lockForUpdate()
                                ->first();
                            
                            if ($order) {
                                $order->status = 2; // Assuming 2 is the status for 'Partially Finished'
                                $order->update();
                            }

                             //Update Order Production Items Status 
                            $orderItems = OrderItem::where('order_id', $production['order_id'])
                                ->where('item_id', $production['item_id'])
                                ->first();

                            if ($orderItems) {
                                $orderItems->status = 'Partially Finished'; // Assuming 2 is the status for 'Partially Finished'
                                $orderItems->save();
                            }
                        }
                    }
                    $production->save();


                    return response()->json(['success' => true, 'message' => 'Production Finished created successfully', 'production_finished' => $production_finished], 200);

                }
            } catch (\Exception $e) {
                return response()->json(['success' => false, 'message' => 'Failed to create production Finished Goods', 'error' => $e->getMessage()], 500);
            }
            
        }
    }
    
    public function finished_list(Request $request){

        $validator=validator($request->all(),[
            'production_id' => 'required|integer',
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

            try{

                $production_finished=ProductionFinishedGood::with('warehouse')->where('production_id',$request['production_id']);
                // ->where('is_disabled',0);

                if($request['search']!=null && $request['search']!=''){

                    $production_finished = $production_finished->where('type', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('notes', 'LIKE', '%' . $request['search'] . '%')
                        ->orWhere('quantity', 'LIKE', '%' . $request['search'] . '%');
                }

                    // get custom_date 
                if ($request['custom_date']!='' && isset($request['custom_date'])) {
                    $customDate = $request->custom_date;
                    $production_finished = $production_finished->whereDate('created_at', $customDate);
                }

                // Count all the items
                $production_finished_count=$production_finished->count();

                // Pagination
                $production_finished=$production_finished->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
                    ->orderBy('id','desc')
                    ->get();

            }catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                return [
                    'success' => false,
                    'message' => 'Production Finished Raw not found'
                ];
            }
            
            $response=[
                'success'=>true,
                'count'=>$production_finished_count,
                'production_finished'=>$production_finished,
                'message'=>'Production Finished List Fetch Successfully'
            ];

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