<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Employee;
use App\Models\Item;
use App\Models\ItemCategory;
use App\Models\ItemReturn;
use App\Models\ItemReturnItem;
use App\Models\SerialNumber;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ItemReturnController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data=[
            'itemReturns'=>ItemReturn::with('item','employee','branch','recivedUser')->get(),
        ];
        // dd($data);
        return view('itemReturn.index',$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $data=[
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'employees' => Employee::where('status',"active")->get(),
        ];
        return view('itemReturn.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();
            $itemReturn = new ItemReturn();
            $itemReturn->date= $date;
            $itemReturn->employee_id = $request->employee_id;
            $itemReturn->branch_id = $request->branch_id;
            $itemReturn->recived_user_id = auth()->user()->id;
            $itemReturn->reason = $request->reason;
            $itemReturn->serial_add_or_not = $request->serilNumberAddorNot;
            $itemReturn->save();

            $employeeName=Employee::where('id',$request->employee_id)->first();

            $len=sizeof($request->productId);
            for($i=0;$i<$len;$i++)
            {
                $itemReturnItem= new ItemReturnItem();
                $itemReturnItem->item_retern_id = $itemReturn->id;
                $itemReturnItem->item_id = $request->productId[$i];
                $itemReturnItem->qty = $request->qty[$i];
                $itemReturnItem->serial_no = $request->serialNumber[$i];
                $itemReturnItem->save();

                $tempProduct=Item::find($request->productId[$i]);
                if($tempProduct->serial_number=="enable")
                {
                    if($request->serilNumberAddorNot=="yes"){
                        $serialNumbers = explode(",", $request->serialNumber[$i]);
                        foreach($serialNumbers as $key=>$value){
                            $tempSerialNumber=SerialNumber::where('item_id',$request->productId[$i])->where('serial_no',$value)->where('status',"used")->first();
                            if($tempSerialNumber){
                                $tempSerialNumber->status="notused";
                                $tempSerialNumber->remark="{$employeeName->name} return this Item";
                                $tempSerialNumber->item_return_id=$itemReturnItem->id;
                                $tempSerialNumber->save();
                            }else{

                                Toastr::error("{$value} This serial Number is not Found or previously not used");
                                return back();
                            }
                        }
                    }else{
                        $serialNumbers = explode(",", $request->serialNumber[$i]);
                        foreach($serialNumbers as $key=>$value){
                            $checkSerialNumer=SerialNumber::where('item_id',$request->productId[$i])->where('serial_no',$value)->first();
                            if($checkSerialNumer){

                                Toastr::error("{$value} This serial Number is already Exist");
                                return back();
                            }else{
                                $serialNo= new SerialNumber();
                                $serialNo->item_id=$request->productId[$i];
                                $serialNo->item_return_id=$itemReturnItem->id;
                                $serialNo->serial_no=$value;
                                $serialNo->status="notused";
                                $serialNo->save();

                            }
                        }
                    }

                }


            }
            DB::commit();
            Toastr::success("ItemReturn Successfull");
            return back();

        } catch (\Exception $ex)
        {
            DB::rollback();
            dd($ex);
        }

    }

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\ItemReturn  $itemReturn
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // dd('Edit');
        $itemReturn=ItemReturn::with('item.product','employee')->find($id);
        if (!isset($itemReturn->employee)){
            Toastr::error("This return Form CRM You Can not edit this");
            return redirect()->back();
        }
        $data=[
            'itemReturn'=>$itemReturn,
            'categories' => ItemCategory::all(),
            'branches' => Branch::all(),
            'employees' => Employee::where('status',"active")->get(),
        ];
        // dd($data);
        return view('itemReturn.edit',$data);
    }

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

            $itemReturn=ItemReturn::with('item')->find($request->id);
            foreach($itemReturn->item as $value)
            {
                $serialNumbers = explode(",", $value->serial_no);
                foreach($serialNumbers as $s_no){
                    $temp=SerialNumber::where('serial_no',$s_no)->first();
                    if($temp->status=="used")
                    {
                        Toastr::error("you Can not Edit Because {$s_no} already Use");
                        return back();
                    }
                }
            }

            $date = today();
            $itemReturn->date= $date;
            $itemReturn->employee_id = $request->employee_id;
            $itemReturn->branch_id = $request->branch_id;
            $itemReturn->recived_user_id = auth()->user()->id;
            $itemReturn->reason = $request->reason;
            $itemReturn->serial_add_or_not = $request->serilNumberAddorNot;
            $itemReturn->save();
            ItemReturnItem::where('item_retern_id',$request->id)->delete();
            SerialNumber::where('item_retern_id',$request->id)->delete();
            dd('come');

            $employeeName=Employee::where('id',$request->employee_id)->first();

            $len=sizeof($request->productId);
            for($i=0;$i<$len;$i++)
            {
                $itemReturnItem= new ItemReturnItem();
                $itemReturnItem->item_retern_id = $itemReturn->id;
                $itemReturnItem->item_id = $request->productId[$i];
                $itemReturnItem->qty = $request->qty[$i];
                $itemReturnItem->serial_no = $request->serialNumber[$i];
                $itemReturnItem->save();

                $tempProduct=Item::find($request->productId[$i]);
                if($tempProduct->serial_number=="enable")
                {
                    if($request->serilNumberAddorNot=="yes"){
                        $serialNumbers = explode(",", $request->serialNumber[$i]);
                        foreach($serialNumbers as $key=>$value){
                            $tempSerialNumber=SerialNumber::where('item_id',$request->productId[$i])->where('serial_no',$value)->where('status',"used")->first();
                            if($tempSerialNumber){
                                $tempSerialNumber->status="notused";
                                $tempSerialNumber->remark="{$employeeName->name} return this Item";
                                $tempSerialNumber->save();
                            }else{

                                Toastr::error("{$value} This serial Number is not Found or previously not used");
                                return back();
                            }
                        }
                    }else{
                        $serialNumbers = explode(",", $request->serialNumber[$i]);
                        foreach($serialNumbers as $key=>$value){
                            $checkSerialNumer=SerialNumber::where('item_id',$request->productId[$i])->where('serial_no',$value)->first();
                            if($checkSerialNumer){

                                Toastr::error("{$value} This serial Number is already Exist");
                                return back();
                            }else{
                                $serialNo= new SerialNumber();
                                $serialNo->item_id=$request->productId[$i];
                                $serialNo->serial_no=$value;
                                $serialNo->status="notused";
                                $serialNo->save();

                            }
                        }
                    }

                }


            }


            DB::commit();
            Toastr::success("ItemReturn Update Successfull");
            return redirect(route('item-return.index'));


        }catch (\Exception $e){
            DB::rollback();
            dd($e);
        }

    }

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

    public function getItem(Request $request)
    {
        $items=Item::where('category_id',$request->data)->get();
        return $items;
    }
}
