<?php

namespace App\Http\Controllers;

use App\Classes\SMS\StockReminderSms;
use App\Models\Employee;
use App\Models\Item;
use App\Models\StockOut;
use App\Models\Requisition;
use Illuminate\Http\Request;
use App\Models\RequisitionItem;
use App\Models\RequisitionApprove;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use App\Models\RequisitionApproveItem;
use App\Models\SerialNumber;
use Brian2694\Toastr\Facades\Toastr;

class RequisitionApproveController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = RequisitionApprove::paginate('100');
        return view('requisition_approve.index', [
            'page_title' => 'Requisition Approve List',
            'requisition_approves' => $list,
            'url' => route('requisition-approves.create'),
            'add_button' => 'true',
            'class' => 'text-white bg-blue-600',
            'value' => 'Add New Requisition Approve'
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('requisition_approve.create', [
            // 'requisitions' => Requisition::availableRequisitions(),
            'requisitions' => Requisition::where('status', 'Pending')->get(),
            'page_title' => 'Requisition Approval'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //  dd($request->all());
        // $request->validate([
        //     'products' => 'array|required',
        //     'remark' => 'nullable',
        // ]);
        // return back();
        DB::beginTransaction();
        try{
            $requisition_approve = new RequisitionApprove();
            $requisition_approve->requisition_id = $request->requisition_id;
            $requisition_approve->remark = $request->remark;
            $requisition_approve->requisition_approve_number = "RA-" . \App\Classes\RequisitionApproveNumber::serial_number();
            $requisition_approve->creator_user_id = Auth::id();
            $requisition_approve->save();

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

            for($i=0; $i<$len; $i++)
            {
                $item = new RequisitionApproveItem();
                $item->requisition_id = $request->requisition_id;
                $item->requisition_approve_id = $requisition_approve->id;
                $item->item_id = $request->item_id[$i];
                $item->quantity = $request->approve_qty[$i];
                $item->save();
            }

            for($i=0; $i<$len; $i++)
            {
                $stock = new StockOut();
                $stock->requisition_id = $request->requisition_id;
                $stock->requisition_approve_id = $requisition_approve->id;
                $stock->item_id = $request->item_id[$i];
                $stock->quantity = $request->approve_qty[$i];
                $stock->save();
            }

            $requisition =Requisition::find($request->requisition_id);
            $requisition->status ="Approved";
            $requisition->save();

            // $serial_len=sizeof($request->serial);
            // dd($serial_len);
            // for($i=0; $i<$serial_len; $i++)
            // {
            //     dd(gettype($request->serial));
            //     // dd($request->serial[$i]);
            // }

            $employeeName=Employee::where('id',$requisition->employee_id)->first();
            // dd($request->serial);
            if($request->serial){

                foreach($request->serial as $key=>$value)
                {
                    $item_id=$key;
                    // dd($value);
                    foreach($value as $v=>$va)
                    {
                        $serialNumber=SerialNumber::where('id',$va)->first();
                        // dd($v);
                        $serialNumber->status="used";
                        $serialNumber->remark="{$employeeName->name} this employe Take This Serial Number";
                        $serialNumber->requisition_id=$requisition->id;
                        $serialNumber->save();
                    }
                }
            }

            DB::commit();

            $len_itmes = sizeof($request->item_id);

            for($i=0; $i<$len_itmes; $i++)
            {
                $item = Item::with('category','stockIn','stockOut','itemReturn','itemAdjustment')->find($request->item_id[$i]);
                $remaning_stock = $item->stockIn->sum('quantity') - $item->stockOut->sum('quantity') + $item->itemReturn->sum('qty') -  $item->itemAdjustment->sum('quantity');
                $current_quantiy = $item->alert_quantity ?? 0;
                if($remaning_stock < $current_quantiy && $current_quantiy != 0)
                {
                    // (new StockReminderSms())->sendSms($item->id,$current_quantiy);
                }
            }
            $request->session()->flash('success_message', 'Requisition Approved Successful!.');
            return redirect()->route('requisition.index');

        } catch (\Exception $e) {
            dd($e);
            DB::rollBack();
            Toastr::info('Something went wrong!.', '', ["progressbar" => true]);
            return back();
        }




    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\RequisitionApprove  $requisitionApprove
     * @return \Illuminate\Http\Response
     */
    public function show(RequisitionApprove $requisitionApprove)
    {
        return view('requisition_approve.show', [
            'requisitionApprove' => $requisitionApprove,
            'page_title' => 'Requisition Approve Details'
        ]);
    }

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

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\RequisitionApprove  $requisitionApprove
     * @return \Illuminate\Http\Response
     */
    public function destroy(RequisitionApprove $requisitionApprove)
    {
        //
    }
    public function requisitionApprove($id)
    {
        // dd(Requisition::with('items.item.serialNumbers')->find($id));
        return view('requisition.approve', [
            'page_title' => 'Requisition Approve',
            'requisition_id' => $id,
            'requisitions' => Requisition::where('status', 'Pending')->get(),
            'url' => route('requisition.index'),
            'add_button' => 'true',
            'class' => 'btn btn-primary',
            'value' => 'Requisition List',
            'requisition'=>Requisition::with('items.item.serialNumbers')->find($id),
        ]);
    }
    public function getRequisitionByRequisitionId($id)
    {
        $requisition_items = RequisitionItem::with('item')->where('requisition_id', $id)->get();

        $requisition = Requisition::find($id);
        // dd($requisition_items);
        $r_items = $requisition->availableItems();

        foreach ($r_items as $r_item) {
            if ($r_item->quantity > 0) {
                $items[] = [
                    'item_id' => $r_item->item_id,
                    'quantity' => $r_item->quantity,
                    'stock_qty' => \App\Classes\AvailableStockCalculation::item_id($r_item->item_id),
                    'name' => $r_item->item->name,
                    'unit' => $r_item->item->unit->name,
                    'category' => $r_item->item->category->name,
                ];
            }
        }
        // dd($items);
        $data = [
            'items' => $items ?? '',
        ];

        return $data;
    }
}
