<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Item;
use App\Models\StockTransaction;
use App\Models\User;
use App\Models\Activity;
use validator;
use Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ItemImport;
use App\Imports\ItemExport;

use App\Service\ActivityService;
use App\Service\StockEntryService;
use App\Service\Tms\VehicleService;
use App\Service\Tms\TrailerService;
use App\Service\Tms\RimService;
use App\Service\Tms\TyreService;
use App\Service\Tms\BatteryService;
use App\Service\StaticMaster;
use Log;
use Illuminate\Support\Facades\Schema;

class ItemController extends Controller
{

    public function itemCreateUpdate(Request $request){
        // Validate Item
        $validator=validator($request->all(),[

            'name'=>'required|string',
            'type'=>'required',
            // 'unit'=>'required'
        ]);

        if ($validator->fails()) { 

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

        } else {

        // defining data variables

            $data=[

                'name','category_id','item_code',

                'sub_category_id','description','sku',

                'price','unit','tax_rate','opening_stock','type','purchase_price','tag_ids',

                'image_url','sale_acc_id','purchase_acc_id','custom_fields','as_on_date','hsn_code',

                'preferred_vendor','sale_description','purchase_description','exemption_reason',

                'tax_preference','is_sale','is_purchase','attachments',

                'related_product_ids',
                'brand_id','brand_name','company_sku','part_id',
                // Barcode
                'barcode_value','barcode_type','barcode_image'

            ];

            // Assign valiables to objects
            $obj=[];

            foreach ($data as $key => $value) {
                if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                    $obj[$value]=$request[$value]??null;
                }
            }

            if($request['id']>0){

                // Updating an existing  item
                try {

                    $item=Item::findOrFail($request['id']);

                    $item->update($obj);

                    //Creating New Product Variant
                    if(isset($request['new_items']) && $request['new_items']!=null && $request['new_items']!=''){

                        if(count($request['new_items']) > 0){

                            // Step 1: Create all items first
                            foreach ($request['new_items'] as $prod) {

                                $obj['company_sku'] = $prod['company_sku'];
                                $obj['sku'] = $prod['sku'];
                                $obj['brand_name'] = $prod['brand_name'];
                                $obj['brand_id'] = $prod['brand_id'];

                                $newItem = Item::create($obj);
                                $createdItems[] = $newItem; // collect full model
                            }

                            // Step 2: Assign related_product_ids to each
                            $allIds = collect($createdItems)->pluck('id')->toArray();

                            $allIds[] = $item['id']; // Add current item's ID

                            foreach ($createdItems as $item1) {
                                // Exclude current item's own ID
                                $relatedIds = array_values(array_diff($allIds, [$item1->id]));

                                $item1->related_product_ids = json_encode($relatedIds);
                                $item1->update(); // Or $item->update();
                            }

                            $item->related_product_ids = json_encode(array_values(array_diff($allIds, [$item->id])));
                            $item->update();
                        }
                    }

                    //Updating Opening Stock
                    if(isset($request['opening_stock_value'])){

                        $stockService=new StockEntryService;
                        $stockService->addOpeningStock($request,$item);
                    }

                      // Creating Battery Details
                    if(isset($request['battery_details']) && $request['battery_details']!=null && $request['battery_details']!=''){
                        $battery = new BatteryService;
                        $battery->batteryCreateUpdate($request,$item);
                    }

                    // Creating Rim Details
                    if(isset($request['rim_details']) && $request['rim_details']!=null && $request['rim_details']!=''){
                        $rim = new RimService;
                        $rim->rimCreateUpdate($request,$item);
                    }

                    // Creating Tyre Details
                    if(isset($request['tyre_details']) && $request['tyre_details']!=null && $request['tyre_details']!=''){
                        $tyre = new TyreService;
                        $tyre->tyreCreateUpdate($request,$item);
                    }


                    // Creating Activities
                    $activity=new ActivityService;

                    $activity->activityCreateUpdate('Item',$item['id'],'Updated');

                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id found'], 404);
                }

            }else{

                // Checking for Duplicate SKU
                if($request['sku']!=null && $request['sku']!=''){
                    $check=Item::where('sku',$request['sku'])
                        ->where('is_disabled',0)
                        ->where('type','Product')
                        ->first();

                    if($check!=null){

                        $response=[

                            'item'=>$check,
                            'success'=>false,
                            'message'=>'Duplicate SKU '.$check['sku'] .' Found!'
                        ];
                        return response()->json($response);

                    }
                }
                // Checking for Duplicate Name
                // if($obj['name'] != null && $obj['name'] != ''){
                //     $checkName = Item::where('name', $obj['name'])
                //                     ->where('is_disabled', 0)
                //                     ->where('type', 'Product')
                //                     ->first();
                
                //     if($checkName != null){
                //         $response = [
                //             'item' => $checkName,
                //             'success' => false,
                //             'message' => 'Duplicate Name '. $checkName['name'] .' Found!'
                //         ];
                
                //         return response()->json($response);
                //     }
                // }

                // Creating New Item
                $item=Item::create($obj);

                // Creating Opening Stock
                if(isset($request['opening_stock_value'])){

                    $stockService=new StockEntryService;
                    $stockService->addOpeningStock($request,$item);
                }

                //Creating New Product Variant
                if(isset($request['new_items']) && $request['new_items']!=null && $request['new_items']!=''){

                    if(count($request['new_items']) > 0){

                        // Step 1: Create all items first
                        foreach ($request['new_items'] as $prod) {

                            $obj['company_sku'] = $prod['company_sku'];
                            $obj['sku'] = $prod['sku'];
                            $obj['brand_name'] = $prod['brand_name'];
                            $obj['brand_id'] = $prod['brand_id'];

                            $newItem = Item::create($obj);
                            $createdItems[] = $newItem; // collect full model
                        }

                        // Step 2: Assign related_product_ids to each
                        $allIds = collect($createdItems)->pluck('id')->toArray();

                        $allIds[] = $item['id']; // Add current item's ID

                        foreach ($createdItems as $item1) {
                            // Exclude current item's own ID
                            $relatedIds = array_values(array_diff($allIds, [$item1->id]));

                            $item1->related_product_ids = json_encode($relatedIds);
                            $item1->update(); // Or $item->update();
                        }

                        $item->related_product_ids = json_encode(array_values(array_diff($allIds, [$item->id])));
                        $item->update();
                    }
                }

                // Creating Battery Details
                if(isset($request['battery_details']) && $request['battery_details']!=null && $request['battery_details']!=''){
                    $battery = new BatteryService;
                    $battery->batteryCreateUpdate($request,$item);
                }

                // Creating Rim Details
                if(isset($request['rim_details']) && $request['rim_details']!=null && $request['rim_details']!=''){
                    $rim = new RimService;
                    $rim->rimCreateUpdate($request,$item);
                }

                // Creating Tyre Details
                if(isset($request['tyre_details']) && $request['tyre_details']!=null && $request['tyre_details']!=''){
                    $tyre = new TyreService;
                    $tyre->tyreCreateUpdate($request,$item);
                }

                // Creating Activities
                $activity=new ActivityService;
                $activity->activityCreateUpdate('Item',$item['id'],'Created');

            }

            $response=[
                'item'=>$item,
                'success'=>true,
                'message'=>'Item Created Successfully'
            ];

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


    public function itemList(Request $request){

        $user=Auth::user();

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

        // if ($validator->fails()) { 

        //     return [
        //         'success' => false, 

        //         'message' => $validator->errors()->first(),

        //         'items_details' => null

        //     ];

        // } else {

        if($user!=null){

            $item=Item::where('organisation_id',$user['active_organisation'])
                ->with('category','sub_category')
                ->where('is_disabled',0);

            
            // Filters
            if(isset($request['active'])){

                $item=$item->where('active',$request['active']);

            }

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

                // Goods , Services , Raw ,Packaging
                $item=$item->where('part_id',$request['part_id']);

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

                // Goods , Services , Raw ,Packaging
                $item=$item->where('type',$request['type']);

            }

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

                // Goods , Services , Raw ,Packaging
                $item=$item->whereIn('type',$request['types']);
            }

            if(isset($request['manufacturing_store']) && $request['manufacturing_store']==1){

                // Goods , Services , Raw ,Packaging
                $item=$item->where('manufacturing_store','>',0);
            }

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

                $item = $item->where(function ($query) use ($request) {

                    $query->where('name', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('sku', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('brand_name', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('description', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhereHas('category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    })

                    ->orWhereHas('sub_category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    });

                });
            }

            // get Alphabetically data by name

            if ($request->has('name') && $request->name === '1') {

                $item = $item->orderBy('name');

            }
            // get price data by ascending  or descending

            if ($request->has('price')) {

                if ($request->price === '1') {

                    $item = $item->orderBy('price');

                } elseif ($request->price === '0') {

                    $item = $item->orderByDesc('price');

                }

            }

                // get purchase_price data by ascending  or descending

            if ($request->has('purchase_price')) {

                if ($request->purchase_price === '1') {

                    $item = $item->orderBy('purchase_price');

                } elseif ($request->purchase_price === '0') {

                    $item = $item->orderByDesc('purchase_price');

                }

            }

            //In store or not
            if ($request->in_store == '1' && isset($request->in_store)) {
                $item = $item->where('in_store', 1);
            } 

            //In Tms store or not
            if ($request->in_tms == '1' && isset($request->in_tms)) {
                $item = $item->where('in_tms', 1);
            } 
            if ($request->tms_store ==1) {
                $item = $item->where('tms_store','>',0);
            } 

            // Count all the items

            $item_count=$item->count();

            // Pagination

            $item=$item->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)

                ->orderBy('id','desc')

                ->get();

            $response=[

                'success'=>true,

                'message'=>'Items fetched Successfully',

                'total_items'=>$item_count,

                'item'=>$item

            ];

        } else {

            $response=[

                'success'=>false,

                'message'=>'Your Are not Authenticated',

                'total_items'=>null,

                'item'=>null

            ];
        }

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

    }



    public function itemDetails(Request $request){

        $user=Auth::user();

        if($user!=null){

            // Validate Item

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

            if ($validator->fails()) { 

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

            } else {

                $preferred_vendor=[];

                // Fetch item details
                $item_details =  Item::where('id',$request->input('item_id'))
                    ->with('activity','activity.entryby:id,name','category','sub_category',
                            'purchase_account:id,account_name','sale_account:id,account_name',
                            // 'battery_details','rim_details','tyre_details','brand'
                            )
                    ->first();

                 // If preferred_vendor_ids is a string like "[326]", we need to convert it to an array
                if (isset($item_details['preferred_vendor']) && $item_details['preferred_vendor']!=null && $item_details['preferred_vendor']!='') {

                    $preferred_vendor_ids = json_decode($item_details['preferred_vendor'], true);

                    $preferred_vendor=User::whereIn('id',$preferred_vendor_ids)->get();
                }

                // Fetch Warehouse stock Details
                // Get total quantity by warehouse
                $total_quantity_by_warehouse = StockTransaction::where('item_id', $request->input('item_id'))
                    ->with('warehouse:id,name',)
                    ->where('quantity','>', 0)
                    ->where('rolledback', 0)
                    ->where('fy', $request['fy'])
                    ->where('warehouse_id', '!=', 0) // Add this line
                    ->groupBy('warehouse_id')
                    // ->selectRaw('warehouse_id, sum(quantity) as total_quantity')
                    ->selectRaw(
                        'warehouse_id, 
                        SUM(CASE WHEN `inout` = 1 THEN quantity ELSE 0 END) - 
                        SUM(CASE WHEN `inout` = 2 THEN quantity ELSE 0 END) as total_quantity'
                    )
                    ->get();

                // Get total quantity by zone
                $total_quantity_by_zone = StockTransaction::where('item_id', $request->input('item_id'))
                    ->with('zone.warehouse:id,name')
                    ->where('rolledback', 0)
                    ->where('quantity','>', 0)
                    ->where('fy', $request['fy'])
                    ->where('zone_id', '!=', 0) // Add this line
                    ->groupBy('zone_id')
                    // ->selectRaw('zone_id, sum(quantity) as total_quantity')
                    ->selectRaw(
                        'zone_id, 
                        SUM(CASE WHEN `inout` = 1 THEN quantity ELSE 0 END) - 
                        SUM(CASE WHEN `inout` = 2 THEN quantity ELSE 0 END) as total_quantity'
                    )
                    ->get();

                // Get total quantity by rack
                $total_quantity_by_rack = StockTransaction::where('item_id', $request->input('item_id'))
                    ->with('rack','rack.warehouse:id,name','rack.zone:id,name')
                    ->where('rolledback', 0)
                    ->where('quantity','>', 0)
                    ->where('fy', $request['fy'])
                    ->where('rack_id', '!=', 0) // Add this line
                    ->groupBy('rack_id')
                    // ->selectRaw('rack_id, sum(quantity) as total_quantity')
                    ->selectRaw(
                        'rack_id, 
                        SUM(CASE WHEN `inout` = 1 THEN quantity ELSE 0 END) - 
                        SUM(CASE WHEN `inout` = 2 THEN quantity ELSE 0 END) as total_quantity'
                    )
                    ->get();

                // Get total quantity by bin
                $total_quantity_by_bin = StockTransaction::where('item_id', $request->input('item_id'))
                    ->with('bin.warehouse:id,name','bin.rack:id,name','bin.zone:id,name','bin')
                    ->where('rolledback', 0)
                    ->where('quantity','>', 0)
                    ->where('fy', $request['fy'])
                    ->where('bin_id', '!=', 0) // Add this line
                    ->groupBy('bin_id')
                    // ->selectRaw('bin_id, sum(quantity) as total_quantity')
                    ->selectRaw(
                        'bin_id, 
                        SUM(CASE WHEN `inout` = 1 THEN quantity ELSE 0 END) - 
                        SUM(CASE WHEN `inout` = 2 THEN quantity ELSE 0 END) as total_quantity'
                    )
                    ->get();

                // Get total quantity by warehouse, rack, and bin
                $total_quantity_details = StockTransaction::where('item_id', $request->input('item_id'))
                    ->with('warehouse:id,name','rack:id,name','zone:id,name','bin:id,name,bin_code')
                    ->where('rolledback', 0)
                    ->where('fy', $request['fy'])
                    ->groupBy('warehouse_id', 'rack_id', 'bin_id','zone_id')
                    ->selectRaw('warehouse_id,zone_id , rack_id, bin_id, sum(quantity) as total_quantity')
                    ->selectRaw(
                        'warehouse_id,zone_id , rack_id, bin_id,
                        SUM(CASE WHEN `inout` = 1 THEN quantity ELSE 0 END) - 
                        SUM(CASE WHEN `inout` = 2 THEN quantity ELSE 0 END) as total_quantity'
                    )
                    ->get();

                $opening_stock = StockTransaction::where('item_id', $request->input('item_id'))
                    ->where('fy', $request['fy'])
                    ->where('transaction_type', StaticMaster::$OPENING_STOCK_TYPE)
                    ->where('rolledback', 0)
                    ->first();

                $response = [
                    'success' => true,
                    'message' => 'Item detail fetched Successfully',
                    'item_details' => $item_details,
                    'opening_stock' => $opening_stock,
                    'preferred_vendor'=>$preferred_vendor,
                    'total_quantity_by_warehouse'=>$total_quantity_by_warehouse,
                    'total_quantity_by_rack'=>$total_quantity_by_rack,
                    'total_quantity_by_zone'=>$total_quantity_by_zone,
                    'total_quantity_by_bin'=>$total_quantity_by_bin,
                    'total_quantity_details'=>$total_quantity_details
                ];

            } 

        } else {

            $response=[
                'success'=>false,
                'message'=>'Your Are not Authenticated',
                'items_details'=>null
            ];

        }

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


    public function stockDetails(Request $request){
         // Validate Item

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

            'item_id'=>'required|integer',
            'fy'=>'required'

        ]);

        if ($validator->fails()) { 

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

        } else {
            $stock_details=StockTransaction::where('item_id',$request->input('item_id'))

                ->with('warehouse','rack','zone','bin')
                ->where('rolledback',0)

                ->where('fy',$request['fy']);

            if(isset($request['transaction_date']) && $request['transaction_date']!=null && $request['transaction_date']!=''){
                $stock_details=$stock_details->whereDate('transaction_date',$request['transaction_date']);
            }

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

                $stock_details = $stock_details->where(function ($query) use ($request) {

                    $query->where('quantity', 'LIKE', '%' . $request['quantity'] . '%')

                    ->orWhere('description', 'LIKE', '%' . $request['search'] . '%');
                });

            }

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

                $customDate = $request->custom_date;

                $stock_details = $stock_details->whereDate('transaction_date', $customDate);

            }

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

                $fromDate = $request->fromDate;

                $toDate = $request->toDate;

                // 'fromDate' and 'toDate'

                $stock_details = $stock_details->whereBetween('transaction_date', [$fromDate, $toDate]);

            }
            
            $stock_details=$stock_details->orderBy('transaction_date','desc')

                ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)

                ->get();

                $response = [
                    'success' => true,
                    'message' => 'Item Srock detail fetched Successfully',
                    'stock_details' => $stock_details,
                ];

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


    public function itemActivity(Request $request){
        // Validate Item

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

            'item_id'=>'required|integer',
            'fy'=>'required'

        ]);

        if ($validator->fails()) { 

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

        } else {

            $activity=Activity::where('module','Item')
                ->where('module_id',$request['item_id'])
                ->with('entryby');

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

                $customDate = $request->custom_date;

                $activity = $activity->whereDate('date', $customDate);

            }
    
                if ($request['from_date']!='' && isset($request['to_date'])) {
    
                    $fromDate = $request->from_date;
    
                    $toDate = $request->to_date;
    
                    // 'fromDate' and 'toDate'
    
                    $activity = $activity->whereBetween('date', [$fromDate, $toDate]);
    
                }
                
                $activity=$activity->orderBy('date','desc')
    
                    ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
    
                    ->get();
    
                    $response = [
                        'success' => true,
                        'message' => 'Item Activity fetched Successfully',
                        'activity' => $activity,
                    ];
    
                return response()->json($response);
        }
    }

    // Import Excel To database
    public function import(Request $request){
        // Validate Item

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

            'file' => 'required|file'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            $file = $request->file('file');
            Excel::import(new ItemImport, $file);
            // Creating Activities

            $activity=new ActivityService;

            $activity->activityCreateUpdate('Item',0,'Imported');
            // return redirect()->back()->with('success', 'Item imported successfully!');

            $response=[

                'success'=>true,

                'message'=>'Item Excel Imported Successfully'

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

        }

    }

    // Export data to excel  File
    public function export(){

        // Creating Activities

        $activity=new ActivityService;

        $activity->activityCreateUpdate('Item',0,'Exported');



        return Excel::download(new ItemExport, 'products.xlsx');

    }

    // item custome fields

    public  function customItemFields(){

       $fields=CustomField::where('type','item')->get();

       return response()->json([

           'fields'=>$fields

       ]);

    }



    public function  addCustomField(Request $request){

          $this->validate($request,[
              'field_name'=>'required',
              'label'=>'required',
              'field_type'=>'required',
          ]);

         $customField= new CustomField();

         $customField->field_name='items';

         $customField->field_name=$request->field_name;

         $customField->field_type=$request->field_type;

         $customField->required_status=$request->required_status??0;

         $customField->type='item';

         $customField->save();

         return response()->json(['msg'=>'Field added Successfully']);

     }

     

    
    
     public function status(Request $request){

         // Validate Item

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

            'item_id'=>'required|integer',

            'active'=>'required|integer'

        ]);



        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first(),

            ];



        } else {



            try{

                $item =  Item::where('id',$request->input('item_id'))->first();

                $item['active']=$request['active'];

                $item->update();



                $response=[

                    'success'=>true,

                    'message'=>'Status Updated successfully.',

                    'item'=>$item

                ];

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['message' => 'Invalid Id found'], 404);

            }



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



        }

    }



    public function delete(Request $request){

        $user=Auth::user();
        // Validate Item
        $validator=validator($request->all(),[
           'item_id'=>'required|integer'
       ]);

       if ($validator->fails()) { 

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

       } else {

           try{

               $item =  Item::where('id',$request->input('item_id'))

                    ->where('organisation_id',$user['active_organisation'])

                    ->first();

               $item['is_disabled']=1;

               $item->update();

               $response=[
                   'success'=>true,
                   'message'=>'Item Deleted successfully.'
               ];

           } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

               // Return error message in JSON if ID not found
               return response()->json(['message' => 'Invalid Id found'], 404);
           }

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

       }

    }

    public function relatedItemsList(Request $request)
    {
        $validator = validator($request->all(), [
            'item_id' => 'required'
        ]);

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

        $item = Item::find($request['item_id']);

        // Decode the JSON string to array
        $related_ids = json_decode($item->related_product_ids, true); // <- fix here

        // Validate that it's an array
        if (!is_array($related_ids)) {
            $related_ids = [];
        }

        $related_items = Item::whereIn('id', $related_ids)
            ->with(['category', 'sub_category']);

        if (!empty($request['search'])) {
            $related_items = $related_items->where(function ($query) use ($request) {
                $query->where('name', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('sku', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('brand_name', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('description', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('part_id', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhereHas('category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    })
                    ->orWhereHas('sub_category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    });
            });
        }

        $count = $related_items->count();

        return response()->json([
            'success' => true,
            'message' => 'Related Items fetched successfully.',
            'total' => $count,
            'items' => $related_items->get() // <- don't forget ->get() here
        ]);
    }

}

