<?php

namespace App\Http\Controllers;

use App\Models\Stock;
use App\Models\GrnReturn;
use Illuminate\Http\Request;
use App\Models\GrnReturnHasItem;
use Illuminate\Support\Facades\DB;
use App\Models\GrnReturnHasItemHasStock;

class GrnReturnHasItemHasStockController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $idGrnReturn)
    {

        $grnReturn = GrnReturn::with('item')->find($idGrnReturn); //get grn return data

        //dd($grnReturn);

        if (!$grnReturn->item) { //validate grn returh has item
            return back()->with('warning', 'Sorry! empty grn return item not allow to complete');
        }

        if ($grnReturn->grnReturnStock) { //check grn return item has grn return item has stock data
            return back()->with('warning', 'Sorry! grn return already deducted from stock');
        }

        if ($grnReturn->status == 'Complete') { //check grn return status is complete
            return back()->with('warning', 'Completed GRN return is now allow to complete');
        }



        DB::beginTransaction();
        try {
            //finalize process
            //$isQtyAvaiable = true;

            //dd($grnReturn);

            foreach ($grnReturn->item as $item) { //iterate grn return has item
                //dd($item->id);
                $qtyEachItemInGrnReturnHasItem = GrnReturnHasItem::where('grn_return_id', $idGrnReturn)->where('item_id', $item->item->id)->sum('qty');
                $qtyStockEachItem = Stock::where('branch_id', $grnReturn->branch_id)->where('item_id', $item->id)->sum('qty');
                //dd($qtyStockEachItem);
                if ($qtyEachItemInGrnReturnHasItem > $qtyStockEachItem) { //validate each item total grn return itme qty is not available in the stock

                    //dd($qtyEachItemInGrnReturnHasItem.' - '.$qtyStockEachItem);
                    //$stock_1 =
                    DB::rollBack();
                    return back()->with('warning', 'Stock qty is not available to return.');
                } else { //if stock qty is available to update grn return then execute below

                    //dd('b');
                    $stocks = Stock::where('branch_id', $grnReturn->branch_id)->where('item_id', $item->id)->where('qty', '>', 0)->orderBy('id', 'asc')->get();
                    $grnReturnItemQty = $item->qty; //grn return has item qty

                    foreach ($stocks as $stock) {
                        //$grnReturnHasItemHasQty = 0;
                        //dd('tt'.$item->item_id);
                        $grnReturnHasItemHasStock = [
                            'stock_id' => $stock->id,
                            'grn_return_has_item_id' => $item->item_id,
                        ];

                        //dd('rrrrr');
                        //$stockUpdate = Stock::findOrFail($stock->id);
                        if ($grnReturnItemQty > $stock->qty) {

                         

                            //update stock data
                            $stock->qty = 0;
                            $stock->update();

                            //save grn return has item has tock 
                            $grnReturnHasItemHasStock['qty'] = $stock->qty;
                            $grnReturnHasItemHasStock = GrnReturnHasItemHasStock::create($grnReturnHasItemHasStock);
                            $grnReturnHasItemHasStock->code = 'GRIHS-' . str_pad($grnReturnHasItemHasStock->id, 5, '0', STR_PAD_LEFT);
                            $grnReturnHasItemHasStock->update();
                               $grnReturnItemQty  -=  $stock->qty;
                       
                        } else if ($grnReturnItemQty == $stock->qty) {
                            //$stockUpdate->qty = 0;
                            //$grnReturnItemQty  = 0;

                            //update stock data
                            $stock->qty = 0;
                            $stock->update();


                            //save grn return has item has tock 
                            $grnReturnHasItemHasStock['qty'] = $grnReturnItemQty;
                            $grnReturnHasItemHasStock = GrnReturnHasItemHasStock::create($grnReturnHasItemHasStock);
                            $grnReturnHasItemHasStock->code = 'GRIHS-' . str_pad($grnReturnHasItemHasStock->id, 5, '0', STR_PAD_LEFT);
                            $grnReturnHasItemHasStock->update();
                            break;
                        } else if ($grnReturnItemQty < $stock->qty) {
                            //$stockUpdate->qty = $stock - $item->qty;
                            //$grnReturnItemQty  = 0;


                            //update stock data
                            $stock->qty -= $grnReturnItemQty;
                            $stock->save();


                            //save grn return has item has tock 
                            $grnReturnHasItemHasStock['qty'] = $grnReturnItemQty;
                            $grnReturnHasItemHasStock = GrnReturnHasItemHasStock::create($grnReturnHasItemHasStock);
                            $grnReturnHasItemHasStock->code = 'GRIHS-' . str_pad($grnReturnHasItemHasStock->id, 5, '0', STR_PAD_LEFT);
                            $grnReturnHasItemHasStock->update();

                            break;
                        }

                        //dd('xxxxx');


                    }
                }
            }


            //update grn return has complete
            $grnReturn->status = 'Complete';
            $grnReturn->update();

            DB::commit();
            return redirect('grnReturn/all')->with('success', 'GRN return has updated stock successfully');
        } catch (\Throwable $th) {
            $error = $th->getMessage() . ' - ' . $th->getLine();
            return back()->with('error', $error);
        }


        //return back to grn return list table
    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\GrnReturnHasItemHasStock  $grnReturnHasItemHasStock
     * @return \Illuminate\Http\Response
     */
    public function edit(GrnReturnHasItemHasStock $grnReturnHasItemHasStock)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\GrnReturnHasItemHasStock  $grnReturnHasItemHasStock
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, GrnReturnHasItemHasStock $grnReturnHasItemHasStock)
    {
        //
    }

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