<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\ItemCategory;
use App\Models\SerialNumber;
use App\Models\StockAdjustment;
use App\Models\StockAdjustmentItem;
use App\Models\StockAdjustmentType;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class StockAdjustmentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data=[
            'adjustments'=>StockAdjustment::with('type','adjustmentItems')->get(),
        ];
        return view('adjustment.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data=[
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'adjustment_types'=>StockAdjustmentType::get(),
        ];
        return view('adjustment.create',$data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        DB::beginTransaction();
        try{
            $date= today();
            $stockAdjustment= New StockAdjustment();
            $stockAdjustment->stock_adjustment_type_id=$request->type_id;
            $stockAdjustment->creator_user_id=auth()->id();
            $stockAdjustment->reason=$request->reason;
            $stockAdjustment->date=$date;
            $stockAdjustment->save();

            $typeName=StockAdjustmentType::find($request->type_id);

            $len=sizeof($request->productId);

            for($i=0;$i<$len;$i++){
                $stockAdjustmentItem= new StockAdjustmentItem();
                $stockAdjustmentItem->stock_adjustment_id= $stockAdjustment->id;
                $stockAdjustmentItem->item_id= $request->productId[$i];
                $stockAdjustmentItem->quantity= $request->qty[$i];
                $stockAdjustmentItem->serial_no= $request->serialNumber[$i];
                $stockAdjustmentItem->save();




                if($request->serialNumber[$i]){

                    $serialNumbers = explode(",", $request->serialNumber[$i]);

                    foreach($serialNumbers as $key=>$serialNo){
                        $tempSerialNo= SerialNumber::where('serial_no',$serialNo)->where('item_id',$request->productId[$i])->first();
                        if($tempSerialNo){
                            if($tempSerialNo->status=="used"){
                                Toastr::error("{$serialNo} Serial Number already In Use");
                                return back();
                            }else{

                                $tempSerialNo->status="used";
                                $tempSerialNo->remark="used because of {$typeName->name} type adjustment";
                                $tempSerialNo->save();
                            }
                        }else{
                            Toastr::error("{$serialNo} Serial No Not Found");
                            return back();
                        }
                    }
                }
            }



            DB::commit();
            Toastr::success("Stock Adjustment Successfuly Added");
            return redirect(route('adjustment.index'));
        }catch (\Exception $e)
        {
            DB::rollBack();
            dd($e);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\StockAdjustment  $stockAdjustment
     * @return \Illuminate\Http\Response
     */
    public function show(StockAdjustment $stockAdjustment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\StockAdjustment  $stockAdjustment
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data=[
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'adjustment_types'=>StockAdjustmentType::get(),
            'adjustment'=>StockAdjustment::with('adjustmentItems.product')->find($id),
        ];
        // dd($data);
        return view('adjustment.edit',$data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\StockAdjustment  $stockAdjustment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, StockAdjustment $stockAdjustment)
    {
        // dd($request->all());
        DB::beginTransaction();
        try{

            $itemOfStockAdjustment= StockAdjustmentItem::where('stock_adjustment_id',$request->id)->get();
            foreach($itemOfStockAdjustment as $key=>$value)
            {
                $serila_no=$value->serial_no;
                $numbers = explode(",", $serila_no);
                foreach($numbers as $num){
                    $tempSerialNumber=SerialNumber::where('item_id',$value->item_id)->where('serial_no',$num)->first();
                    if($tempSerialNumber){
                        $tempSerialNumber->status="notused";
                        $tempSerialNumber->remark="";
                        $tempSerialNumber->save();

                    }
                }
            }

            $date= today();
            $stockAdjustment= StockAdjustment::find($request->id);
            $stockAdjustment->stock_adjustment_type_id=$request->type_id;
            $stockAdjustment->creator_user_id=auth()->id();
            $stockAdjustment->reason=$request->reason;
            $stockAdjustment->date=$date;
            $stockAdjustment->save();

            $typeName=StockAdjustmentType::find($request->type_id);

            $itemOfStockAdjustment= StockAdjustmentItem::where('stock_adjustment_id',$request->id)->delete();

            $len=sizeof($request->productId);

            for($i=0;$i<$len;$i++){
                $stockAdjustmentItem= new StockAdjustmentItem();
                $stockAdjustmentItem->stock_adjustment_id= $stockAdjustment->id;
                $stockAdjustmentItem->item_id= $request->productId[$i];
                $stockAdjustmentItem->quantity= $request->qty[$i];
                $stockAdjustmentItem->serial_no= $request->serialNumber[$i];
                $stockAdjustmentItem->save();



                if($request->serialNumber[$i]){

                    $serialNumbers = explode(",", $request->serialNumber[$i]);

                    foreach($serialNumbers as $key=>$serialNo){
                        $tempSerialNo= SerialNumber::where('serial_no',$serialNo)->where('item_id',$request->productId[$i])->first();
                        if($tempSerialNo){
                            if($tempSerialNo->status=="used"){
                                Toastr::error("{$serialNo} Serial Number already In Use");
                                return back();
                            }else{

                                $tempSerialNo->status="used";
                                $tempSerialNo->remark="used because of {$typeName->name} type adjustment";
                                $tempSerialNo->save();
                            }
                        }else{
                            Toastr::error("{$serialNo} Serial No Not Found");
                            return back();
                        }
                    }
                }
            }


            DB::commit();
            Toastr::success("Adjustment Update Successful");
            return redirect(route('adjustment.index'));
        }catch (\Exception $e){
            DB::rollBack();
            dd($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\StockAdjustment  $stockAdjustment
     * @return \Illuminate\Http\Response
     */
    public function destroy(StockAdjustment $stockAdjustment)
    {
        //
    }
}
