<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ToDoList;
use App\Models\purchaseProductsBadgstock;
use App\Models\productCategory;
use App\Models\product;
use App\Models\purchase;
use App\Models\Branches;
use App\Models\purchaseProduct;
use App\Models\saleProduct;
use App\Models\productTransfer;
use Illuminate\Support\Facades\DB;
use App\Models\purchaseProductItem;
use Carbon\Carbon;
class productController extends Controller
{
    public function addProduct()
    {   
        $productCategories = productCategory::get();
        $ToDoList = ToDoList::get();
        return view('Section.Product.addProduct',compact('ToDoList','productCategories'));
      
    }


    public function BarCode()
    {   
        $productCategories = productCategory::get();
        $ToDoList = ToDoList::get();
        return view('Section.Product.barcode',compact('ToDoList','productCategories'));
      
    }

  public function ProductData(Request $request)
    {   
        $data = $request->all();
        // dd($data);
        $id =$data['id'];  
        $productCategories = productCategory::get();

        $products = product::where('id', $id)->first();

         $purchaseProductsBadgstocks = purchaseProductsBadgstock::leftJoin('branches', 'purchase_products_badgstock.branches_id', '=', 'branches.id')
        ->leftJoin('products', 'purchase_products_badgstock.product_id', '=', 'products.id')
        ->where('product_id', $id)
        ->select('purchase_products_badgstock.*','branches.branch_name','products.image','products.name','products.model','products.code')
        ->get();

        $purchaseSummary = purchaseProductsBadgstock::leftJoin('branches', 'purchase_products_badgstock.branches_id', '=', 'branches.id')
    ->leftJoin('products', 'purchase_products_badgstock.product_id', '=', 'products.id')
    ->where('product_id', $id)
    ->selectRaw('
        SUM(purchase_products_badgstock.quantity) as total_quantity,
        SUM(purchase_products_badgstock.total_cost) as total_cost,
        SUM(purchase_products_badgstock.sale_quantity) as total_sale_quantity
    ')
    ->first();

        $ToDoList = ToDoList::get();
        return view('Section.Product.productDetails',compact('ToDoList','productCategories','purchaseProductsBadgstocks','products','purchaseSummary'));
      
    }


public function ProductBranchData(Request $request)
    {   
        $data = $request->all();
        $id =$data['id'];  
        $branches = Branches::get();
        $branchesName = Branches::where('id', $id)->value('branch_name');
        $productCategories = productCategory::get();

        $products = product::where('id', $id)->first();

         $purchaseProductsBadgstocks = purchaseProductsBadgstock::leftJoin('branches', 'purchase_products_badgstock.branches_id', '=', 'branches.id')
        ->leftJoin('products', 'purchase_products_badgstock.product_id', '=', 'products.id')
        ->where('branches.id', $id)
        ->select('purchase_products_badgstock.*','branches.branch_name','products.price','products.image','products.name','products.model','products.code')
        ->get();

        $purchaseSummary = purchaseProductsBadgstock::leftJoin('branches', 'purchase_products_badgstock.branches_id', '=', 'branches.id')
    ->leftJoin('products', 'purchase_products_badgstock.product_id', '=', 'products.id')
     ->where('branches.id', $id)
    ->selectRaw('
        SUM(purchase_products_badgstock.quantity) as total_quantity,
        SUM(purchase_products_badgstock.total_cost) as total_cost,
        SUM(purchase_products_badgstock.sale_quantity) as total_sale_quantity
    ')
    ->first();

        $ToDoList = ToDoList::get();
        return view('Section.Product.productBranchDetails',compact('ToDoList','branchesName','branches','productCategories','purchaseProductsBadgstocks','products','purchaseSummary'));
      
    }
    
    // public function transferProduct(Request $request)
    // {   
    //     $data = $request->all();
    //     dd($data);
       
    //     $mortgageData = $data['mortgageData'] ?? [];

    //     foreach ($mortgageData as $rowData) {

    //            $preexistProductsBadgstock = purchaseProductsBadgstock::where('each_cost', $rowData['each_cost'])
    //         ->where('product_id', $rowData['itemDataId'])
    //         ->where('branches_id', $rowData['fromBranch'])->get();

    //         $existProductsBadgstock = purchaseProductsBadgstock::where('each_cost', $rowData['each_cost'])
    //         ->where('product_id', $rowData['itemDataId'])
    //         ->where('branches_id', $rowData['TOBranch'])->get();

    //         if($rowData['type'] == "product item"){
    //         $existingItemQuantity = purchaseProductItem::where('product_id', $rowData['itemDataId'])
    //         ->where('branches_id', $rowData['fromBranch'])
    //         ->where('each_cost', $rowData['each_cost'])
    //         ->where('imu_number', $rowData['imu_number'])
    //         ->get(); 

    //         $existingItemQuantity->branches_id =  $rowData['TOBranch'];
    //         }

    //          $preexistProductsBadgstock->quantity -= $rowData['quantity'];

    //         if($existProductsBadgstock){
    //             $existProductsBadgstock->quantity += $rowData['quantity'];
    //         }



    //         else{
    //              purchaseProductsBadgstock::create([
    //                         'product_id' => $rowData['itemDataId'],
    //                         'purchases_id' => $preexistProductsBadgstock->id,
    //                         'quantity' => $rowData['quantity'],
    //                         'branches_id' => $rowData['TOBranch'],
    //                         'total_cost' => $rowData['each_cost'] * $rowData['quantity'],
    //                         'each_cost' => $rowData['each_cost'],
    //                     ]);
    //         }

            
    //     }

    // }

    public function transferProduct(Request $request)
{   
    $data = $request->all();
  
    $mortgageData = $data['mortgageData'] ?? [];

    foreach ($mortgageData as $rowData) {
        // FROM branch record
        $fromStock = purchaseProductsBadgstock::where('each_cost', $rowData['each_cost'])
            ->where('product_id', $rowData['itemDataId'])
            ->where('price', $rowData['price'])
            ->where('branches_id', $rowData['fromBranch'])
            ->first();

        // TO branch record
        $toStock = purchaseProductsBadgstock::where('each_cost', $rowData['each_cost'])
            ->where('product_id', $rowData['itemDataId'])
            ->where('price', $rowData['price'])
            ->where('branches_id', $rowData['TOBranch'])
            ->first();

            
             productTransfer::create([
                'product_id' => $rowData['itemDataId'],
                'quantity' => $rowData['quantity'],
                'date' => Carbon::today()->toDateString(),
                'from_branches_id' => $rowData['fromBranch'] ,
                'to_branches_id' => $rowData['TOBranch'],
            ]);

        // If item type is 'product item', update its branch
        if ($rowData['type'] === "product item") {
            
            $productItem = purchaseProductItem::where('product_id', $rowData['itemDataId'])
                ->where('branches_id', $rowData['fromBranch'])
                ->where('each_cost', $rowData['each_cost'])
                ->where('price', $rowData['price'])
                ->where('imu_number', $rowData['imu_number'])
                ->first();

            if ($productItem) {
                $productItem->branches_id = $rowData['TOBranch'];
                $productItem->save();
            }
        }

        // Reduce quantity from FROM branch
        if ($fromStock) {
            $fromStock->quantity -= $rowData['quantity'];
            $fromStock->save();
        }

        if ($toStock) {
            // Increase quantity in TO branch
            $toStock->quantity += $rowData['quantity'];
            $toStock->save();
        } else {
            // Create new stock record in TO branch
            purchaseProductsBadgstock::create([
                'product_id' => $rowData['itemDataId'],
                'purchases_id' => $fromStock->purchases_id ,
                'quantity' => $rowData['quantity'],
                'price' => $rowData['price'],
                'branches_id' => $rowData['TOBranch'],
                'total_cost' => $rowData['each_cost'] * $rowData['quantity'],
                'each_cost' => $rowData['each_cost'],
            ]);
        }
    }

    return response()->json(['message' => 'Product transferred successfully.']);
}

public function returnProduct(Request $request)
    {  
        $ToDoList = ToDoList::get();
        return view('Section.Product.returnProduct',compact('ToDoList'));
    }

  public function prductlistData(Request $request)
    {   
        $data = $request->all();
        $id =$data['id'];  

        $purchaseProductItem = purchaseProductItem::leftJoin('purchases', 'purchase_product_items.purchases_id', '=', 'purchases.id')
    ->where('products_badgstock_id', $id)
    ->select(
        'purchase_product_items.*',
        'purchases.purchases_id',
        DB::raw("CASE 
                    WHEN EXISTS (
                        SELECT 1 FROM sale_items 
                        WHERE sale_items.item_id = purchase_product_items.id
                    ) THEN 'sold'
                    ELSE 'not sold'
                 END AS sale_status")
    )
    ->get();
         
        $response['data'] = $purchaseProductItem;
        return response()->json($response);
    }

    public function listProduct()
    {   
        $productCategories = productCategory::get();
        $ToDoList = ToDoList::get();
        return view('Section.Product.listProduct',compact('ToDoList','productCategories'));
      
    }

public function listProductBranches()
    {   
        $productCategories = productCategory::get();
        $ToDoList = ToDoList::get();
        return view('Section.Product.productBranchReport',compact('ToDoList','productCategories'));
      
    }


public function quantityAdjustment()
    {   
        $productCategories = productCategory::get();
        $ToDoList = ToDoList::get();
        $branches = Branches::get();
        return view('Section.Product.quantityAdjesment',compact('ToDoList','branches','productCategories'));
      
    }

    

 public function Productlist()
    {   
        $product = product::get();
      
        $response['data'] = $product;
        return response()->json($response);
      
    }


public function ProductlistBranch()
    {   
       $product = DB::table('purchase_products_badgstock')
    ->leftJoin('branches', 'purchase_products_badgstock.branches_id', '=', 'branches.id')
    ->select(
        'branches.branch_name',
        'purchase_products_badgstock.branches_id',
        DB::raw('SUM(purchase_products_badgstock.quantity) as total_quantity'),
        DB::raw('SUM(purchase_products_badgstock.sale_quantity) as total_sale_quantity')
    )
    ->groupBy('purchase_products_badgstock.branches_id', 'branches.branch_name')
    ->get();
      
        $response['data'] = $product;
        return response()->json($response);
      
    }


    

   public function productQytAdjustment(Request $request)
{
    $data = $request->all();
    $mortgageData = $data['mortgageData'] ?? [];

    foreach ($mortgageData as $rowData) {

        // 1️⃣ Find stock for this branch & product
        $purchaseProductsBadgstock = purchaseProductsBadgstock::where('each_cost', $rowData['each_cost'])
            ->where('product_id', $rowData['productid'])
            ->where('branches_id', $rowData['branch'])
            ->first();

        if (!$purchaseProductsBadgstock) {
            // 2️⃣ Fallback: find a general stock record with each_cost = 0 & branch 0
            $purchaseProductsBadgstock = purchaseProductsBadgstock::where('each_cost', 0)
                ->where('product_id', $rowData['productid'])
                ->where('price', $rowData['Price'])
                ->where('branches_id', null)
                ->first();

                


            // 3️⃣ If still not found, create a new one
            if (!$purchaseProductsBadgstock) {
                $purchaseProductsBadgstock = new purchaseProductsBadgstock();
                $purchaseProductsBadgstock->each_cost = 0;
                $purchaseProductsBadgstock->product_id = $rowData['productid'];
                $purchaseProductsBadgstock->price = $rowData['Price'];
                $purchaseProductsBadgstock->branches_id = $rowData['branch'];
                $purchaseProductsBadgstock->quantity = 0;
                $purchaseProductsBadgstock->total_cost = 0;
            } else {
                // Update branch if using fallback record
                $purchaseProductsBadgstock->branches_id = $rowData['branch'];
            }
        }

        
        // 4️⃣ Apply quantity and cost adjustment
        if (strtolower($rowData['adjustmentType']) == "addition") {
            $purchaseProductsBadgstock->quantity += $rowData['quantity'];
            $purchaseProductsBadgstock->total_cost += $rowData['totalPrice'];
        } else if (strtolower($rowData['adjustmentType']) == "substraction") {
    
            $purchaseProductsBadgstock->quantity -= $rowData['quantity'];
            $purchaseProductsBadgstock->total_cost -= $rowData['totalPrice'];
        }

        $purchaseProductsBadgstock->save();

        // 5️⃣ Update product quantity
        $product = product::find($rowData['productid']);
        if ($product) {
            if (strtolower($rowData['adjustmentType']) == "addition") {
                $product->quantity += $rowData['quantity'];
            } else if (strtolower($rowData['adjustmentType']) == "substraction") {
                $product->quantity -= $rowData['quantity'];
            }
            $product->save();
        }
    }

    return response()->json(['message' => 'Product quantity adjusted successfully.']);
}


    public function storeProduct(Request $request)
    {

        $data = $request->all();
        // dd($data);

        
     
        $product =  product::create([
            'name' => $data['ProductName'],
            'model' => $data['model'],
            'products_type' => $data['productstype'],
            'portion_sizes' => $data['portionSizes'],
            'code' => $data['Code'],
            'product_category_id' => $data['Category'],
            'product_sub_category_id' => $data['subCategory'],
            'product_brand_id' => $data['brand'],
            'alert_quantity' => $data['AlertQuantity'],
            'price' => $data['Price'],
            'Wholesale_price' => $data['WholesalePrice'],
            'Wholesale_quantity' => $data['WholesaleQuantity'],             
            'description' => $data['description'],

        ]); 

        if ($data['productstype'] != "Products") {
    // Check if the badgstock already exists for this product
    $exists = purchaseProductsBadgstock::where('product_id', $product->id)->exists();

    if (!$exists) {
        purchaseProductsBadgstock::create([
            'product_id' => $product->id,
            'quantity' => 0,
            'total_cost' => 0,
            'each_cost' => 0,
            'price' => 0,
        ]);
    }
}


      if ($data['productstype'] == "Products") {
    // Check if the badgstock already exists for this product
    $exists = purchaseProductsBadgstock::where('product_id', $product->id)->exists();

    if (!$exists) {
        purchaseProductsBadgstock::create([
            'product_id' => $product->id,
            'quantity' => 0,
            'total_cost' => 0,
            'each_cost' => 0,
            'price' => $data['Price'],
        ]);
    }
}


          // Handle the image upload
    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $imageName = time() . rand(1, 9) . '.' . $image->getClientOriginalExtension();
        $image->move('assets/Product', $imageName);

        // Save the image details (if associated with another model or field in `People`)
        $product->image = 'assets/Product/' . $imageName;
        $product->save();
    }

    return response()->json([
        'message' => 'Supplier created successfully!',
        'data' => $product,
    ], 201);
}






    public function updateProduct(Request $request)
{
    $data = $request->all();
    $Productid = $data['Productid'];

    // Find the existing product
    $product = product::find($Productid);

    if (!$product) {
        return response()->json(['message' => 'Product not found.'], 404);
    }

    // Update product fields
    $product->name = $data['ProductName'];
    $product->model = $data['model'];
    $product->products_type = $data['productstype'];
    $product->portion_sizes = $data['portionSizes'];
    $product->code = $data['Code'];
    $product->product_category_id = $data['Category'];
    $product->product_sub_category_id = $data['subCategory'];
    $product->product_brand_id = $data['brand'];
    $product->alert_quantity = $data['AlertQuantity'];
    $product->price = $data['Price'];
    $product->Wholesale_price = $data['WholesalePrice'];
    $product->Wholesale_quantity = $data['WholesaleQuantity'];
    $product->description = $data['description'];
    $product->save();

    // Handle badge stock creation for non-"Products"
    if ($data['productstype'] != "Products") {
        $exists = purchaseProductsBadgstock::where('product_id', $product->id)->exists();

        if (!$exists) {
            purchaseProductsBadgstock::create([
                'product_id' => $product->id,
                'quantity' => 0,
                'total_cost' => 0,
                'each_cost' => 0,
                'price' => 0,
            ]);
        }
    }

    // Handle the image upload
    if ($request->hasFile('image')) {
        $image = $request->file('image');
        $imageName = time() . rand(1, 9) . '.' . $image->getClientOriginalExtension();
        $image->move('assets/Product', $imageName);

        $product->image = 'assets/Product/' . $imageName;
        $product->save();
    }

    return response()->json([
        'message' => 'Product updated successfully!',
        'data' => $product,
    ], 200);
}



public function deleteProduct(Request $request)
{
    $data = $request->all();
    $Productid = $data['Productid'];

    // Find the product
    $product = product::find($Productid);

    if (!$product) {
        return response()->json([
            'message' => 'Product not found.'
        ], 404);
    }

    // Optional: delete related image file if exists
    if ($product->image && file_exists(public_path($product->image))) {
        unlink(public_path($product->image));
    }

    // Delete the product
    $product->delete();

    return response()->json([
        'message' => 'Product deleted successfully.'
    ], 200);
}


    


    public function searchProduct(Request $request)
    {
        $query = $request->get('query');
        // Fetch similar products (adjust to your database structure)
        $suggestions = Product::where('name', 'like', "%{$query}%")
            ->orWhere('code', 'like', "%{$query}%")
            ->limit(10)
            ->get(['id', 'name', 'code']); // Select 'id', 'name', and 'code'

       

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

    // public function updateProductItem(Request $request)
    // {
    //     $data = $request->all();
    //     $id =$data['id'];
    //     $purchaseProductsBadgstock = purchaseProductsBadgstock::where('id', $id)->first();
    //     $productId = $purchaseProductsBadgstock->product_id;
    //     $purchasesId = $purchaseProductsBadgstock->purchases_id;
    //     $each_cost = $purchaseProductsBadgstock->each_cost;
    //     $total_cost = $purchaseProductsBadgstock->total_cost;
    //     $price = $purchaseProductsBadgstock->price;
    //     $price = $purchaseProductsBadgstock->price;
    //     $branches_id = $purchaseProductsBadgstock->branches_id;
    //     $quantity = $purchaseProductsBadgstock->quantity;

        
       

    //     if($purchaseProductsBadgstock->price != $data['productPrice'] || $purchaseProductsBadgstock->each_cost != $data['productCoat']){
        
            

    //         $existpurchaseProductsBadgstock = purchaseProductsBadgstock::where('id', $id)
    //         ->where('product_id', $productId)
    //         ->where('price', $data['productPrice'])
    //         ->where('each_cost', $data['productCoat'])->first();

    //         if($existpurchaseProductsBadgstock){
    //                 $existpurchaseProductsBadgstock->quantity += $quantity;
    //                 $existpurchaseProductsBadgstock->save();
    //         }else{
    //             purchaseProductsBadgstock::create([
    //                 'product_id' => $productId,
    //                 'purchases_id' => $purchasesId,
    //                 'quantity' => $quantity,
    //                 'branches_id' => $branches_id,
    //                 'total_cost' => $data['productCoat'] * $quantity,
    //                 'each_cost' => $data['productCoat'],
    //                 'price' => $data['productPrice'],
    //             ]);
    //         }

    //         $purchaseProduct = purchaseProduct::where('id', $id)
    //         ->where('product_id', $productId)
    //         ->where('purchases_id', $purchasesId)
    //         ->where('price', $price)
    //         ->where('each_cost', $each_cost)->first();

    //         $purchaseProduct->each_cost = $data['productCoat'];
    //         $purchaseProduct->price = $data['productPrice'];
    //         $purchaseProduct->save();

    //         $purchaseProductsBadgstock->delete();
           
    //     }
    //     $purchase = purchase::where('id', $purchasesId)->first();
    //     $purchaseTotalCost = $purchase->total_cost;
    //     $diffTotalCost = ($data['productCoat'] * $quantity) - $total_cost;
    //     $purchase->total_cost += $diffTotalCost;
    //     $purchase->save();
    // }

//     public function updateProductItem(Request $request)
// {
//     $data = $request->all();
//     // dd( $data);
//     $id = $data['id'];

//     $purchaseProductsBadgstock = purchaseProductsBadgstock::find($id);
//     if (!$purchaseProductsBadgstock) return;

//     $productId = $purchaseProductsBadgstock->product_id;
//     $purchasesId = $purchaseProductsBadgstock->purchases_id;
//     $each_cost = $purchaseProductsBadgstock->each_cost;
//     $total_cost = $purchaseProductsBadgstock->total_cost;
//     $price = $purchaseProductsBadgstock->price;
//     $branches_id = $purchaseProductsBadgstock->branches_id;
//     $quantity = $purchaseProductsBadgstock->quantity;



//     if ($price != $data['productPrice'] || $each_cost != $data['productCoat']) {

//         $existingStock = purchaseProductsBadgstock::where([
//             ['product_id', '=', $productId],
//             ['price', '=', $data['productPrice']],
//             ['each_cost', '=', $data['productCoat']]
//         ])->first();

        

//         if ($existingStock) {
//             $existingStock->quantity += $quantity;
//             $existingStock->save();
//         } else {
//             purchaseProductsBadgstock::create([
//                 'product_id' => $productId,
//                 'purchases_id' => $purchasesId,
//                 'quantity' => $quantity,
//                 'branches_id' => $branches_id,
//                 'total_cost' => $data['productCoat'] * $quantity,
//                 'each_cost' => $data['productCoat'],
//                 'price' => $data['productPrice'],
//             ]);
//         }

//         $purchaseProduct = purchaseProduct::where([
//             ['id', '=', $id],
//             ['product_id', '=', $productId],
//             ['purchases_id', '=', $purchasesId],
//             ['price', '=', $price],
//             ['each_cost', '=', $each_cost]
//         ])->first();

//         if ($purchaseProduct) {
//             $purchaseProduct->each_cost = $data['productCoat'];
//             $purchaseProduct->price = $data['productPrice'];
//             $purchaseProduct->save();
//         }

//         $purchaseProductsBadgstock->delete();
//     }

//     $purchase = purchase::find($purchasesId);
//     if ($purchase) {
//         $diffTotalCost = ($data['productCoat'] * $quantity) - $total_cost;
//         $purchase->total_cost += $diffTotalCost;
//         $purchase->save();
//     }

//    $purchaseProductItem = purchaseProductItem::where([
//             ['product_id', '=', $productId],
//             ['price', '=', $price],
//             ['products_badgstock_id', '=', $id],
//             ['branches_id', '=', $branches_id],
//             ['each_cost', '=', $each_cost]
//         ])->first();

//         if($purchaseProductItem){
//             $purchaseProductItem->each_cost = $data['productCoat'];
//             $purchaseProductItem->price = $data['productPrice'];
//             $purchaseProductItem->save();
//         }
// }


public function updateProductItem(Request $request)
{
    $data = $request->all();
    $id = $data['id'];

    $purchaseProductsBadgstock = purchaseProductsBadgstock::find($id);
    if (!$purchaseProductsBadgstock) return;

    $productId = $purchaseProductsBadgstock->product_id;
    $purchasesId = $purchaseProductsBadgstock->purchases_id;
    $each_cost = $purchaseProductsBadgstock->each_cost;
    $total_cost = $purchaseProductsBadgstock->total_cost;
    $price = $purchaseProductsBadgstock->price;
    $branches_id = $purchaseProductsBadgstock->branches_id;
    $quantity = $purchaseProductsBadgstock->quantity;

    // 🔹 Only proceed if cost or price has changed
    if ($price != $data['productPrice'] || $each_cost != $data['productCoat']) {

        $newpurchaseProductsBadgstock = 0;

        // 🔹 Check if stock with new price and cost already exists
        $existingStock = purchaseProductsBadgstock::where([
            ['product_id', '=', $productId],
            ['price', '=', $data['productPrice']],
            ['each_cost', '=', $data['productCoat']],
            ['branches_id', '=', $branches_id],
        ])->first();

        if ($existingStock) {
            // Add quantity to existing stock
            $existingStock->quantity += $quantity;
            $existingStock->total_cost += ($data['productCoat'] * $quantity);
            $existingStock->save();
        } else {
            // Create a new stock entry
            $existingStock = purchaseProductsBadgstock::create([
                'product_id' => $productId,
                'purchases_id' => $purchasesId,
                'quantity' => $quantity,
                'branches_id' => $branches_id,
                'total_cost' => $data['productCoat'] * $quantity,
                'each_cost' => $data['productCoat'],
                'price' => $data['productPrice'],
            ]);
        }

        $newpurchaseProductsBadgstock = $existingStock->id;

        // 🔹 Reduce quantity from old stock
        $purchaseProductsBadgstock->quantity -= $quantity;

        if ($purchaseProductsBadgstock->quantity <= 0) {
            // Check if purchaseProductItem records still reference this stock
            $haspurchaseProductItem = purchaseProductItem::where('products_badgstock_id', $purchaseProductsBadgstock->id)->exists();

            if (!$haspurchaseProductItem) {
                // No related records → safe to delete
                $purchaseProductsBadgstock->delete();
            } else {
                // Related records exist → set qty = 0 and update them to point to new stock
                $purchaseProductsBadgstock->quantity = 0;
                $purchaseProductsBadgstock->total_cost = 0;
                $purchaseProductsBadgstock->save();

               purchaseProductItem::where('products_badgstock_id', $purchaseProductsBadgstock->id)
                    ->update([
                    'products_badgstock_id' => $newpurchaseProductsBadgstock,
                    'each_cost' => $data['productCoat'],
                    'price' => $data['productPrice'],
                ]);


                $purchaseProductsBadgstock->delete();
            }
        } else {
            // Update total cost for remaining quantity
            $purchaseProductsBadgstock->total_cost = $purchaseProductsBadgstock->each_cost * $purchaseProductsBadgstock->quantity;
            $purchaseProductsBadgstock->save();
        }

        // 🔹 Update purchaseProduct table
        $purchaseProduct = purchaseProduct::where([
            ['product_id', '=', $productId],
            ['purchases_id', '=', $purchasesId],
            ['price', '=', $price],
            ['each_cost', '=', $each_cost],
        ])->first();

        if ($purchaseProduct) {
            $purchaseProduct->each_cost = $data['productCoat'];
            $purchaseProduct->price = $data['productPrice'];
            $purchaseProduct->save();
        }

        // 🔹 Update all related purchaseProductItem entries
        purchaseProductItem::where([
            ['product_id', '=', $productId],
            ['price', '=', $price],
            ['products_badgstock_id', '=', $id],
            ['branches_id', '=', $branches_id],
            ['each_cost', '=', $each_cost],
        ])->update([
            'each_cost' => $data['productCoat'],
            'price' => $data['productPrice'],
            'products_badgstock_id' => $newpurchaseProductsBadgstock,
        ]);

        // 🔹 Update purchase total cost
        $purchase = purchase::find($purchasesId);
        if ($purchase) {
            $diffTotalCost = ($data['productCoat'] * $quantity) - $total_cost;
            $purchase->total_cost += $diffTotalCost;
            $purchase->save();
        }
    }
}


}
