<?php

namespace App\Http\Controllers;

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

class GrnReturnController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $grnReturns = GrnReturn::with('branch')
            ->select('grn_returns.*')
            ->withSum('item', 'qty')
            ->selectRaw('(SELECT SUM(qty*unit_price)FROM grn_return_has_items WHERE grn_return_has_items.grn_return_id = grn_returns.id)AS total_sum')
            ->orderBy('id', 'desc')
            ->paginate(10);;
        return view('grnReturn/all', compact('grnReturns'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $branches = branch::all();
        return view('grnReturn/new', compact('branches'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'branch' => 'integer|required|gt:0',
            'date' => 'date|required',
            'vehicle_number' => 'string|nullable',
            'person_name' => 'string|nullable',
            'note' => 'string|nullable:max:200'
        ], [
            'branch.gt' => 'Please select valid branch'
        ]);

        $grnReturn = [
            'vehicle_number' => $request->vehicle_number,
            'date' => $request->date,
            'person_name' => $request->person_name,
            'note' => $request->note,
            'branch_id' => $request->branch,
        ];

        try {

            DB::beginTransaction();

            $grnReturn = GrnReturn::create($grnReturn);
            $grnReturn->code = 'GRNRTN-' . str_pad($grnReturn->id, 5, '0', STR_PAD_LEFT);
            $grnReturn->update();

            DB::commit();
            return back()->with('success', 'GRN Return header data created successfully');
        } catch (\Throwable $th) {
            DB::rollBack();
            return back()->with('error', $th->getMessage());
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\GrnReturn  $grnReturn
     * @return \Illuminate\Http\Response
     */
    public function show(GrnReturn $grn, $idGrnReturn)
    {
        $grnReturn = GrnReturn::with('branch', 'item')->find($idGrnReturn);
        $branches  = branch::all();
        $items = Item::all();
        return view('grnReturn/view', compact('grnReturn', 'branches', 'items'));
        //dd($idGrnReturn);
        //return $grnReturn;
        //return $idGrnReturn;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\GrnReturn  $grnReturn
     * @return \Illuminate\Http\Response
     */
    public function edit(GrnReturn $grnReturn, $idGrnReturn)
    {
        $grnReturn = GrnReturn::with('branch', 'item')->find($idGrnReturn);
        $branches  = branch::all();
        $items = Item::all();
        return view('grnReturn/edit', compact('grnReturn', 'branches', 'items'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\GrnReturn  $grnReturn
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, GrnReturn $grnReturn, $id)
    {
        $request->validate([
            'branch' => 'required|integer|gt:0',
            'date' => 'date|required',
            'vehicle_number' => 'string|nullable|max:20',
            'person_name' => 'string|nullable|max:50',
            'note' => 'string|nullable|max:200'
        ], [
            'branch.gt' => 'Please select valid branch'
        ]);

        DB::beginTransaction();

        $grnReturn = GrnReturn::with('item', 'branch')->find($id);

        $grnReturn->date = $request->date;
        $grnReturn->note = $request->note;
        $grnReturn->vehicle_number = $request->vehicle_number;
        $grnReturn->person_name = $request->person_name;

        //if grn return is processing branch can be edit
        if ($grnReturn->status == 'Processing') {
            $grnReturn->branch_id = $request->branch;
        }

        try {
            $grnReturn->update();
            DB::commit();
            return back()->with('success', 'GRN Return header data update successfully');
        } catch (\Throwable $th) {
            //throw $th;
            DB::rollBack();
            return back()->with('error', $th->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\GrnReturn  $grnReturn
     * @return \Illuminate\Http\Response
     */
    public function destroy(GrnReturn $grnReturn, $id)
    {

        try {

            DB::beginTransaction();
            // dd($id);
            $grnReturn = GrnReturn::with('item')->find($id);
            $grnReturnHasItems = GrnReturnHasItem::where('grn_return_id', $id)->with('grnReturnHasItemHasStock')->get();
            foreach ($grnReturnHasItems as $grnReturnHasItem) {

                foreach ($grnReturnHasItem->grnReturnHasItemHasStock as $grnReturnHasItemHasStock) {
                    // return $grnReturnHasItemHasStock;
                    //$grnReturnHasItemHasStocks = $grnReturnHasItem->grnReturnHasItemHasStock;
                    //view ($grnReturnHasItem);
                    // return $grnReturnHasItem;
                    //$grnReturnHasItemHasStock = $grnReturnHasItem->grnReturnHasItemHasStock;
                    $stock = Stock::findOrFail($grnReturnHasItemHasStock->stock_id);

                    //reverse item to stock
                    $stock->qty += $grnReturnHasItemHasStock->qty;
                    $stock->update();

                    //$grnReturnHasItemHasStock = GrnReturnHasItemHasStock::findOrFail($grnReturnHasItemHasStock->id);
                    $grnReturnHasItemHasStock->delete();
                }
                $grnReturnHasItem->delete();
            }

            //$grnReturnHasItem->grnReturnHasItemHasStock->delete();
            //$grnReturn->item->delete();
            $grnReturn->delete();

            DB::commit();

            return redirect('grnReturn/all')->with('success', 'GRN Return data removed successfully');


            //dd('qqq');
            // if ($grnReturn->item->grnReturnHasItemHasStock->isNotEmpty()) {
            //     dd('data found'.$grnReturn->item);
            // } else {
            //     dd('not found');
            // }
            //get grn return and ghr return has item data
            //if there grn return imte has tock then update stock and then remove it
            //remove grn return has item

            //remove grn rethrn hreadr

            //finalize process
        } catch (\Throwable $th) {
            //throw $th;
            $error = $th->getMessage() . ' - ' . $th->getLine();
            DB::rollBack();
            return back()->with('error', $error);
        }
    }

    public function grnReturnSummery()
    {
        $grnReturns = GrnReturn::with('branch', 'item')
            ->select('grn_returns.*')
            ->withSum('item', 'qty')
            ->selectRaw('(SELECT SUM(qty*unit_price)FROM grn_return_has_items WHERE grn_return_has_items.grn_return_id = grn_returns.id)AS total_sum')
            ->orderBy('id', 'desc')->paginate(1);
        return view('reports/grnReturnSummery', compact('grnReturns'));
        //return $grnReturns;
    }
}
