<?php

namespace App\Service\Warehouse;

use App\Models\ShopWarehouseStocks;
use App\Models\WarehouseStock;
use Illuminate\Support\Facades\DB;

class WarehouseShopService
{
    public static function UpdateDataStore($data)
    {

        $data = collect($data);

        //  New Stock Data insert and Update
        foreach ($data['list'] as $key => $value) {
            $existing = ShopWarehouseStocks::where('product_id', $value['product_id'])->where('attribute_id', $value['attribute_id'])->where('shop_id', auth()->user()->shop_id)->first();
            if ($existing) {

                WarehouseStock::where('id', $existing->id)->update([
                    'opening_stock_date' => $data['opening_date'],
                    'opening_stock' => DB::raw('quantity +'.$value['quantity']),
                    'product_id' => $value['product_id'],
                    'attribute_id' => $value['attribute_id'],

                    'quantity' => DB::raw('quantity +'.$value['quantity']),
                    'salse' => (float) str_replace(',', '', $value['salse']),
                    'purchase' => (float) str_replace(',', '', ($existing->purchase_total + ($value['purchase'] * $value['quantity'])) / ($existing->quantity + $value['quantity'])),
                    'salse_total' => (float) str_replace(',', '', ($value['salse']) * ($existing->quantity + $value['quantity'])),
                    'purchase_total' => (float) str_replace(',', '', (($existing->purchase_total + ($value['purchase'] * $value['quantity'])) / ($existing->quantity + $value['quantity'])) * ($existing->quantity + $value['quantity'])),
                ]);
            } else {

                ShopWarehouseStocks::create([
                    'opening_stock_date' => $data['opening_date'],
                    'opening_stock' => (int) $value['quantity'],
                    'shop_id' => auth()->user()->shop_id,
                    'product_id' => $value['product_id'],
                    'attribute_id' => $value['attribute_id'],

                    'quantity' => (int) $value['quantity'],
                    'salse' => (float) str_replace(',', '', $value['salse']),
                    'purchase' => (float) str_replace(',', '', $value['purchase']),
                    'salse_total' => (float) str_replace(',', '', $value['salse'] * $value['quantity']),
                    'purchase_total' => (float) str_replace(',', '', $value['total']),
                ]);
            }
        }
    }
}
