<?php

namespace App\Http\Controllers\inventory;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\stores;
use App\Models\Product;
use App\Models\Unit;

use App\Models\storestocklevel;
use App\Models\adjustmentQty;

use DB;
use auth;


class adjustment extends Controller
{
    public function index(){
        $stores = stores::all();

        return view('inventory.adjustment.index',compact('stores'));
    }


    public function products(int $store){
        $store = stores::find($store);
        $products = Product::all();
        return view('inventory.adjustment.products',compact('store','products'));
    }

    public function product(int $store,int $product){
        $histories = DB::SELECT("SELECT * FROM inv_adjustment WHERE product = ?",[$product]);

        $store = stores::find($store);
        $product = Product::find($product);
        $unit = Unit::find($product->SellingUnit);
        return view('inventory.adjustment.product',compact('store','product','unit','histories'));
    }


    public function save(Request $request,int $store,int $product){
        $adjustmentQty = new adjustmentQty();

       // $adjustmentQty->store = $store;
        $adjustmentQty->product = $product;
        $adjustmentQty->applydate = date('Y-m-d');
        $adjustmentQty->type = 0;
        $adjustmentQty->quantity = $request->quantity;
        $adjustmentQty->unit = 0;
        $adjustmentQty->remarks = 'Change in stock value';
        $adjustmentQty->userid = auth()->user()->id;


        $adjustmentQty->save();





        if(storestocklevel::SELECT('*')->WHERE('StoreCtrlNum',$store)->WHERE('ItemCtrlNum',$product)->exists()){
            $storestocklevel = storestocklevel::SELECT('*')->WHERE('StoreCtrlNum',$store)->WHERE('ItemCtrlNum',$product)->first();
            $storestocklevel->Quantity = $request->quantity;
            $storestocklevel->update();
        }else {
            $storestocklevel = new storestocklevel();

            $storestocklevel->StoreCtrlNum = $store;
            $storestocklevel->ItemCtrlNum = $product;
            $storestocklevel->Quantity = $request->quantity;
            $storestocklevel->save();
        }
        
        DB::table("stocklevels")->where(['ItemCtrlNum' => $product])->update(['Quantity' => storestocklevel::WHERE('ItemCtrlNum',$product)->sum('Quantity')]);
        
        
       // DB::SELECT("UPDATE stocklevels SET Quantity = ? WHERE ItemCtrlNum = ? ",[storestocklevel::WHERE('ItemCtrlNum',$product)->sum('Quantity'),$product]);

        return redirect()->route('inventory.products',[$store]);
    }
}
